如何以编程方式获取Android中开放当前活动的屏幕截图?

时间:2016-06-02 11:05:35

标签: android

使用手机和移动主屏幕时截屏。 当我在移动屏幕上使用消息传递,所有应用程序和任何内容时也要这样做。

在排序中,拍摄移动运行屏幕的图像:

4 个答案:

答案 0 :(得分:1)

在清单中添加以下权限 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE/>" <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE/>"

try {
    // image naming and path  to include sd card  appending name you choose for file
    String mPath = Environment.getExternalStorageDirectory().toString() + "/" + "name"+ ".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 OOM
    e.printStackTrace();
}

答案 1 :(得分:1)

使用它。我所做的是,当点击按钮时,它以与屏幕截图捕获类似的方式保存整个布局。

     linearLayout = (LinearLayout) findViewById(R.id.screenshots); //say   for eg: this is the main layout id wich holds everything(images etc)
     //use a button to call this method.        
     private void saveLayout() {
       // View v1 = getWindow().getDecorView().getRootView();
       View v1 = linearLayout.getRootView();
       v1.setDrawingCacheEnabled(true);
       myBitmap = v1.getDrawingCache();
       if (myBitmap != null) {
          Toast.makeText(MainScreen.this, "Bitmap not null",
          Toast.LENGTH_SHORT).show();
          saveBitmap(myBitmap);
       } else {
          Toast.makeText(MainScreen.this, "Bitmap null",Toast.LENGTH_SHORT).show();
       }
    }

   private void saveBitmap(Bitmap bitmap) {

    try {
        File mFolder = new File(getFilesDir() + "/nmc"); //give a name for the folder
        File imagePath = new File(mFolder + "screenshot.png"); 
        if (!mFolder.exists()) {
            mFolder.mkdir();
        }
        if (!imagePath.exists()) {
            imagePath.createNewFile();
        }
        FileOutputStream fos=null;

        fos = new FileOutputStream(imagePath);
        // bitmap.compress(CompressFormat.PNG, 100, fos);
        bitmap.compress(Bitmap.CompressFormat.PNG, 60, fos);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        String encodedByte = Base64.encodeToString(byteArray,Base64.DEFAULT);
        Log.e("encodeByte", encodedByte);
        fos.flush();
        fos.close();
        MediaStore.Images.Media.insertImage(getContentResolver(), bitmap,"Screen", "screen");

    } catch (FileNotFoundException e) {
        Log.e("no file", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("io", e.getMessage(), e);
    }

}

答案 2 :(得分:1)

为什么其他答案中有那么多行代码?该方法的核心只有3行:

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

然后在您的按钮单击事件中:

        bitmap = takeScreenshot();
        CommonUtils.saveImage(bitmap);

顺便说一句,CommonUtils code如下:

  public static void saveImage(Bitmap bitmap) {

    File imageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
      + "DCIM" + File.separator + Constants.APP_NAME);
    boolean mkdirSuccess = true;
    if (!imageDir.exists()) {
      mkdirSuccess = imageDir.mkdir();
    }
    if (!mkdirSuccess) {
      Log.e("== saveImage", "mkdir FAILED!");
      return;
    }
    String fileName = System.currentTimeMillis() + ".jpg";
    File file = new File(imageDir, fileName);
    try {
      FileOutputStream fileOutputStream = new FileOutputStream(file);

      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
      fileOutputStream.flush();
      fileOutputStream.close();

      Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
      intent.setData(Uri.fromFile(file));
      BaseApplication.getContext().sendBroadcast(intent);

    } catch (IOException e) {
      e.printStackTrace();
    }

  }

答案 3 :(得分:0)

1-Create layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativelayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Create ScreenShot" />

    <ImageView
        android:id="@+id/sowscreenshot"
        android:layout_width="216dp"
        android:layout_height="360dp"
        android:layout_below="@+id/btn"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp" />

</RelativeLayout>

2-Create Activity

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    Button btn_screenshoot;
    int i = 0;
    ImageView imgv_showscreenshot;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgv_showscreenshot = (ImageView) findViewById(R.id.showscreenshot);
        btn_screenshoot = (Button) findViewById(R.id.btn);
        btn_screenshoot.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                View view = findViewById(R.id.relativelayout);
                view.setDrawingCacheEnabled(true);
                Bitmap bitmap = view.getDrawingCache();
                BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);

// set screenshot bitmapdrawable to imageview
                imgv_showscreenshot.setBackgroundDrawable(bitmapDrawable);
                if (Environment.MEDIA_MOUNTED.equals(Environment
                        .getExternalStorageState())) {
// we check if external storage is available, otherwise
// display an error message to the user using Toast Message
                    File sdCard = Environment.getExternalStorageDirectory();
                    File directory = new File(sdCard.getAbsolutePath()
                            + "/ScreenShots");
                    directory.mkdirs();

                    String filename = "screenshot" + i + ".jpg";
                    File yourFile = new File(directory, filename);

                    while (yourFile.exists()) {
                        i++;
                        filename = "screenshot" + i + ".jpg";
                        yourFile = new File(directory, filename);
                    }

                    if (!yourFile.exists()) {
                        if (directory.canWrite()) {
                            try {
                                FileOutputStream out = new FileOutputStream(
                                        yourFile, true);
                                bitmap.compress(Bitmap.CompressFormat.PNG, 90,
                                        out);
                                out.flush();
                                out.close();
                                Toast.makeText(
                                        MainActivity.this,
                                        "File exported to /sdcard/ScreenShots/screenshot"
                                                + i + ".jpg",
                                        Toast.LENGTH_SHORT).show();
                                i++;
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                } else {
                    Toast.makeText(MainActivity.this,
                            "Sorry SD Card not available in your Device!",
                            Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

}

3-Add permission to Manifest file

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