Pergunta

I' m using Picasso to help the cache of images.

The question is, how can I access the downloaded image to make a share intent?

any ideas? thanks!

Foi útil?

Solução

I hope you can understand my question :-)

Sorry for my delay, I found a solution, but, not a good one...

First, I really searched for a while and looked at the code of Picasso. It seems like you should provide your own downloader and other stuff. But then, why should I use the lib...

And then, I suppose it's Picasso's design / architecture to just cache the file in the internal storage. Maybe because the external storage is not always available (like the user may plug in his SD card to his computer), or maybe because the external storage is not as fast as the internal... That's my guess. In a word, other apps cannot access the internal storage of the current app, so the share cannot be done.

Thus, I made a really ordinary solution. I just wait for Picasso to give the Bitmap, and compress it to a file in the external file, then do the share. It seems like a bad solution, but it really solves the problem, yes...

You should be aware of whether the external cache directory is available or not. If not, you cannot do the share. And you need to put the compress task in a background thread, so, waiting the external file cached... Does it seem like a bad solution? I think so...

Below is my project code, you can have a try...

private boolean mSaved; // a flag, whether the image is saved in external storage
private MenuItem mShare;
private Intent mIntent;
private ShareActionProvider mShareActionProvider;
private File mImage; // the external image file would be saved...


private Target target = new Target() {
    @Override
    public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileOutputStream os = null;
                try {
                    String dir = CatnutUtils.mkdir(getActivity(), Constants.FANTASY_DIR); // check the exteral dir avaiable or not...
                    String[] paths = Uri.parse(mUrl).getPath().split("/");
                    mImage = new File(dir + File.separator + paths[2] + Constants.JPG); // resoleve the file name
                } catch (Exception e) { // the external storage not available...
                    Log.e(TAG, "create dir error!", e);
                    return;
                }
                try {
                    if (mImage.length() > 10) { // > 0 means the file exists
                        // the file exists, done.
                        mIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mImage));
                        mSaved = true;
                        return;
                    }
                    os = new FileOutputStream(mImage);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                    mIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mImage));
                    mSaved = true;
                } catch (FileNotFoundException e) {
                    Log.e(TAG, "io error!", e);
                } finally {
                    if (os != null) {
                        try {
                            os.close();
                        } catch (IOException e) {
                            Log.e(TAG, "io closing error!", e);
                        }
                    }
                }
            }
        }).start();
        mFantasy.setImageBitmap(bitmap);
    }
@Override
    public void onBitmapFailed(Drawable errorDrawable) {
        mFantasy.setImageDrawable(errorDrawable);
    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {
        if (placeHolderDrawable != null) {
            mFantasy.setImageDrawable(placeHolderDrawable);
        }
    }
};

@Override
public void onPrepareOptionsMenu(Menu menu) {
    mShare.setEnabled(mSaved);
}

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.fantasy, menu);
    mShare = menu.findItem(R.id.action_share);
    mShareActionProvider = (ShareActionProvider) mShare.getActionProvider();
    mShare.setActionProvider(mShareActionProvider);

    mShareActionProvider.setShareIntent(mIntent);
}

Finally, call Picasso.with(getActivity()).load(mUrl).into(target);

When the file is saved, the user can click the share menu do the share.

Outras dicas

public static File getImageFile(Context context, String url)
{
    final String CACHE_PATH = context.getCacheDir().getAbsolutePath() + "/picasso-cache/";

    File[] files=new File(CACHE_PATH).listFiles();
    for (File file:files)
    {
        String fname= file.getName();
        if (fname.contains(".") && fname.substring(fname.lastIndexOf(".")).equals(".0"))
        {
            try
            {
                BufferedReader br=new BufferedReader(new FileReader(file));
                if (br.readLine().equals(url))
                {
                    File imgfile= new File(CACHE_PATH + fname.replace(".0", ".1"));     

                    if (imgfile.exists())
                    {
                        return imgfile;
                    }
                }
            }
            catch (FileNotFoundException|IOException e)
            {
            }
        }
    }
    return null;
}

I've just found out this guide with a very good solution.

https://guides.codepath.com/android/Sharing-Content-with-Intents

The code will be like this:

// Can be triggered by a view event such as a button press
public void onShareItem(View v) {
    // Get access to bitmap image from view
    ImageView ivImage = (ImageView) findViewById(R.id.ivResult);
    // Get access to the URI for the bitmap
    Uri bmpUri = getLocalBitmapUri(ivImage);
    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
    }
}

// Returns the URI path to the Bitmap displayed in specified ImageView
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;
}

It basically consists in retrieving the bitmap from the imageview and saving it to a local temp file and then using it for sharing. I've tested it and it seems to work fine.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top