我从互联网上获取此代码以捕获当前活动的屏幕。
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
Bitmap bitmap = rootView.getDrawingCache();
String str = new SimpleDateFormat("MM_dd_yyyy_HH_mm_ss").format(Calendar.getInstance().getTime()) + ".jpg";
File imagePath = new File(Environment.getExternalStorageDirectory() , str);
Log.i("catpure", "" + Environment.getExternalStorageDirectory() );
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
我也试过不同的代码。没有什么对我有用。 logcat中没有错误。代码运行时没有任何错误,但仍然没有保存图像。请让我知道我错在哪里。提前谢谢。
============================================ ==================================
修改
我检查了我的代码和错误日志。表明 :
Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied).
但我有
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
AndroidManifest.xml中的。
有什么问题?请帮忙。
============================================ =============================
更新 这是一个Android 5问题:
答案 0 :(得分:1)
此函数将返回当前活动的位图。所以你必须存储,如果你想稍后使用,或者如果你想在同一个应用程序中,那么你可以使用位图对象
public static Bitmap captureScreenshot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
Rect rect = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
@SuppressWarnings("deprecation")
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
@SuppressWarnings("deprecation")
int height = activity.getWindowManager().getDefaultDisplay().getHeight();
Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return bitmap2;
}
这是保存位图的功能:
private void saveImagetoSDCard(Bitmap bitmap)
{
Bitmap bit=takeScreenshot(DisplayImage.this);
try
{
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath();
File storagePath = new File(Environment.getExternalStorageDirectory() + "/MyCameraApp/");
file = new File(storagePath, "Yudiz_krrish.png");
Log.d("TAG","File path after editing :"+file.getPath().toString());
FileOutputStream fOut = null;
fOut = new FileOutputStream(file);
bit.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
btn_changeSettiong.setVisibility(View.VISIBLE);
btn_saveImage.setVisibility(View.VISIBLE);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}