I want to take the screenshot of my app in code. First of all, I need to get the current view but the method getCurrentFocus() always returns null. What can I do?
Asked
Active
Viewed 2,223 times
1 Answers
0
Please note that you can only take a screenshot of what you are presenting on your view, you cannot take it of other activities or apps that are present on the screen at the time.
public static Bitmap takeScreenshot(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;
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay().getHeight();
Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, statusBarHeight, width,
height - statusBarHeight);
view.destroyDrawingCache();
return bitmap2;
}

Jose Sutilo
- 908
- 1
- 5
- 7
-
1I have a question; when calling this function, how can I send the current activity as parameter? **takeScreenshot(getActivity());** is there something like that? – anilbey Aug 02 '13 at 11:55
-
It depends on how your code is set up, but normally you are running that code from within an activity and all you have to do is: takeScreenshot(this.getActivity()) or just this – Jose Sutilo Aug 02 '13 at 12:14
-
PS: please note that getActivity() is specific to phonegap Activities, you would probably be ok by just passing **this** – Jose Sutilo Aug 02 '13 at 12:26
-
1it says **The method getActivity() is undefined for the type new View.OnClickListener(){}** – anilbey Aug 02 '13 at 12:30
-
1in that case, you cannot use this, as you are inside a new OnClickListener, at which point that will be this, so you have to do something like: **YourActivityName.this** where YourActivityName is the name of the activity in which you are setting up that view and clicklisteners – Jose Sutilo Aug 02 '13 at 12:35