4

In my android project I have an activity that needs to run a code every minute. How can I do this? The code needs to run every minute while the activity is running and not paused (i.e. the user is seeing it and not some other activity). Also it shouldn't run when the app is minimized.

When the activity ends, the code should stop running.

Does anyone know the code for this?

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474

2 Answers2

9

You can register for android.intent.action.TIME_TICK broadcast in your activity

private BroadcastReceiver receiver;

@Overrride
public void onCreate(Bundle savedInstanceState){


  IntentFilter filter = new IntentFilter();
  filter.addAction("android.intent.action.TIME_TICK");

  receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      // TODO : codes runs every minutes
    }
  }
     registerReceiver(receiver, filter);
}

@Override
protected void onDestroy() {
  super.onDestroy();
  unregisterReceiver(receiver);
}

Broadcast Action: The current time has changed. Sent every minute. You can not receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver().

This is a protected intent that can only be sent by the system.

Constant Value: "android.intent.action.TIME_TICK"

REFERENCE

UPDATED
as Joakim mentioned in comment since you want to stop code when activity stops running, You can register the receiver in onResume and unregister it in onPause

@Override
protected void onPause() {
  super.onPause();
  unregisterReceiver(receiver);
}

@Overrride
public void onResume(){
  super.onResume();
  registerReceiver(receiver, filter);
}
Farnabaz
  • 4,030
  • 1
  • 22
  • 42
1

In onResume you can start a thread that does your code. Then sleeps for one minute. In onPause you can stop this thread(set run to false).

Something like this:

private class myThread extends Thread{
    private boolean run = true;

    public void run(){
        while(run){
            do code
            Thread.sleep(1000l * 60) // one minute
        }
     }
}
Joakim Palmkvist
  • 540
  • 2
  • 11
  • l makes the type to a long. Its not really a problem in this case, but if you would like to make the time to something like 1000 * 60 * 60 *24 *40 *60 it would be created as an int and therefore it would not be the correct amount. The value would be MAX_INTEGER instead of the correct long value – Joakim Palmkvist Mar 10 '14 at 11:53