service repeatr a function after amin android code example
Example 1: run code periodically android
Handler myHandler = new Handler();
int delay = 1000;
myHandler.postDelayed(new Runnable() {
public void run() {
System.out.println("myHandler: here!");
handler.postDelayed(this, delay);
}
}, delay);
Date when = new Date(System.currentTimeMillis());
try {
Intent someIntent = new Intent(someContext, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0,
someIntent,
PendingIntent.FLAG_CANCEL_CURRENT
);
AlarmManager alarms = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE
);
alarms.setRepeating(
AlarmManager.RTC_WAKEUP,
when.getTime(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent
);
} catch(Exception e) {
e.printStackTrace();
}
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
System.out.println("MyReceiver: here!")
}
}
MyReceiver receiver = new MyReceiver();
context.registerReceiver(receiver, intentFilter);
Example 2: android studio repeatable
private int mInterval = 5000;
private Handler mHandler;
@Override
protected void onCreate(Bundle bundle) {
mHandler = new Handler();
startRepeatingTask();
}
@Override
public void onDestroy() {
super.onDestroy();
stopRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
@Override
public void run() {
try {
updateStatus();
} finally {
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}