当前位置: 首页 > news >正文

安卓截屏;前台服务

  private var mediaProjectionManager: MediaProjectionManager? = nullval REQUEST_MEDIA_PROJECTION = 10001private var isstartservice = true//启动MediaService服务fun startMediaService() {if (isstartservice) {startService(Intent(this, MediaService::class.java))isstartservice = false}}//停止MediaService服务fun stopMediaService(context: Context) {val intent = Intent(context, MediaService::class.java)context.stopService(intent)}// 申请截屏权限private fun getScreenShotPower() {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {mediaProjectionManager =getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManagerif (mediaProjectionManager != null) {val intent = mediaProjectionManager!!.createScreenCaptureIntent()startActivityForResult(intent, REQUEST_MEDIA_PROJECTION)}}}@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {super.onActivityResult(requestCode, resultCode, data)if (requestCode == REQUEST_MEDIA_PROJECTION && data != null) {
//            mediaProjection = mediaProjectionManager!!.getMediaProjection(RESULT_OK, data)val mediaPro = mediaProjectionManager!!.getMediaProjection(RESULT_OK, data)val bitmap = screenShot(mediaPro)      //截屏val bs = getBitmapByte(bitmap)//对图片进行处理逻辑  例如可以保存本地、进行图片分享等等操作Log.e("WWW", "EEE" + bitmap)if (bitmap != null) {if (typeShare != -1) {if (typeShare == 0) {/*** 微信分享*/shareWechat(bitmap)} else if (typeShare == 1) {/*** 保存到本地相册*/bitmap?.let { it1 -> ImageSaver.saveBitmapToGallery(this, it1, "-", "+++") }stopMediaService(this)}}}//            startRecord()    //三:录屏
//            if (!isStart) {
//                isStart = !isStart
//                startPlayRoute()
//                multiple = 150f
//            } else {
//                multiple = 150f
//            }
//            isShowShareTipsPop = true}}/*** 分享到微信* @param view View*/private fun shareWechat(view: Bitmap?) {
//        var bmp: Bitmap? = loadBitmapFromViewBySystem(view)val imgObj = WXImageObject(view)val msg = WXMediaMessage()msg.mediaObject = imgObjval thumbBmp = Bitmap.createScaledBitmap(view!!,150,150,true)msg.thumbData = bmpToByteArray(thumbBmp, true)val req = SendMessageToWX.Req()req.transaction = buildTransaction("img")req.message = msgreq.scene = SendMessageToWX.Req.WXSceneSession // 分享到对话框api!!.sendReq(req)stopMediaService(this)}@RequiresApi(api = Build.VERSION_CODES.KITKAT)fun screenShot(mediaProjection: MediaProjection): Bitmap? {val wm1 = this.windowManagerval width = wm1.defaultDisplay.widthval height = wm1.defaultDisplay.heightObjects.requireNonNull(mediaProjection)@SuppressLint("WrongConstant") val imageReader: ImageReader =ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 60)var virtualDisplay: VirtualDisplay? = nullif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {virtualDisplay = mediaProjection.createVirtualDisplay("screen",width,height,1,DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,imageReader.getSurface(),null,null)}SystemClock.sleep(1000)//取最新的图片val image: Image = imageReader.acquireLatestImage()// Image image = imageReader.acquireNextImage();//释放 virtualDisplay,不释放会报错virtualDisplay!!.release()return image2Bitmap(image)}// 位图转 Byteprivate fun getBitmapByte(bitmap: Bitmap?): ByteArray {val out = ByteArrayOutputStream()// 参数1转换类型,参数2压缩质量,参数3字节流资源bitmap!!.compress(Bitmap.CompressFormat.PNG, 100, out)try {out.flush()out.close()} catch (e: IOException) {e.printStackTrace()}return out.toByteArray()}@RequiresApi(api = Build.VERSION_CODES.KITKAT)fun image2Bitmap(image: Image?): Bitmap? {if (image == null) {println("image 为空")return null}val width: Int = image.getWidth()val height: Int = image.getHeight()val planes: Array<Image.Plane> = image.planesval buffer: ByteBuffer = planes[0].bufferval pixelStride: Int = planes[0].pixelStrideval rowStride: Int = planes[0].rowStrideval rowPadding = rowStride - pixelStride * widthval 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}

package com.allynav.iefa.service

import android.R
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
/**
*@author zd
*@time 2023/4/10 8:55
*@description : 截屏前台服务
*
**/

class MediaService : Service() {private val NOTIFICATION_CHANNEL_ID = "com.tencent.trtc.apiexample.MediaService"private val NOTIFICATION_CHANNEL_NAME = "com.tencent.trtc.apiexample.channel_name"private val NOTIFICATION_CHANNEL_DESC = "com.tencent.trtc.apiexample.channel_desc"override fun onCreate() {super.onCreate()startNotification()}fun startNotification() {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//Call Start foreground with notificationval notificationIntent = Intent(this, MediaService::class.java)val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0)val notificationBuilder: NotificationCompat.Builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID).setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.alert_dark_frame)).setSmallIcon(R.drawable.alert_dark_frame).setContentTitle("Starting Service").setContentText("Starting monitoring service").setContentIntent(pendingIntent)val notification: Notification = notificationBuilder.build()val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID,NOTIFICATION_CHANNEL_NAME,NotificationManager.IMPORTANCE_DEFAULT)channel.description = NOTIFICATION_CHANNEL_DESCval notificationManager =getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManagernotificationManager.createNotificationChannel(channel)startForeground(1,notification) //必须使用此方法显示通知,不能使用notificationManager.notify,否则还是会报上面的错误}}override fun onBind(intent: Intent?): IBinder {throw UnsupportedOperationException("Not yet implemented")}
}
http://www.lryc.cn/news/168591.html

相关文章:

  • C++ PrimerPlus 复习 第八章 函数探幽
  • JavaScript-Ajax-axios-Xhr
  • 怎样查看kafka写数据送到topic是否成功
  • 腾讯mini项目-【指标监控服务重构】2023-08-16
  • PTA:7-3 两个递增链表的差集
  • 智能合约漏洞案例,DEI 漏洞复现
  • Attention is all you need 论文笔记
  • Hdoop伪分布式集群搭建
  • java临时文件
  • C++中的<string>头文件 和 <cstring>头文件简介
  • 安装MySQL
  • 输入学生成绩,函数返回最大元素的数组下标,求最高分学生成绩(输入负数表示输入结束)
  • 常用音频接口:TDM,PDM,I2S,PCM
  • git clone报错Failed to connect to github.com port 443 after 21055 ms:
  • 【操作系统】深入浅出死锁问题
  • springboot实现webSocket服务端和客户端demo
  • 代码走读: FFMPEG-ffplayer02
  • 【数据结构】——排序算法的相关习题
  • C高级day5(Makefile)
  • Android 系统中适配OAID获取
  • 差分数组leetcode 2770 数组的最大美丽值
  • 请求响应状态码
  • 安卓机型系统美化 Color.xml文件必备常识 自定义颜色资源
  • YOLO物体检测-系列教程1:YOLOV1整体解读(预选框/置信度/分类任/回归任务/损失函数/公式解析/置信度/非极大值抑制)
  • 2023/9/12 -- C++/QT
  • 【Purple Pi OH RK3566鸿蒙开发板】OpenHarmony音频播放应用,真实体验感爆棚!
  • Android rom开发:9.0系统上实现4G wifi 以太网共存
  • 高速自动驾驶HMI人机交互
  • 【自然语言处理】关系抽取 —— SOLS 讲解
  • 周易算卦流程c++实现