版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/chaoyu168/article/details/80898936
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
MediaProjectionManager mediaProjectionManager;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
mediaProjectionManager = (MediaProjectionManager) getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), 1);
final Button button = findViewById(R.id.bt_screenshot);
final ImageView imageView = findViewById(R.id.img_display);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (MyApplication.mediaProjection != null) {
MyApplication.time = System.currentTimeMillis();
Bitmap bitmap = CreateBitmap.getInstance(MainActivity.this, true, null, "null").getBitmap();
if (bitmap == null) {
Log.i("img", "bitmap为空");
} else {
imageView.setBackground(new BitmapDrawable(null, bitmap));
}
} else {
Log.i("img", "未获取到截屏权限");
}
}
});
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
MyApplication.mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
}
public void checkPermission() {
final List<String> permissionsList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
} else {
}
if (permissionsList.size() != 0) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
100);
}
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 100) {
if (grantResults.length > 0 && (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
} else {
Log.i("img", "未获取权限");
}
}///instant-run
}
}
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import static android.content.Context.WINDOW_SERVICE;
/**
* Created by Administrator on 2017/3/16.
*/
public class CreateBitmap {
private static MediaProjection mediaProjection = MyApplication.mediaProjection;
private static ImageReader mImageReader;
private static VirtualDisplay virtualDisplay1;
private static DisplayMetrics displayMetrics = new DisplayMetrics();
private static WindowManager windowManager;
private static Bitmap bmp, bitmap;
private static Image image;
private static int width;
private static int height;
private static int pixelStride;
private static int rowStride;
private static int rowPadding;
private static String path, name;
private static int screenwidth, screenheight;
private static Image.Plane[] planes;
static ByteBuffer buffer;
private static class singleHolder {
static final CreateBitmap createbitmap = new CreateBitmap();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static CreateBitmap getInstance(final Context context, final Boolean isSave, String inpath, String inname) {
init(context, inpath, inname);
if (image != null) {
analysesImage();
long time = System.currentTimeMillis() - MyApplication.time;
Log.i("img", "截图已生成" + time);
if (isSave)
savePic(context);
}
return singleHolder.createbitmap;
}
private static void loop() {
do {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (image != null);
}
// 初始化操作
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static void init(final Context context, String inpath, String inname) {
if (bitmap != null) {
bitmap = null;
}
path = inpath;
name = inname;
windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(displayMetrics);
screenwidth = displayMetrics.widthPixels;
screenheight = displayMetrics.heightPixels;
mImageReader = ImageReader.newInstance(screenwidth, screenheight, PixelFormat.RGBA_8888, 2);
virtualDisplay1 = mediaProjection.createVirtualDisplay("screen-mirror", screenwidth, screenheight, displayMetrics.densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null);
do {
try {
Thread.sleep(10);
image = mImageReader.acquireLatestImage();
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (image == null);
}
//解析image
private static void analysesImage() {
planes = image.getPlanes();
buffer = planes[0].getBuffer();
width = image.getWidth();
height = image.getHeight();
pixelStride = planes[0].getPixelStride();
rowStride = planes[0].getRowStride();
rowPadding = rowStride - pixelStride * width;
bmp = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buffer);
bitmap = Bitmap.createScaledBitmap(bmp, bmp.getWidth(), bmp.getHeight(), false);
image.close();
}
//保存图片
private static void savePic(Context context) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && bitmap != null) {
if (path == null) {
path = Environment.getExternalStorageDirectory().getPath() + "/Android/screen";
} else {
path = Environment.getExternalStorageDirectory().getPath() + path;
}
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
if (name == null) {
name = System.currentTimeMillis() + "";
}
File file1 = new File(file, name + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file1);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
Log.i("img", "截屏已保存到本地" + path);
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file1);
intent.setData(uri);
context.sendBroadcast(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public Bitmap getBitmap() {
return bitmap;
}
}
import android.app.Application;
import android.media.projection.MediaProjection;
public class MyApplication extends Application {
public static MediaProjection mediaProjection;
public static long time;
}
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class ScreenShotActivity extends Activity {
MediaProjectionManager mediaProjectionManager;
MediaProjection mediaProjection;
ImageReader mImageReader;
VirtualDisplay virtualDisplay1;
DisplayMetrics displayMetrics;
WindowManager windowManager;
String name, path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
name = intent.getStringExtra("name");
path = intent.getStringExtra("path");
checkPermission();
}
public void requestCapturePermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//5.0 之后才允许使用屏幕截图
return;
}
mediaProjectionManager = (MediaProjectionManager)
getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
startActivityForResult(
mediaProjectionManager.createScreenCaptureIntent(),
1);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
captureScreen();
}
public void checkPermission() {
final List<String> permissionsList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
} else {
requestCapturePermission();
}
if (permissionsList.size() != 0) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
100);
}
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 100) {
if (grantResults.length > 0 && (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
requestCapturePermission();
} else {
Log.e("ScreenShotActivity", "未获取权限");
}
}///instant-run
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void captureScreen() {
displayMetrics = new DisplayMetrics();
windowManager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
mImageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2);
virtualDisplay1 = mediaProjection.createVirtualDisplay("screen-mirror", width, height, displayMetrics.densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Image image = mImageReader.acquireLatestImage();
if (image != null) {
final Image.Plane[] planes = image.getPlanes();
final ByteBuffer buffer = planes[0].getBuffer();
int width = image.getWidth();
int height = image.getHeight();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * width;
Bitmap bmp = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buffer);
Bitmap bitmap = Bitmap.createScaledBitmap(bmp, bmp.getWidth(), bmp.getHeight(), false);
if(bitmap!=null){
long spendtimes = System.currentTimeMillis() - MyApplication.time;
Log.e("ScreenShotActivity", "bitmap成功时间" + spendtimes);
}
setSavePic(bitmap);
bitmap.recycle();
image.close();
}
}
}, 10);
}
private void setSavePic(Bitmap bitmap) {//保存截屏到本地
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if (path == null) {
path = Environment.getExternalStorageDirectory().getPath() + "/截屏";
} else {
path = Environment.getExternalStorageDirectory().getPath() + "/" + path;
}
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
if (name == null) {
name = System.currentTimeMillis() + "";
}
File file1 = new File(file, name + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file1);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
// Toast.makeText(this, "截屏已保存到本地" + path, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file1);
intent.setData(uri);
sendBroadcast(intent);
finish();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import android.content.Context;
import android.content.Intent;
public class ShotClass {
private static class SingleHolder {
static final ShotClass shot = new ShotClass();
}
public static ShotClass getInstance() {
return SingleHolder.shot;
}
public void createShot(Context context, String path, String name) {
Intent intent = new Intent(context, ScreenShotActivity.class);
intent.putExtra("path", path);
intent.putExtra("name", name);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
源码下载:https://download.csdn.net/download/chaoyu168/10516429