Невозможно включить тревогу, если startForegroundService не используется после перезагрузки - PullRequest
0 голосов
/ 23 января 2020

Если fooAlarm () вызывается из приложения, все работает отлично:

  public static void fooAlarm(
            Context context,
            int iRequestCode) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(context, FooIntentService.class);
        intent.putExtra("RequestCode", iRequestCode);
        PendingIntent service = PendingIntent.getService(
                context,
                iRequestCode,
                intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        am.set(
                AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + 5000,
                service);

    }


public class FooIntentService extends IntentService {

    public FooIntentService() {
        super("FooIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("debug", "onHandleIntent has been called");
    }
}

Однако, если он вызывается из BroadcastReceiver после перезагрузки, сигнал тревоги не срабатывает:

public class OnBootReceiver extends BroadcastReceiver {
    public OnBootReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
                fooAlarm(context, iRequestCode);
                 Log.d("debug", "fooAlarm() has been called.");
            } else {
                utility.doNothing();
            }
        } catch (Exception ex) {

        }
    }
}

Единственный способ заставить его работать - использовать startForegroundService () следующим образом:

 public class OnBootReceiver extends BroadcastReceiver {
    public OnBootReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
                 context.startForegroundService(new Intent(context, FooIntentService.class));
                 fooAlarm(context, iRequestCodd);
            } else {
                utility.doNothing();
            }
        } catch (Exception ex) {

        }
    }
}

Я хочу избежать использования startForegroundService (). Есть ли способ сделать это?

...