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);
}
}
}