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