By using AlarmManager
and Service
you can achieve this.
Read documentation here AlarmManager.
Here is code block to set and remove the alarm for repeating tasks
To set The alarm
public void createAlarm() {
ServerDetails serverDetails = new ServerDetails(this);
if (serverDetails.isSettingsOK()) {
Intent i = new Intent(this, MyService.class);
if (PendingIntent.getService(this, 0, i,
PendingIntent.FLAG_NO_CREATE) == null) {
PendingIntent pendingIntent = PendingIntent.getService(this, 0,
i, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
int interval = 2 * 60 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + interval, interval,
pendingIntent);
Log.d("alarm", "alarm set successfully " + interval);
} else {
Log.d("alarm", "alarm already set");
}
}
}
To Cancel the alarm
public void cancelAlarm() {
Intent i = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, i,
PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null) {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
Log.d("alarm", "alarm cancelled");
}
}
This is the service which will run in background when alarm activates.
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("service Created", "service created");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
doYourTaskHere();
}
private void doYourTaskHere() {
// call here webservice or any other task here which you want to do in every two minutes
}
}