foregroundservice thread handler delay code example
Example: 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);