omega
omega

Reputation: 43833

How to run code every minute in android activity?

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

Upvotes: 4

Views: 2599

Answers (2)

Farnabaz
Farnabaz

Reputation: 4066

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);
}

Upvotes: 9

Joakim Palmkvist
Joakim Palmkvist

Reputation: 540

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
        }
     }
}

Upvotes: 1

Related Questions