简体   繁体   中英

AlarmManager with notification not firing

I'm making an app with a persistent notification, so I'm trying to use AlarmManager to periodically update the notification.

I've extended BroadcastReceiver :

public class Notification extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        updateNotification();
    }

If I just run notification.onReceive, the notification updates as expected, so I believe the problem isn't here. I've also added code in 'MainActivity.onCreate that is supposed to create and run an alarmManager`:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent alarmIntent = new Intent(getApplicationContext(), Notification.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    manager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 5000,
        pendingIntent);
}

Nothing appears to happen when I run the app, but I see the AlarmManager service draining my battery, so I'm pretty sure something is running. I think the problem is with pendingIntent ; Either that or I am missing something (haven't done anything else in the project relating to AlarmManager ).

Coding this on Android Studio and running it on my Note 4. minSdkVersion 19 , targetSdkVersion 21

Any help is greatly appreciated. Thanks!

Ok, turns out the example I was looking at didn't mention that I had to add

<receiver android:name=".Notification" />

to the manifest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM