Java – Share intents take a long time to appear

Share intents take a long time to appear… here is a solution to the problem.

Share intents take a long time to appear

I’m trying to include image sharing in my app and everything works fine, but the share selector takes a long time to appear on the device

Here’s what I’m doing :

I

have ImageView “items_details_image” and I want to share an image of it to be able to send it via 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’s how I get a bitmap from an 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 takes longer than usual to compare it with other apps on the same device, such as gallery or other apps

Solution

You are performing disk I/O on the main application thread, in getLocalBitmapUri(). Whenever you write a bitmap to disk, this will jam your UI.

Related Problems and Solutions