该问题可能是由于应用程序没有正确申请后台服务权限导致的。在 Android 10(API 级别 29)及更高版本中,应用程序必须具有 FOREGROUND_SERVICE 权限才能在后台运行服务。
您可以按照以下步骤解决这个问题:
public class MyService extends Service {
private static final int NOTIFICATION_ID = 1;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 创建前台服务通知
createNotificationChannel();
Notification notification = createNotification();
// 将服务设置为前台服务
startForeground(NOTIFICATION_ID, notification);
// 执行服务逻辑
return START_STICKY;
}
// 创建前台服务通知渠道
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"channel_id",
"Channel Name",
NotificationManager.IMPORTANCE_LOW
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
// 创建前台服务通知
private Notification createNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Foreground Service")
.setContentText("Running")
.setPriority(NotificationCompat.PRIORITY_LOW);
return builder.build();
}
// 其他服务逻辑...
}
请注意,上述代码中的 createNotificationChannel 和 createNotification 方法是用于创建前台服务通知和通知渠道的辅助方法。您可以根据自己的需求进行修改。
Intent serviceIntent = new Intent(context, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent);
} else {
context.startService(serviceIntent);
}
通过以上步骤,您的应用程序应该能够在 Android 10 及更高版本上正常启动前台服务,并且 android:foregroundServiceType="mediaProjection" 属性应该能够起作用。