How to make Android BroadcastReceiver work with Al

2019-02-25 23:52发布

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条回答
Explosion°爆炸
2楼-- · 2019-02-26 00:31

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.

查看更多
登录 后发表回答