Android - 没有截屏当前屏幕

时间:2015-05-04 13:08:37

标签: android

代码适用于第一个屏幕截图,并且无论移动到另一个视图,都可以保持相同的屏幕截图。

如何获取当前截图?

public void saveBitmap(Bitmap bitmap) {

    File imagePath = new File(Environment.getExternalStorageDirectory() + "/" + new SimpleDateFormat("yyyyMMddhhmmss'.jpg'").format(new Date()) );
    FileOutputStream fos =null;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(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);
    }
}

点击信息:

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.iSave:
          Bitmap bitmap = null;
          bitmap = takeScreenshot();
          saveBitmap(bitmap);
        break;
    } 
}

这里:

public Bitmap takeScreenshot() {
   View rootView = findViewById(android.R.id.content).getRootView();
   rootView.setDrawingCacheEnabled(true);
   return rootView.getDrawingCache();
}

2 个答案:

答案 0 :(得分:15)

在拍摄完屏幕后调用rootView.setDrawingCacheEnabled(false);。将其关闭然后再打开会强制它正确更新。

public Bitmap takeScreenshot() {
   View rootView = findViewById(android.R.id.content).getRootView();
   rootView.setDrawingCacheEnabled(true);
   Bitmap bitmap = rootView.getDrawingCache();
   rootView.setDrawingCacheEnabled(false);
   return bitmap;
}

答案 1 :(得分:2)

我曾尝试捕获当前的Activity,然后分享屏幕截图。以下是我的做法,如果你仍然感兴趣,请看看它们,我想你会同意。

首先,获取当前Activity的根视图:

View rootView = getWindow().getDecorView().findViewById(android.R.id.content);

View rootView = findViewById(android.R.id.content);

View rootView = findViewById(android.R.id.content).getRootView();

第二次,从根视图中获取Bitmap

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

private final static String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
public static void store(Bitmap bm, String fileName){
    File dir = new File(dir);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dir, fileName);
    try {
        FileOutputStream fOut = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

At last,分享屏幕截图文件:

private void shareImage(String 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);
    startActivity(Intent.createChooser(intent, "Share Screenshot"));
}