如何截取当前活动的屏幕截图然后分享? [英] How to take a screenshot of a current Activity and then share it?
问题描述
我需要截取 Activity
的屏幕截图(没有标题栏,用户不应看到实际已截取的屏幕截图),然后通过操作菜单按钮共享"进行共享.我已经尝试了一些解决方案,但它们对我不起作用.有什么想法吗?
I need to take a screenshot of Activity
(without the title bar, and the user should NOT see that a screenshot has actually been taken) and then share it via an action menu button "share". I have already tried some solutions, but they didn't work for me. Any ideas?
推荐答案
这就是我截取屏幕并分享的方式.
This is how I captured the screen and shared it.
首先,从当前活动获取根视图:
First, get root view from current activity:
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
其次,捕获根视图:
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
第三,将Bitmap
存入SDCard:
Third, store the Bitmap
into the SDCard:
public static void store(Bitmap bm, String fileName){
final static String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if(!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
最后,分享一下当前Activity
的截图:
At last, share the screenshot of current Activity
:
private void shareImage(File file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No App Available", Toast.LENGTH_SHORT).show();
}
}
我希望你能从我的代码中得到启发.
I hope you will be inspired by my codes.
更新:
将以下权限添加到您的 AndroidManifest.xml
中:
Add below permissions into your AndroidManifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
因为它创建和访问外部存储中的文件.
Because it creates and accesses files in external storage.
更新:
从 Android 7.0 Nougat 开始,禁止共享文件链接.要解决这个问题,您必须实现 FileProvider 并共享content://"uri 而不是file://"uri.
Starting from Android 7.0 Nougat sharing file links are forbiden. To deal with this you have to implement FileProvider and share "content://" uri not "file://" uri.
此处很好地说明了如何操作.
Here is a good description how to do it.
这篇关于如何截取当前活动的屏幕截图然后分享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!