Android take screen shot programmatically

47,970

Solution 1

Here you go...I used this:

View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, getString(R.string.free_tiket)+".jpg");
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(myPath);
    b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    fos.flush();
    fos.close();
    MediaStore.Images.Media.insertImage( getContentResolver(), b, 
                                         "Screen", "screen");
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

v iz root layout...just to point ;)))

Solution 2

For the next reader of this question-

The very simple way to do this by drawing your view to canvas-

pass your main layout reference to this method-

 Bitmap file = save(layout);

 Bitmap save(View v)
   {
    Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    v.draw(c);
    return b;
   }

Solution 3

I think you have to wait until the layout is drawn completely..Use ViewTreeObserver to get a call back when layout is drawn completely..

On your onCreate add this code..Only call getScreen from inside onGlobalLayout()..

ViewTreeObserver vto = content.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout() {
    content.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    getScreen();
  }
});

I asked a somewhat similiar question once..Please see my question which explains the way to take screenshot in android..Hope this helps

Solution 4

public class MainActivity extends Activity
{
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            Bitmap bitmap = takeScreenshot();
            saveBitmap(bitmap);

        }
    });
}

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

public void 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);
    }
}
}

don't forgot to give write external storage permission!

Share:
47,970

Related videos on Youtube

user577732
Author by

user577732

Updated on September 28, 2020

Comments

  • user577732
    user577732 over 3 years

    First off i am writing a root app so root permissions are no issue. I've searched and searched and found a lot of code that never worked for me here is what i've pieced together so far and sorta works. When i say sorta i mean it makes an image on my /sdcard/test.png however the file is 0 bytes and obviously can't be viewed.

    public class ScreenShot extends Activity{
    
    View content;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blank);
        content = findViewById(R.id.blankview);
        getScreen();
    }
    
    private void getScreen(){
        Bitmap bitmap = content.getDrawingCache();
        File file = new File("/sdcard/test.png");
        try 
        {
            file.createNewFile();
            FileOutputStream ostream = new FileOutputStream(file);
            bitmap.compress(CompressFormat.PNG, 100, ostream);
            ostream.close();
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
    }
    

    Any help on how i can take a screen shot in android via code would be greatly appreciated thank you!

    ===EDIT===

    The following is everything i'm using the image is made on my sdcard and is no longer 0bytes but the entire thing is black there is nothing on it. I've bound the activity to my search button so when i'm some where on my phone i long press search and it is supposed to take a screen shot but i just get a black image? Everything is set transparent so i'd think it should grab whatever is on the screen but i just keep getting black

    Manifest

    <activity android:name=".extras.ScreenShot"
        android:theme="@android:style/Theme.Translucent.NoTitleBar"
        android:noHistory="true" >
        <intent-filter>
            <action android:name="android.intent.action.SEARCH_LONG_PRESS" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        </activity>
    

    XML

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="#00000000"
      android:id="@+id/screenRoot">    
    </LinearLayout>
    

    Screenshot class

    public class ScreenShot extends Activity{
    
    View content;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screenshot);
        content = findViewById(R.id.screenRoot);
        ViewTreeObserver vto = content.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
          @Override
          public void onGlobalLayout() {
            content.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            getScreen();
          }
        });
    }
    
    private void getScreen(){
        View view = content;
        View v = view.getRootView();
        v.setDrawingCacheEnabled(true);
        Bitmap b = v.getDrawingCache();             
        String extr = Environment.getExternalStorageDirectory().toString();
        File myPath = new File(extr, "test.jpg");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(myPath);
            b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
        }catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finish();
    }
    }
    
  • user577732
    user577732 over 12 years
    k thanks for the answer going to take a look at your question tomorrow just too tired at the moment. I do have one other question though how come root isn't called when i do this? and will this code just be taking a screen shot of the layout only because i want to basically take a screen shot of what's on the screen i have it bound to the search key when long pressed
  • Shreyash Mahajan
    Shreyash Mahajan over 12 years
    What is view ?? I am using your code but i got the error that view cannot be resolved. So What is view ?
  • Jovan
    Jovan over 12 years
    View is LinearLayout...you must add id to your linear or relative layout(what you use) and in onCreate you define it like this: View view= findViewById(R.id.linearLayoutRoot); then y use rest of my code...
  • Shreyash Mahajan
    Shreyash Mahajan over 12 years
    Ok Thanks. I got it. And it Works great. But i need your some what more help if u can.
  • Shreyash Mahajan
    Shreyash Mahajan over 12 years
    Actualy i am taking the screen shot of the Camera preview that displayed on the Screen. There are also some Button Available on that View. Now while i am taking the Screen Shot, that Layout is captured but i am not able to take a Snapshot of that camera display. Whay it is like that ???
  • Shreyash Mahajan
    Shreyash Mahajan over 12 years
    Do u have any Idea to implement it ?
  • Shreyash Mahajan
    Shreyash Mahajan over 12 years
    Ok. Its works fine. But if i am using that code to take a screen shot of the camer view then it is not going to work.
  • Jovan
    Jovan over 12 years
    Currently nothing comes to my mind...but i don't understand you completely...you want to save what your camera captured??? Is this showing on your view???
  • user577732
    user577732 over 12 years
    @Jovan i tried your code but i get a black screen now please take a look at my question and the second edit to see exactly what i have thank you for the help thus far
  • user577732
    user577732 over 12 years
    alright so changing the theme in the manifest to light gave me a white image so it appears we're screen shoting the layout which is kind of what i assumed by it not needing root access. I need to take a screen shot not of my app but of anything much like the app drocap does
  • Jovan
    Jovan over 12 years
    I haven't been here for the weekend...have you find a solution??? I now understand what you want, but i can't help you...i did't use anything like that, but I'm a newcomer..if i run into something or think of something i will write it here...
  • Shreyash Mahajan
    Shreyash Mahajan over 12 years
    Yes, It Works fine. But what if i want to take the screen shot with high resolution ?
  • Jovan
    Jovan over 10 years
    Just a name in string value...you can put what you want here...it's a value for a File
  • BossWalrus
    BossWalrus about 10 years
    @user577732 have you found a solution the black/white screen that you are getting on your save?
  • Abhishek Tamta
    Abhishek Tamta over 9 years
    @Jovan I have done all the things there is no error coming but app in not running. Give any solution.
  • abbasalim
    abbasalim over 8 years
    very nice, this is update but other ways cash image and is bad