简体   繁体   中英

How to send notification by timing or interval even the app is not running in Android?

I am absolute beginner to Android. Now I am about to create a small project on my own. That will be a to-do app. And what I want to do is, user set a task for specific date and time. User may set multiple tasks. What I want to do is, I want to send notification to user when then time is the same as the time that is set for task even if the app is closed. How can I achieve that? I searched online todo app tutorials. But they do not include that feature.

I found this: How to send notification to specific people even if the app is closed? . I think that is not what I want. I found some. But they are incomplete. So it is very difficult to follow for an absolute beginner.

Use Alarm Manager to schedule an event for the specific date and time. That will get executed even if your app is in the background by registering broadcast receiver in the manifest file.

Once the broadcast receiver runs, you send a notification

Hope this gives you the beginning

Create wakeLocker class and call it in broadcastreceiver class.

public abstract class WakeLocker {

private static PowerManager.WakeLock wakeLock;

public static void acquire(Context context) {
    if (wakeLock != null) wakeLock.release();

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
            PowerManager.ACQUIRE_CAUSES_WAKEUP |
            PowerManager.ON_AFTER_RELEASE, "WakeLock");
    wakeLock.acquire();
}

public static void release() {
    if (wakeLock != null) wakeLock.release(); wakeLock = null;
}

more more details, refer http://developer.android.com/reference/android/os/PowerManager.WakeLock.html ?

Call the method (acquire) like this.

  public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
             WakeLocker.acquire(context);
            // your code
        }}

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