Capture Screen shot on Android using Java code

22,050

Here is a solution to take the screenshot of your screen and write it to the sd card

Setting up your Root layout:

View content = findViewById(R.id.layoutroot);
content.setDrawingCacheEnabled(true);

Function to get the rendered view:

private void getScreen()
{
    View content = findViewById(R.id.layoutroot);
    Bitmap bitmap = content.getDrawingCache();
    File file = new File( Environment.getExternalStorageDirectory() + "/test.png");
    try 
    {
        file.createNewFile();
        FileOutputStream ostream = new FileOutputStream(file);
        bitmap.compress(CompressFormat.PNG, 100, ostream);
        ostream.close();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

Remember to add

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

to your AndroidManifest.

Share:
22,050
Srini
Author by

Srini

Updated on July 12, 2020

Comments

  • Srini
    Srini almost 4 years

    Possible Duplicate:
    Screenshot Android

    I would like to capture screenshots programatically (not the screen shot of my view) and have created an application to take the screen shot of my view.

    I am trying to capture the device screen shot (like if user opned any image file) by using Java code(I thought of creating service and from service we can take picture but I am not sure how to achieve this).

    I found some native code using frame buffer fb0 but I am very knew to this and no idea how to use it.

  • Srini
    Srini almost 12 years
    Hi Thanks for reply! I want to capture the device screen not my activity , the idea is if user opened any of the image file and press menu button then I want to capture screen!
  • Antrromet
    Antrromet almost 12 years
    Yea I understand you. For that you will have to get the root layout of the screen. Get the root layout of your activity.
  • Srini
    Srini almost 12 years
    could you please paste me the code to get the root layout , still I have doubt that if my activity is launched and get the root layout means it will get the back ground window screen instead of my current activity screen? sorry for asking his doubt!
  • Antrromet
    Antrromet almost 12 years
    @Srini Check out this link stackoverflow.com/questions/4486034/…