解决 java.lang.SecurityException: Media projections require a foreground service of type ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION

我在Android8.0上增加的截屏功能,也声明了响应权限,但是在Android11上就报权限错误。原来在Android10以后启动前台服务时候有第三个参数。

低版本我们调用 public final void startForeground(int id, Notification notification) 即可 但是在Android10以后需要调用 public final void startForeground(int id, @NonNull Notification notification, @RequiresPermission @ForegroundServiceType int foregroundServiceType)

有个权限类型的参数。

解决方案:

MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE); mediaProjection = mediaProjectionManager.getMediaProjection(intent.getIntExtra("resultCode", -1), intent.getParcelableExtra("data")); // 创建通知 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Media Projection Service") .setContentText("Running media projection...") .setSmallIcon(android.R.drawable.ic_media_play); // 将服务设置为前台服务 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { startForeground(NOTIFICATION_ID, builder.build(), ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION); } else { startForeground(NOTIFICATION_ID, builder.build()); }

__EOF__

本文作者拜雨
本文链接https://www.cnblogs.com/baiyuas/p/18596977.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   拜雨  阅读(344)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示