Android Oreo后台服务限制启动\u粘性问题
在android oreo之后,服务的使用有一些限制。我无法理解这些限制是如何影响代码的?例如,如果我通过startService函数启动服务,并在startcommand函数中返回start_STICKY,服务将在kill后重新启动。我在这里看不到android 8的任何问题。我可以在后台服务中侦听位置更新。这里的限制是什么?返回start_sticky就足以重新创建和创建。再次运行服务?在过去3天里,我一直在研究这个话题。最后,我从android开发者网站上读到了关于android 8后台服务限制的内容,只有一件事很重要,如果你想在后台运行服务,那么你应该在5秒内在你的应用程序中显示通知,否则你将得到非法的异常 这里是实现Android Oreo后台服务限制启动\u粘性问题,android,service,android-8.0-oreo,foreground-service,Android,Service,Android 8.0 Oreo,Foreground Service,在android oreo之后,服务的使用有一些限制。我无法理解这些限制是如何影响代码的?例如,如果我通过startService函数启动服务,并在startcommand函数中返回start_STICKY,服务将在kill后重新启动。我在这里看不到android 8的任何问题。我可以在后台服务中侦听位置更新。这里的限制是什么?返回start_sticky就足以重新创建和创建。再次运行服务?在过去3天里,我一直在研究这个话题。最后,我从android开发者网站上读到了关于android 8后台服
@Override
public void onCreate() {
super.onCreate();
startInForeground();
}
private void startInForeground() {
Intent notificationIntent = new Intent(this, SplashScreenActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"some_channel_id")
.setSmallIcon(R.drawable.ic_motion_new)
.setContentTitle("Sure")
.setContentText("Local call notification")
.setTicker("TICKER")
.setContentIntent(pendingIntent);
Notification notification=builder.build();
NotificationChannel channel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
channel = new NotificationChannel("local_call_notification", "Local Call", NotificationManager.IMPORTANCE_MIN);
channel.setDescription("Local Call Notification");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
startForeground(2, notification);
NotificationManager notificationManager= (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(2);
}
启动服务
Intent startServiceIntent=新的Intent(上下文,xyz.class)
根据我的测试,当服务在后台运行时,如果手动终止应用程序,服务将通过设置start\u sticky重新启动。但当服务在后台运行一段时间后,无论是否设置了Start\u Sticky参数,系统都会自动终止该服务。另一个现象是,当我在Android 10上运行时,无论我如何设置参数,服务都不会自动重新启动。服务不会在后台运行,因此您肯定无法在后台收听位置更新。这并不是说打瞌睡和应用程序待机模式也会影响位置更新。你应该查看后台限制文档。我知道这个规则,我也可以使用context.startService(startServiceIntent)启动服务;(oreo或更高版本)当应用程序位于前台时。我现在看不到有关限制的任何问题。START\u STICKY将在终止后再次启动服务。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(startServiceIntent);
} else {
context.startService(startServiceIntent);
}