Android: How to Use Alarmmanager

Android: How to use AlarmManager

"Some sample code" is not that easy when it comes to AlarmManager.

Here is a snippet showing the setup of AlarmManager:

AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);

mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);

In this example, I am using setRepeating(). If you want a one-shot alarm, you would just use set(). Be sure to give the time for the alarm to start in the same time base as you use in the initial parameter to set(). In my example above, I am using AlarmManager.ELAPSED_REALTIME_WAKEUP, so my time base is SystemClock.elapsedRealtime().

Here is a larger sample project showing this technique.

Alarm Manager Example

This is working code. It wakes CPU every 10 minutes until the phone turns off.

Add to Manifest.xml:

...
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
...
<receiver android:process=":remote" android:name=".Alarm"></receiver>
...

Code in your class:

package yourPackage;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;

public class Alarm extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();

// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

wl.release();
}

public void setAlarm(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}

public void cancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}

Set Alarm from Service:

package yourPackage;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

public class YourService extends Service
{
Alarm alarm = new Alarm();
public void onCreate()
{
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
alarm.setAlarm(this);
return START_STICKY;
}

@Override
public void onStart(Intent intent, int startId)
{
alarm.setAlarm(this);
}

@Override
public IBinder onBind(Intent intent)
{
return null;
}
}

If you want to set alarm repeating at phone boot time:

Add permission and the service to Manifest.xml:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
...
<receiver android:name=".AutoStart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
...
<service
android:name=".YourService"
android:enabled="true"
android:process=":your_service" >
</service>

And create a new class:

package yourPackage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AutoStart extends BroadcastReceiver
{
Alarm alarm = new Alarm();
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
alarm.setAlarm(context);
}
}
}

How to start Service using Alarm Manager in Android?

This is what I have used, for starting service after 30 seconds from current time,

Intent intent = new Intent(DashboardScreen.this, ServiceClass.class);
PendingIntent pintent = PendingIntent.getService(DashboardScreen.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);

Try it, and let me know what happen...

EDIT:

In your manifest.xml file

 <service android:enabled="true" android:name=".ServiceClass" />

Using AlarmManager() to call a function

So I just want to know how can I use intents etc to call a specific function in the service itself?

You don't, at least not directly.

You can create a service, and you can use a getService() PendingIntent in order to have AlarmManager invoke that service. However, you will get control in onStartCommand(), not some other "specific function in the service itself". You are welcome to call some other "specific function in the service itself" from onStartCommand() if you wish, but please bear in mind that you are on the main application thread and therefore cannot do very much. If you have a lot of work to do, you might consider creating an IntentService instead of a plain Service, so that you can get control on a background thread (in onHandleIntent()).

Should I use AlarmManager or Handler?

I'd say that it depends on the polling interval. I guess it's quite low in your case (around a few secs), so you should go the Handler way, or by using the Timer class.

AlarmManger is a much higher level service and it involves a larger overhead to handle this use case. When an alarm triggers, you need to handle it with BroadcastReceivers. This means that every time you handle one of these alarm, you needs to register listeners for the sensors you're interested in, which is immensely inefficient imho.

Can i use AlarmManager with LocalBroadcastManager on android?

No, it is not possible, because LocalBroadcastManager is only for your own process, and AlarmManager's backend runs in a different process. That is why there is no way to create a PendingIntent that works with LocalBroadcastManager.

start a service with Alarmmanager at specific date and time and Repeating

it's better to use job scheduler or firebase dispatcher for your requirement

refer this links
https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129

https://github.com/firebase/firebase-jobdispatcher-android



Related Topics



Leave a reply



Submit