解决 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 @   拜雨  阅读(310)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· PowerShell开发游戏 · 打蜜蜂
· 凌晨三点救火实录:Java内存泄漏的七个神坑,你至少踩过三个!
点击右上角即可分享
微信分享提示