我可以使用AlarmManager与LocalBroadcastManager在Android?(C

2019-06-27 08:32发布

我有这样的代码:

private AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
private PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, new Intent("my action-name"), 0);

alarmManager.setInexactRepeating((int)AlarmManager.ELAPSED_REALTIME_WAKEUP,     SystemClock.elapsedRealtime() + autoUpdateIntervalInMinutes * 60 * 1000,  autoUpdateIntervalInMinutes * 60 * 1000, alarmIntent);

但我想改变这种为LocalBroadcastManager。 这可能吗?

Answer 1:

不,这是不可能的,因为LocalBroadcastManager是只为自己的过程,并AlarmManager的后端在不同的进程中运行。 这就是为什么没有办法创造PendingIntent与工程LocalBroadcastManager



Answer 2:

但是,你可以注册一个BroadcastReceiver基本上转换的“全球通”广播到LocalBroadcast:

public class AutoUpdateBroadcastReceiver extends BroadcastReceiver {

  private static final String TAG = AutoUpdateBroadcastReceiver.class.getSimpleName();

  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d(TAG, ".onReceive");
    LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(context);
    lbm.sendBroadcast(intent);
  }
}


文章来源: Can i use AlarmManager with LocalBroadcastManager on android?