Android startForeground 在 activity 关闭后重新启动

Android startForeground get restarted after activity close

我目前正在尝试在前台服务上执行一些代码。 在 android 6 和 android 7 上,我的 phone 一切正常。 但是当我尝试使用 android 5 设备时,服务会在 activity 被销毁时终止。

我在调用 bindService 之前手动启动服务。 我在 onStart 上调用 bindService,在 onStop 方法上调用 unbindService。

这是我的服务

public class ExecutionService extends Service {
    private final IBinder binder = new ExecutionBinder();
    private static final int NOTIFICATION_ID = 1;
    private static final String STOP_ACTION = "STOP_ACTION";

    private Notification.Builder builder;
    private boolean timerHeaderVisible;
    private NotificationManager nm;
    private Intent notificationIntent;
    private PendingIntent contentIntent;

    public class ExecutionBinder extends Binder {
        public ExecutionService getService() {
          return ExecutionService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        builder = new Notification.Builder(this);

        Intent stopSelf = new Intent(this, ExecutionService.class);
        stopSelf.setAction(STOP_ACTION);
        PendingIntent closePendingIntent = PendingIntent.getService(this, 0, stopSelf,PendingIntent.FLAG_CANCEL_CURRENT);

        builder.setSmallIcon(R.drawable.ic_time)
                .setContentTitle(getString(R.string.app_name))
                .addAction(R.drawable.ic_stop, getString(R.string.stop), closePendingIntent)
                .setVibrate(new long[]{0L});

        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_NO_CLEAR;
        startForeground(NOTIFICATION_ID, notification);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        if(notificationManager != null)
            notificationManager.cancelAll();
        isStarted = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent != null && intent.getAction() != null && intent.getAction().equals(STOP_ACTION)) {
            stopForeground(true);
            stopSelf();
        }

        return START_STICKY;
    }

}

我注意到从未调用过 onDestroy 方法,但调用了两次 onCreate 方法。

如何让它在 android 5 台设备上运行? 感谢您的帮助。

尝试删除此方法

 @Override
    public void onDestroy() {
        super.onDestroy();
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        if(notificationManager != null)
            notificationManager.cancelAll();
        isStarted = false;
    }

终于找到问题所在了。我在 activity 的 onDestroy 中调用一个空对象的方法。然后服务崩溃了(只有 android ?)。 我没有在控制台中看到错误,因为应用程序正在重新启动。