How to Create a Persistent Alarmmanager

AlarmManager - How to repeat an alarm at the top of every hour?

When you set alarms you have two times: First trigger time, and the next trigger interval.

You then have to calculate the remaining miliseconds to the next top of the hour, then set one hour for the repeating interval.

// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += remainingMilisecondsToTopHour;
long a=c.getTimeInMillis();

// Schedule the alarm!
AlarmManager am = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME,
c.getTimeInMillis(), 1*60*60*1000, sender);

AlarmManager alternatives for persistent frequent scheduling

As a workaround you can set up 60 alarms to get flexible solution for your current implementation. Check OS version and set up as many alarms as you need.

But for a long-term solution I suggest you to implement sticky foreground service which would work similar to music player. Something simple like Handler.postDelayed should be enough to keep it alive. The reason to do this way is that alarms are not accurate and it is always better to have some control on the process.

Will AlarmManager work if my application is not running?

From AlarmManager

AlarmManager provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.


In simple way, it will work until your device has been rebooted.

You can read Android AlarmManager after reboot where @CommonsWare has been given a link of his sample application which persists Alarm even after device reboot.


Please ignore below section, it seems not valid. I will remove in future

You can read more about application kill at How to create a persistent AlarmManager, and How to save Alarm after app killing? can give you the idea about how to handle such issue (to persist alarm if application has been killed).

How to create persistent alarms even after rebooting

With this code will my alarms will be deleted after reboot ? If yes, how to overcome this.

Yes alarm will get deleted, to overcome this, you need to use Android's Component called BroadcastReceiver as follows,

First, you need the permission in your manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Also, in your manifest, define your service and listen for the boot-completed action:

<receiver
android:name=".receiver.StartMyServiceAtBootReceiver"
android:enabled="true"
android:exported="true"
android:label="StartMyServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

Then you need to define the receiver that will get the BOOT_COMPLETED action and start your service.

public class StartMyServiceAtBootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceIntent = new Intent("com.myapp.NotifyService");
context.startService(serviceIntent);
}
}
}

And now your service should be running when the phone starts up.

2 For Vibration

Again you need to define a permission in AndroidManifest.xml file as follows,

<uses-permission android:name="android.permission.VIBRATE"/>

Here is the code for vibration,

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Vibrate for 300 milliseconds
v.vibrate(300);

Remove Persistent Notification with Alarm Manager

I think you know that you can cancel your notification by its id (you set it to 100 in ur code). To implement expiration, you just need to set another one-time (non-repeating) alarm that cancels your notification. You set that alarm right after you show your notifcation like this:

notificationManager.notify(100,builder.build());

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent=new Intent(context,NotificationCancelReceiver.class);
intent.putExtra("notification_id", 100);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, 0);

// Here's two way to fire a one-time (non-repeating) alarm in one hour
// One way: alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 60 * 60 * 1000, pendingIntent);
// Another way:
alarmManager.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 60 * 60 * 1000, pendingIntent);
// If you want to wake up the system with this alarm use ELAPSED_REALTIME_WAKEUP not ELAPSED_REALTIME

And here's your NotificationCancelReceiver that cancels notification:

@Override
public void onReceive(Context context, Intent intent) {
int id = intent.getIntExtra("notification_id", -1);
if (id != -1) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
}
}

And make sure that you added reciever in AndroidManifest.xml

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

Hope this helps!



Related Topics



Leave a reply



Submit