Android 系统截屏实现

在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();
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小张不爱写代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值