Skip to content

Instantly share code, notes, and snippets.

@Mun0n
Created March 24, 2015 08:12
Show Gist options
  • Save Mun0n/d2bee6c76ee7e34d7155 to your computer and use it in GitHub Desktop.
Save Mun0n/d2bee6c76ee7e34d7155 to your computer and use it in GitHub Desktop.
Android share image and text via intent with ShareActionProvider, using action button.
File shareFile;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_editor, menu);
ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menu.findItem(R.id.action_share));
shareActionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
shareActionProvider.setShareIntent(getDefaultShareIntent());
shareActionProvider.setOnShareTargetSelectedListener(new ShareActionProvider.OnShareTargetSelectedListener() {
@Override
public boolean onShareTargetSelected(ShareActionProvider shareActionProvider, Intent intent) {
saveImageToTemp();
return false;
}
});
private Intent getDefaultShareIntent() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_text));
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FileUtils.DEFAULT_FOLDER);
shareFile = new File(/*Put the File path, it doesn't need to exist*/);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(shareFile));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
return intent;
}
private void saveImageToTemp() {
/*I create a photo file from one of my RelativeLayout, change this for your image source*/
RelativeLayout photoLayout = (RelativeLayout) findViewById(R.id.resultPhoto);
photoLayout.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(photoLayout.getDrawingCache());
photoLayout.setDrawingCacheEnabled(false);
try {
shareFile.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(shareFile);
fos.write(bitmapdata);
fos.flush();
fos.close();
ImageUtils.refresGallery(EditorActivity.this, shareFile);
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment