如何以编程方式截取屏幕截图并将其保存在图库中?

pen*_*y89 5 sdk android

我想知道当前屏幕截图(按下按钮后)的代码是什么,并将其保存在图库中,因为我没有带SD卡的设备.所以我想保存在默认的库中.谢谢

Rag*_*dan 10

  Bitmap bitmap;
  View v1 = findViewById(R.id.rlid);// get ur root view id
  v1.setDrawingCacheEnabled(true); 
  bitmap = Bitmap.createBitmap(v1.getDrawingCache());
  v1.setDrawingCacheEnabled(false);
Run Code Online (Sandbox Code Playgroud)

这应该可以解决问题.

为了节省

  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
  File f = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "test.jpg")
  f.createNewFile();
  FileOutputStream fo = new FileOutputStream(f);
  fo.write(bytes.toByteArray()); 
  fo.close();
Run Code Online (Sandbox Code Playgroud)

  • 工作得很好,答案很好.不要忘记添加权限或它不会工作:<uses-permission android:name ="android.permission.WRITE_EXTERNAL_STORAGE"/> (2认同)

Ami*_*pta 5

    View v1 = L1.getRootView();
    v1.setDrawingCacheEnabled(true);
    Bitmap bm = v1.getDrawingCache();
    BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
    image = (ImageView) findViewById(R.id.screenshots);
    image.setBackgroundDrawable(bitmapDrawable);
Run Code Online (Sandbox Code Playgroud)

有关完整的源代码,请浏览以下博客

http://amitandroid.blogspot.in/2013/02/android-taking-screen-shots-through-code.html

用于存储位图以查看以下链接

Android Saving创建位图到SD卡上的目录


poi*_*oae 0

正如323go评论所述,除非您的设备确实获得了 root 权限,否则这是不可能的。

但如果是的话,这对于Monkeyrunner或者如果你使用模拟器来说可能是一个很好的工作。