viernes, 25 de noviembre de 2016

Compartir Imagen desde una App en Android




Compartir Imagen desde una App en Android

Hola a todos, hoy les traigo un tutorial de como compartir imágenes desde un aplicativo nativo en android a pedido de un comentario en este blog.

El codigo fuente inicial viene de un post anterior llamado: Compartir en redes sociales en Android Studio

Se agrego codigo fuente extra.

1. Agregue 2 widgets en activity_main.xml

  android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="Foto"    android:id="@+id/foto"    android:layout_alignParentTop="true"    android:layout_centerHorizontal="true" />
    android:layout_width="match_parent"    android:layout_height="match_parent"    android:id="@+id/imgfoto"    android:scaleType="centerCrop"    android:layout_below="@+id/foto"    android:layout_centerHorizontal="true"    android:layout_above="@+id/buttonShare" />


2. Agregue las constantes a usar en MainActivity.java

//Constantes para subir foto
private static String APP_DIRECTORY = "MyPictureApp/";private static String MEDIA_DIRECTORY = APP_DIRECTORY + "PictureApp";
private final int MY_PERMISSIONS = 100;private final int PHOTO_CODE = 200;private final int SELECT_PICTURE = 300;
private ImageView mSetImage;private Button mOptionButton;
private String mPath;


3. en el metodo onCreate agregue:
mOptionButton = (Button) findViewById(R.id.foto);mSetImage = (ImageView) findViewById(R.id.imgfoto);
//ahora le asignamos la accion a relizar a los botonesmOptionButton.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        showOptions();    }
});



4. ahora agregamos estas funciones  en el Activity

@Overridepublic void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);    outState.putString("file_path", mPath);}

@Overrideprotected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    mPath = savedInstanceState.getString("file_path");}

@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_OK){
        switch (requestCode){
            case PHOTO_CODE:
                MediaScannerConnection.scanFile(this,                        new String[]{mPath}, null,                        new MediaScannerConnection.OnScanCompletedListener() {
                            @Override                            public void onScanCompleted(String path, Uri uri) {
                                Log.i("ExternalStorage", "Scanned " + path + ":");                                Log.i("ExternalStorage", "-> Uri = " + uri);                            }
                        });

                Bitmap bitmap = BitmapFactory.decodeFile(mPath);                mSetImage.setImageBitmap(bitmap);                break;            case SELECT_PICTURE:
                Uri path = data.getData();                mSetImage.setImageURI(path);                break;
        }
    }
}

@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == MY_PERMISSIONS){
        if(grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
            Toast.makeText(MainActivity.this, "Permisos aceptados", Toast.LENGTH_SHORT).show();            mOptionButton.setEnabled(true);        }
    }else{
        showExplanation();    }
}

private void showExplanation() {
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);    builder.setTitle("Permisos denegados");    builder.setMessage("Para usar las funciones de la app necesitas aceptar los permisos");    builder.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
        @Override        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent();            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);            Uri uri = Uri.fromParts("package", getPackageName(), null);            intent.setData(uri);            startActivity(intent);        }
    });    builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
        @Override        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();            finish();        }
    });
    builder.show();}
5. Agregamos este codigo en el boton de compartir y especifican si desean una red social especifica
mSetImage.buildDrawingCache();Bitmap bitmap = mSetImage.getDrawingCache();
/***** COMPARTIR IMAGEN *****/try {
    File file = new File(getCacheDir(), bitmap + ".png");    FileOutputStream fOut = null;    fOut = new FileOutputStream(file);    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);    fOut.flush();    fOut.close();    file.setReadable(true, false);    final Intent intent = new Intent(android.content.Intent.ACTION_SEND);    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));    intent.setType("image/png");    startActivity(intent);} catch (Exception e) {
    e.printStackTrace();}
6. Agregamos los permisos en el Manifest.
android:name="android.permission.CAMERA"/>android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>android:name="android.permission.READ_EXTERNAL_STORAGE"/>android:name="android.intent.action.MEDIA_MOUNTED"/>
Codigo fuente aqui.
https://bitbucket.org/mchiuyari/compartiendoredessociales
Video.
 

3 comentarios:

  1. ¿Esto podemos hacerlo con html? Nuestra app se ha construido en html al completo, y cuando ha sido necesario css y js. No nos funcionan lo splugins de compartir en redes sociales tipo addtoany o addthis.
    Muchas gracias a todos.

    ResponderEliminar
  2. todo bien pero en sistemas android 7 no corre

    ResponderEliminar
  3. It's true. This freelancing is a good opportunity for the experts in Android application development. I have been working at an in-house job for the last three years as an android developer, but I am looking for a second source of income. Therefore, I think I can work as a freelancer side-by-side. Can you help me find a good platform to work with for the long term?

    ResponderEliminar