不工作服务并在关闭应用程序时停止它 (android)

Do not working service and stop it when close the application (android)

我的问题是,当我从最近的列表中清除该程序时,该服务已停止且无法运行。

这发生在 Android 5 上,在 Android 4 上没问题。 我什至在manifest中处理了服务,但是当进程开启时,服务并没有执行。(android:process=":process")

我将在Android 5 及以后页面关闭后将此服务留在前台,该服务将被删除,不会发生任何事情。

总而言之,我想每 5 秒代替我的位置和其他任务将用户显示为通知,我想在服务中执行此操作。

在activity开始服务:

if (!AppController.IsServiceRunning(TaxiService.class)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                startForegroundService(new Intent(this, TaxiService.class));
            else
                startService(new Intent(this , TaxiService.class));
} 

在manifest.xml中:

<service
       android:name=".TaxiService"
       enabled="true" />

在职:

public class TaxiService extends BaseService {

    private Timer timer;
    private TimerTask timerTask;
    private long PERIOD = 60 * 1000;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        startTimer();
        startForeground(Variable.NOTIFICATION_ID_FOR_WAITING_STUDENT , Notification.ForegroundServiceNotification());
        return START_STICKY;
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        sendBroadcast(new Intent("ServiceIsKilled"));
    }

    public void startTimer() {

        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, to wake up every 1 second
        timer.schedule(timerTask, 1000, PERIOD); //
    }

    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                WaitingStudent();
                GetLocation();
            }
        };
    }

您必须将 Intent Service 与方法一起使用

startForeground()

如果您希望您的服务在 运行

期间继续有效