How to programmatically take a screenshot?

2018-12-30 23:45发布

How can I take a screenshot of a selected area of phone-screen not by any program but from code?

24条回答
刘海飞了
2楼-- · 2018-12-31 00:11

I have created a simple library that takes a screenshot from a View and either gives you a Bitmap object or saves it directly to any path you want

https://github.com/abdallahalaraby/Blink

查看更多
牵手、夕阳
3楼-- · 2018-12-31 00:13

Just extending taraloca's answer. You must add followings lines to make it work. I have made the image name static. Please ensure you use taraloca's timestamp variable incase you need dynamic image name.

    // Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

private void verifyStoragePermissions() {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
    }else{
        takeScreenshot();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        if (requestCode == REQUEST_EXTERNAL_STORAGE) {
            takeScreenshot();
        }
    }
}

And in the AndroidManifest.xml file following entries are must:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 00:15

No root permission or no big coding is required for this method.


On adb shell using below command you can take screen shot.

input keyevent 120

This command does not required any root permission so same you can perform from java code of android application also.

Process process;
process = Runtime.getRuntime().exec("input keyevent 120");

More about keyevent code in android see http://developer.android.com/reference/android/view/KeyEvent.html

Here we have used. KEYCODE_SYSRQ its value is 120 and used for System Request / Print Screen key.


As CJBS said, The output picture will be saved in /sdcard/Pictures/Screenshots

查看更多
刘海飞了
5楼-- · 2018-12-31 00:17

Here is the code that allowed my screenshot to be stored on an SD card and used later for whatever your needs are:

First, you need to add a proper permission to save the file:

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

And this is the code (running in an Activity):

private void takeScreenshot() {
    Date now = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

    try {
        // image naming and path  to include sd card  appending name you choose for file
        String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

        // create bitmap screen capture
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(mPath);

        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        outputStream.flush();
        outputStream.close();

        openScreenshot(imageFile);
    } catch (Throwable e) {
        // Several error may come out with file handling or DOM
        e.printStackTrace();
    }
}

And this is how you can open the recently generated image:

private void openScreenshot(File imageFile) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(imageFile);
    intent.setDataAndType(uri, "image/*");
    startActivity(intent);
}

If you want to use this on fragment view then use:

View v1 = getActivity().getWindow().getDecorView().getRootView();

instead of

View v1 = getWindow().getDecorView().getRootView();

on takeScreenshot() function

Note:

This solution doesn't work if your dialog contains a surface view. For details please check the answer to the following question:

Android Take Screenshot of Surface View Shows Black Screen

查看更多
看风景的人
6楼-- · 2018-12-31 00:18

You can try the following library: http://code.google.com/p/android-screenshot-library/ Android Screenshot Library (ASL) enables to programmatically capture screenshots from Android devices without requirement of having root access privileges. Instead, ASL utilizes a native service running in the background, started via the Android Debug Bridge (ADB) once per device boot.

查看更多
裙下三千臣
7楼-- · 2018-12-31 00:18

if you want to capture a view or layout like RelativeLayout or LinearLayout etc. just use the code :

LinearLayout llMain = (LinearLayout) findViewById(R.id.linearlayoutMain);
Bitmap bm = loadBitmapFromView(llMain);

now you can save this bitmap on device storage by :

FileOutputStream outStream = null;
File f=new File(Environment.getExternalStorageDirectory()+"/Screen Shots/");
f.mkdir();
String extStorageDirectory = f.toString();
File file = new File(extStorageDirectory, "my new screen shot");
pathOfImage = file.getAbsolutePath();
try {
    outStream = new FileOutputStream(file);
    bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
    Toast.makeText(getApplicationContext(), "Saved at "+f.getAbsolutePath(), Toast.LENGTH_LONG).show();
    addImageGallery(file);
    //mail.setEnabled(true);
    flag=true;
} catch (FileNotFoundException e) {e.printStackTrace();}
try {
    outStream.flush();
    outStream.close();
} catch (IOException e) {e.printStackTrace();}
查看更多
登录 后发表回答