在AndroidManifest.xml文件里面填入以下权限
<!--系统截屏权限-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
AndroidSDK28以上 需要启用Service服务
<!--MediaService服务-->
<service android:name=".tools.MediaService"
android:enabled="true"
android:foregroundServiceType="mediaProjection"
android:exported="true"/>
MediaService脚本
public class MediaService extends Service {
private final String NOTIFICATION_CHANNEL_ID="com.tencent.trtc.apiexample.MediaService";
private final String NOTIFICATION_CHANNEL_NAME="com.tencent.trtc.apiexample.channel_name";
private final String NOTIFICATION_CHANNEL_DESC="com.tencent.trtc.apiexample.channel_desc";
public MediaService() {
}
@Override
public void onCreate() {
super.onCreate();
startNotification();
}
public void startNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Call Start foreground with notification
Intent notificationIntent = new Intent(this, MediaService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Starting Service")
.setContentText("Starting monitoring service")
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(NOTIFICATION_CHANNEL_DESC);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
startForeground(1, notification); //必须使用此方法显示通知,不能使用notificationManager.notify,否则还是会报上面的错误
}
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
系统截屏实现
private boolean isstartservice = true;
//启动MediaService服务
public void StartMediaService()
{
if(isstartservice)
{
startService(new Intent(this, MediaService.class));
isstartservice = false;
}
}
public static final int REQUEST_MEDIA_PROJECTION = 10001;
private MediaProjectionManager mediaProjectionManager;
// 申请截屏权限
private void getScreenShotPower()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
mediaProjectionManager = (MediaProjectionManager)getSystemService(Context.MEDIA_PROJECTION_SERVICE);
if (mediaProjectionManager != null)
{
Intent intent = mediaProjectionManager.createScreenCaptureIntent();
startActivityForResult(intent, REQUEST_MEDIA_PROJECTION);
}
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_MEDIA_PROJECTION && data != null)
{
MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(Activity.RESULT_OK, data);
Bitmap bitmap = screenShot(mediaProjection);
byte[] bs = getBitmapByte(bitmap);
//对图片进行处理逻辑 例如可以保存本地、进行图片分享等等操作
}
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public Bitmap screenShot(MediaProjection mediaProjection)
{
WindowManager wm1 = this.getWindowManager();
int width = wm1.getDefaultDisplay().getWidth();
int height = wm1.getDefaultDisplay().getHeight();
Objects.requireNonNull(mediaProjection);
@SuppressLint("WrongConstant")
ImageReader imageReader = ImageReader.newInstance(width, height,PixelFormat.RGBA_8888,60);
VirtualDisplay virtualDisplay = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP)
{
virtualDisplay = mediaProjection.createVirtualDisplay("screen", width, height, 1,DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,imageReader.getSurface(), null, null);
}
SystemClock.sleep(1000);
//取最新的图片
Image image = imageReader.acquireLatestImage();
// Image image = imageReader.acquireNextImage();
//释放 virtualDisplay,不释放会报错
virtualDisplay.release();
return image2Bitmap(image);
}
//将Image转为Bitmap
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static Bitmap image2Bitmap(Image image)
{
if (image == null)
{
System.out.println("image 为空");
return null;
}
int width = image.getWidth();
int height = image.getHeight();
final Image.Plane[] planes = image.getPlanes();
final ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * width;
Bitmap bitmap = Bitmap.createBitmap(width+ rowPadding / pixelStride , height,Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
//截取图片
// Bitmap cutBitmap = Bitmap.createBitmap(bitmap,0,0,width/2,height/2);
//压缩图片
// Matrix matrix = new Matrix();
// matrix.setScale(0.5F, 0.5F);
// System.out.println(bitmap.isMutable());
// bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
image.close();
return bitmap;
}
// 位图转 Byte
private static byte[] getBitmapByte(Bitmap bitmap)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 参数1转换类型,参数2压缩质量,参数3字节流资源
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
try
{
out.flush();
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return out.toByteArray();
}
使用
public void CallMedail()
{
StartMediaService();
getScreenShotPower();
}