Android服务在粘性模式下被破坏
下面是我的android,当按下活动按钮时启动。但我看到,当活动被终止时,服务被破坏。我希望该服务始终处于活动状态,即使该应用程序已关闭/关闭/清除Android服务在粘性模式下被破坏,android,android-service,android-background,Android,Android Service,Android Background,下面是我的android,当按下活动按钮时启动。但我看到,当活动被终止时,服务被破坏。我希望该服务始终处于活动状态,即使该应用程序已关闭/关闭/清除 public class ScreenService extends Service{ private BroadcastReceiver sReceiver; public IBinder onBind(Intent arg){ Log.d(Constant.APP_TAG,"onBind service me
public class ScreenService extends Service{
private BroadcastReceiver sReceiver;
public IBinder onBind(Intent arg){
Log.d(Constant.APP_TAG,"onBind service method called");
return null;
}
public int onStartCommand(Intent intent,int flag, int startIs){
Log.d(Constant.APP_TAG,"onStartCommand service method called");
return START_STICKY;
}
public void onDestroy(){
Log.d(Constant.APP_TAG,"onDestroy service method called");
}
}
它是从使用以下代码的活动开始的:
Intent intent = new Intent(MainActivity.this, ScreenService.class);
MainActivity.this.getApplicationContext().startService(intent);
如果我在android中单击clear all,我会看到ondestroy方法正在被调用。如何保持服务始终运行或至少确保它将重新启动您需要使其成为前台服务 要启动它,请使用
ContextCompat.startForegroundService(this, new Intent(this, ScreenService.class));
在服务中的onCreate()
方法中,您需要告诉服务在前台启动:
@Override
public int onCreate() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(new NotificationChannel("some_id", "My Notification Channel"), Notification.IMPORTANCE_LOW);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "some_id")
.setContentTitle("My Notification")
.setSmallIcon(R.mipmap.ic_launcher);
startForeground(100, builder.build());
}
并在ondestory()
中调用
stopForeground(true);
START\u STICKY
不会阻止进程终止。它只是要求Android在之后及时重启服务。您将需要您的服务成为Android 8 +上的前景服务,使它能够存活超过一分钟,因此您可以考虑将此作为下一步添加。我在Android上重新启动服务后,我很好,但是它保证它会在某个时间点重新启动吗?什么时候会这样?它会发生吗?“是否保证它会在某个时间点重新启动?”——保证很少。这很可能发生。“什么时候会发生?”——操作系统决定的时候。你没有控制权。