AndroidManifest.xml
...
<receiver android:name=".MyAlarmReceiver" />
<service android:name=".MyService" android:process=":my_app_alternate" android:enabled="true" />
...
MyAlarmReceiver.java
public class MyAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MyService.class));
setupAlarm(context);
}
final long intervalMs = 60000; // Интервал в миллисекундах
public static final void setupAlarm(Context context) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
if (am != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + intervalMs, pi);
} else {
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + intervalMs, pi);
}
}
}
}
MyService.java
public class MyService extends Service {
Thread workThread = null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (workThread == null) {
workThread = new Thread(run);
workThread.start();
}
return Service.START_STICKY;
}
final Runnable run = new Runnable() {
@Override
public void run() {
try {
while (true) {
//todo Что там надо делать раз в секунду
Thread.sleep(1000);
}
} catch (InterruptedException iex) { }
workThread = null;
}
}
}
Когда необходимо запустить выполнение кода, вызываем MyAlarmReceiver.setupAlarm. Последующие вызовы происходят из MyAlarmReceiver.onReceive.