How do I repeat a method every 10 minutes after a button press and end it on another button press

Create a BroadcastReceiver

public class AlarmReceiver extends BroadcastReceiver
{   

 @Override
 public void onReceive(Context context, Intent intent)
  {   
    //get and send location information
  }
}

and add the same to your AndroidManifest so that the Receiver is registered

<receiver
    android:name="com.coderplus.AlarmReceiver"
    android:exported="false">
</receiver>

Now you can set a repeating alarm from your Activity which will invoke the receiver every 10 minutes:

AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),600000,
                                                                      pendingIntent);

and to cancel the alarm, call cancel() on the AlarmManager using an equivalent PendingIntent

AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.cancel(pendingIntent);

or if you don’t want to use AlarmManager / BroadcastReceiver, then something like this will help you out. Before you go for it, check – difference between timer and alarmmanager

private class MyTimerTask extends TimerTask {
    @Override
    public void run() {           
      //get and send location information 
    }
}

initialize the Timer and Timer task:

Timer myTimer = new Timer();
MyTimerTask myTimerTask= new MyTimerTask();

Stopping or starting the Timer

//to Stop
myTimer.cancel();
//to start
myTimer.scheduleAtFixedRate(myTimerTask, 0, 600000); //(timertask,delay,period)

Refer
http://developer.android.com/reference/java/util/TimerTask.html

http://developer.android.com/reference/java/util/Timer.html

Leave a Comment