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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With