要在Android 8.0及以上版本上保持后台服务运行,可以使用前台服务。前台服务是一种具有更高优先级的服务,可以在通知栏显示一个持续运行的通知,以提醒用户该服务正在后台运行。
下面是一个使用前台服务的示例代码:
MyService
类中添加以下代码:private void startForegroundService() {
String channelId = "my_channel_id";
String channelName = "My Channel";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setContentTitle("My Service")
.setContentText("Service is running in the background")
.setSmallIcon(R.drawable.ic_notification_icon)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Notification notification = builder.build();
startForeground(1, notification);
}
onStartCommand
方法中调用 startForegroundService
方法来启动前台服务。例如:@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForegroundService();
// 在这里执行你的后台任务逻辑
return START_STICKY;
}
stopForeground(true)
来停止前台服务。例如:private void stopForegroundService() {
stopForeground(true);
stopSelf();
}
请注意,你需要在清单文件中声明前台服务权限:
以上代码示例可以帮助你在Android 8.0及以上版本上保持后台服务运行。