Answer the question
In order to leave comments, you need to log in
How to execute the code with a certain frequency?
There is a need to execute the code, say, with an interval of 1 second, while the application / activity can be minimized and the screen can be turned off on the device in general. What is the more appropriate and architecturally correct solution to use for this?
Answer the question
In order to leave comments, you need to log in
AndroidManifest.xml
...
<receiver android:name=".MyAlarmReceiver" />
<service android:name=".MyService" android:process=":my_app_alternate" android:enabled="true" />
...
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);
}
}
}
}
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;
}
}
}
WorkManager has restrictions from below. Well, no one canceled doze mode. So in this version, as described, it will not work.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question