Skip to content Skip to sidebar Skip to footer

How To Launch A Notification In Conjunction With Alarmmanager?

I am trying to figure out how I should launch a notification. Creating the notification is not what I am asking, but rather a way to launch it in the background so its unobtrusive

Solution 1:

Create a broadcastreceiver or intentservice. Then...

AlarmManageralarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);


Datedate=newDate(); //set this to some specific time
or Calendarcalendar= Calendar.getInstance();

//set either of these to the correct date and time. 

then 
Intentintent=newIntent();
//set this to intent to your IntentService or BroadcastReceiver//then...PendingIntentalarmSender= PendingIntent.getService(context, requestCode, intent,
                            PendingIntent.FLAG_CANCEL_CURRENT);
//or use PendingIntent.getBroadcast if you're gonna use a broadcast

                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), mAlarmSender); // date.getTime to get millis if using Date directly. 

If you'd like these alarms to work correctly even when the phone is restarted, then add:

<actionandroid:name="android.intent.action.BOOT_COMPLETED"/>

as intentfilter on your Receiver in the manifest and recreate your alarms in onReceive.

EDIT

When you create a BroadcastReceiver in your application, it allows to do exactly what it sounds like: receive broadcasts in the system. So for example, you might some BroadcastReceiver like so:

publicclassMyAwesomeBroadcastReceiverextendsBroadcastReceiver {

//since BroadcastReceiver is an abstract class, you must override the following:publicvoidonReceive(Context context, Intent intent) {
       //this method gets called when this class receives a broadcast
    }
}

To send broadcasts to this class explicitly, you define the receiver inside of the manifest, as follows:

<receiverandroid:name="com.foo.bar.MyAwesomeBroadcastReceiver"android:enabled="true"android:exported="false"><intent-filter><actionandroid:name="SOME_AWESOME_TRIGGER_WORD"/><actionandroid:name="android.intent.action.BOOT_COMPLETED"/></intent-filter></receiver>

Having this in the manifest gets you two things: You can send a broadcast explicitly to your receiver whenever you want by

Intenti=newIntent("SOME_AWESOME_TRIGGER_WORD");
                sendBroadcast(intent);

Also, since you've told android you'd like to receive the BOOT_COMPLETED action which is broadcast by the system, your receiver will also get called when that happens.

Solution 2:

Use AlarmManager is the best practice.

Solution 3:

Here is what you can do :

  1. Launch Service through your AlarmManager's pending intent and write your Notification code in that service.

  2. Use a database to store all your Alarms and then reschedule them on device restart by using BOOT_COMPLETEDBroadcast reciver.

Post a Comment for "How To Launch A Notification In Conjunction With Alarmmanager?"