如何使Android BroadcastReceiver与AlarmManager一起使用? [英] How to make Android BroadcastReceiver work with AlarmManager?
问题描述
我具有以下代码来发布意图:
I have the following code to post intents:
alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent("myLog");
intent.putExtra("message", new Date().toString());
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME,System.currentTimeMillis()+1000,5000,alarmIntent);
以及以下接收者:
public class myReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
logText.setText(logText.getText()+"\n"+message);
}
}
private BroadcastReceiver mMessageReceiver = new myReceiver();
为什么我的 mMessageReceiver
仅用一次触发 sendBroadcast
,但是没有收到我的 alarmMgr
广播的意图?
Why my mMessageReceiver
fires only once with the sendBroadcast
, but does not receive the intents broadcasted by my alarmMgr
?
编辑:这也是我的 AndroidManifest.xml
文件的相关部分:
Also this is the related part of my AndroidManifest.xml
file:
<receiver android:name=".MainApp$myReceiver" >
<intent-filter>
<action android:name="com.example.*.*" />
</intent-filter>
</receiver>
编辑2:更多信息:
@Override public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction("myLog");
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
myIntentFilter);
}
这将覆盖 MainActivitie
s onResume()
。
推荐答案
嗯,我可能不在深度,但这对我有用。因此,在这种情况下,我要在当前时间之前设置一个闹钟(例如10分钟左右)。
Hmm I might be out of my depth here, but this works for me. So in this case, I am setting a alarm (like 10 mins or something) ahead of the current time.
// Calculate the time when it expires.
long wakeupTime = System.currentTimeMillis() + duration;
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, wakeupTime, pendingIntent);
这将设置警报关闭并唤醒我的BroadcastReceiver(AlarmReceiver)。我希望这会有所帮助,而且我在这里也不会错。
This sets an alarm to go off and to wake up my BroadcastReceiver (AlarmReceiver). I hope this helps and I am not way off base here.
这篇关于如何使Android BroadcastReceiver与AlarmManager一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!