Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 403
omega Avatar asked Dec 25 '22 12:12

omega


1 Answers

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);
}
like image 148
Farnabaz Avatar answered Jan 04 '23 23:01

Farnabaz