0

I need to start the Service after several seconds. But the onStartCommand method do not get called. I test it with API level 26 and API level 24, but seems not work.

public class MyService extends Service {
    @Override
    public void onCreate() {
        setAlarm(2, 10 * 1000);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.d(LOGTAG, "onStartCommand()...");
        return super.onStartCommand(intent, flags, startId); ;
    }

    private void setAlarm(int req, long interval) {
        LogUtil.d(LOGTAG, "setAlarm()...");
        AlarmManager am = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent();
        PendingIntent pendingIntent = PendingIntent.getService(this, req,
                intent, PendingIntent.FLAG_ONE_SHOT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + interval, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + interval, pendingIntent);
        } else {
            am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + interval, pendingIntent);
        }
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
tian-yuan
  • 11
  • 3
  • You may use FirebaseJobDispatcher for this purpose.. [Check this link for the answer.](https://stackoverflow.com/questions/52722211/foregroundservice-on-android-oreo-gets-killed/52722651#52722651) – Amit Jangid Oct 22 '18 at 09:41
  • `Intent intent = new Intent();` – That's not targeting anything, so it won't do anything when it fires. If you want to start a `Service`, then it should be `Intent intent = new Intent(this, YourService.class);`. Also, if `MyService` is the `Service` you're trying to start with this, then your logic seems a little off, since `MyService`'s `onCreate()` won't run until it has already been started, so the `setAlarm()` call there doesn't make much sense. – Mike M. Oct 22 '18 at 09:54

0 Answers0