Taking a screenshot of current Activity in Android

来源:互联网 发布:淘宝申诉ps小票 编辑:程序博客网 时间:2024/05/16 23:58

http://androidresearch.wordpress.com/2013/01/06/taking-a-screenshot-of-current-activity-in-android/


In this post I’ll show how you can take a screenshot of your current Activity and save the resulting image on /sdcard.

The idea behind taking a screenshot actually is pretty simple: what we need to do is to get a reference of the root view and  generate a bitmap copy of this view.

screenshot

Considering that we want to take the screenshot when a button is clicked, the code will look like this:

1
2
3
4
5
6
7
findViewById(R.id.button1).setOnClickListener(newOnClickListener() {
   @Override
   publicvoid onClick(View v) {
       Bitmap bitmap = takeScreenshot();
       saveBitmap(bitmap);
   }
});

 

First of all we should retrieve the topmost view in the current view hierarchy, then enable the drawing cache, and after that call getDrawingCache().

Calling getDrawingCache(); will return the bitmap representing the view or null if cache is disabled, that’s why setDrawingCacheEnabled(true); should be set to true prior invoking  getDrawingCache().

1
2
3
4
5
publicBitmap takeScreenshot() {
   View rootView = findViewById(android.R.id.content).getRootView();
   rootView.setDrawingCacheEnabled(true);
   returnrootView.getDrawingCache();
}

 

And the method that saves the bitmap image to external storage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
publicvoid saveBitmap(Bitmap bitmap) {
    File imagePath =new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
    FileOutputStream fos;
    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);
    }
}

 

Since the image is saved on external storage, the WRITE_EXTERNAL_STORAGE permission should be added AndroidManifest to file:

1
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

0 0
原创粉丝点击