在Android 12中,Google加强了对前台服务启动的限制,要求应用程序必须满足特定要求才能启动前台服务。以下是在Android 12中启动前台服务的示例:
如果您的应用程序还未添加此权限,请在AndroidMenifest.xml的
如果您的应用程序希望从后台或其他线程启动前台服务,请使用以下代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { ContextCompat.startForegroundService(context, intent); } else { context.startService(intent); }
一旦启动服务,您必须启动前台通知,以便用户可以看到正在运行的服务,并确保Android系统不会杀死该服务。以下是一个示例:
public class MyService extends Service { private static final int NOTIFICATION_ID = 12345;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.notification_title))
.setContentText(getString(R.string.notification_text))
.setSmallIcon(R.drawable.ic_notification)
.build();
startForeground(NOTIFICATION_ID, notification);
// Your code here
return START_STICKY;
}
// Your code here
}
通过上述步骤,您的应用程序可以在Android 12中启动前台服务。但是要注意,前台服务仅在必要时使用,以避免不必要的系统资源消耗。