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