How to make Android BroadcastReceiver work with AlarmManager?

走远了吗. 提交于 2019-12-20 02:57:19

问题


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

And the following receiver:

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

Why my mMessageReceiver fires only once with the sendBroadcast, but does not receive the intents broadcasted by my alarmMgr?

EDIT: 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>

EDIT 2: More info:

@Override public void onResume() {
    super.onResume();
    // Register mMessageReceiver to receive messages.
    IntentFilter myIntentFilter = new IntentFilter();
    myIntentFilter.addAction("myLog");
    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
            myIntentFilter);
}

This overrides MainActivities onResume().


回答1:


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

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.



来源:https://stackoverflow.com/questions/31835099/how-to-make-android-broadcastreceiver-work-with-alarmmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!