Android Services: START_STICKY does not work on Kitkat

前端 未结 5 1087
执笔经年
执笔经年 2021-01-31 20:02

I am using services in an application to listen for how many times the user presses his/her power button. The implementation was working fine on all devices. But when I tested t

5条回答
  •  面向向阳花
    2021-01-31 20:28

    Seems that this is a bug present in Android 4.4, got around it with the following:

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        // TODO Auto-generated method stub
        Intent restartService = new Intent(getApplicationContext(),
                this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI);
    
    }
    

    So this is a method that is overridden in the Service class itself. The reason that I am using the AlarmManager is so that Kitkat does not kill my service.

提交回复
热议问题