I am making an application in Android in which I have to take screenshot of one of my activities and mail it as attachment.
I want to take screenshot of the current
I wanted mine in the action bar so I created a share_menu.xml file:
This adds a button in the action bar with my share_icon and the text.
I did this inside a fragment so I added the code below to my fragment file. If you are inside an activity then you override public boolean onCreateOptionsMenu(Menu menu) instead.
@Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.share_menu, menu);
}
if you are doing this with a fragment then in onCreate() you have to add:
setHasOptionsMenu(true);
This is what is going to kick off the sharing.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.share_item){
Bitmap bm = screenShot(this.getView());
File file = saveBitmap(bm, "mantis_image.png");
Log.i("chase", "filepath: "+file.getAbsolutePath());
Uri uri = Uri.fromFile(new File(file.getAbsolutePath()));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Check out my app.");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "share via"));
}
return super.onOptionsItemSelected(item);
}
Notice this calls two magic methods:
screenShot():
private Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
private static File saveBitmap(Bitmap bm, String fileName){
final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 90, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
To your AndroidManifest.xml, you have to add:
or the screenshot won't be saved, and gmail will think you are trying to attach an empty file.
Also, a lot of SO answers say to use "*/*" for shareIntent.setType() but this creates an issue with facebook sharing, so it's best to leave it as "image/*".