I am trying to provide a share feature on the cards displayed in my android application. I have learn't about the ShareactionProvider. This actionProvider is suppose to be present on every cardview. I have placed the code for the ShareActionprovider on my onBindViewHolder in the Adapter. When the app starts, all the cards execute their share at the same time. I will like to call this share only when the user requests.
@Override
public void onBindViewHolder(final ViewHolder viewHolder, final Cursor cursor) {
final NewsFacade facade = NewsFacade.fromCursor(cursor);
MenuItem shareMenuItem = viewHolder.toolbar.getMenu().findItem(R.id.share);
ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareMenuItem);
shareActionProvider.setShareIntent(viewHolder.sendShareIntent(facade, context));
shareActionProvider.setShareHistoryFileName("custom_share_history.xml");
And Here are the Helper Methods to aid in the sharing:
public Intent sendShareIntent(NewsFacade facade, Context context)
{
saveImageToCache(facade, context);
return shareImage(context);
}
private void saveImageToCache(NewsFacade facade, Context context)
{
try {
Bitmap bitmap = facade.getThumb();
File cachePath = new File(context.getCacheDir(), "images");
cachePath.mkdirs();
FileOutputStream stream = new FileOutputStream(cachePath + "/image.png"); // overwrites this image every time
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Intent shareImage(Context context)
{
File imagePath = new File(context.getCacheDir(), "images");
File newFile = new File(imagePath, "image.png");
Uri contentUri = FileProvider.getUriForFile(context, "com.example.clinton.companion.fileprovider", newFile);
if (contentUri != null) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
shareIntent.setDataAndType(contentUri,context.getContentResolver().getType(contentUri));
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
context.startActivity(Intent.createChooser(shareIntent, "Choose an app"));
return shareIntent;
}
return null;
}
I know, I am calling the ActionProvider in the wrong place. But where else, should I call this, I need an instance of the object that cardview holds, so I can get the image in the cardview to share.
Please any help will be apreciated.
I fixed it. I was calling
context.startActivity(Intent.createChooser(shareIntent, "Choose an app"));
which automatically executes the sharing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.