3

I'm trying to include image sharing in my application and everything is working but the share chooser takes long time to appear on devices

here is what i'm doing:

I have ImageView "items_details_image" and I want to share its image to be able to send it through whatsapp and other apps

void ShareImg() {
    try {
        Uri bmpUri = getLocalBitmapUri(items_details_image);
        if (bmpUri != null) {
            // Construct a ShareIntent with link to image
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
            shareIntent.setType("image/*");
            // Launch sharing dialog for image
            startActivity(Intent.createChooser(shareIntent, "Share Image"));
        } else {
            // ...sharing failed, handle error
        }
    } catch (Exception e) {

    }
}

here is how I get bitmap from Image URL

public Uri getLocalBitmapUri(ImageView imageView) {
    // Extract Bitmap from ImageView drawable
    Drawable drawable = imageView.getDrawable();
    Bitmap bmp = null;
    if (drawable instanceof BitmapDrawable){
        bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    } else {
        return null;
    }
    // Store image to default external storage directory
    Uri bmpUri = null;
    try {
        File file =  new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
        file.getParentFile().mkdirs();
        FileOutputStream out = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.close();
        bmpUri = Uri.fromFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bmpUri;
}

I don't know why it is taking longer than usual comparing it with other apps on the same device such as gallery or whatever

Yazan Allahham
  • 174
  • 2
  • 17

1 Answers1

3

You are doing disk I/O on the main application thread, in getLocalBitmapUri(). This will freeze your UI as long as it takes to write your bitmap to disk.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • so should i make an asynctask to maintain the getLocalBitmapUri ? – Yazan Allahham Apr 11 '17 at 19:12
  • 3
    @YazanAllahham: Even better would be to do something else. This `ImageView` got its image from somewhere. If that "somewhere" already exists at a `Uri`-reachable location, just use the original source of the image. – CommonsWare Apr 11 '17 at 19:19
  • 1
    Wooow ! that was fantastic ! Thank you. since I'm using UniversalImageLoader I could have the Image Uri in the onLoadingComplete event of the ImageLoader! ... you saved me hourss !!! – Yazan Allahham Apr 11 '17 at 19:41