Required to implement a call to a specific function once every N hours. But if we use TimerTask, then when the backlight of the phone goes out, it stops being executed, in other words, it works only when the phone is awake. I also need to keep track of constantly, even if the phone is asleep (Not turned off!).
- read about services if the usual timer does not fit - Gorets
- I know how services work. Service is a process that hangs in the system, from which it must perform something in N hours. More precisely how he will check? - AndroidDev
- look at the system time - if 4 hours has passed from the last event - repeat it again - Gorets
- Not logical. It must be that - that will make him look at the time :) - AndroidDev
- the service looks at time all the time =) but why doesn't Timer () suit? in the same service .. - Gorets
|
3 answers
First, we need to add WAKE_LOCK permission to the manifest.
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission> <receiver android:process=":remote" android:name="AlarmClock"></receiver> Second, connect the AlarmManager
public class AlarmClock extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SOME_TAG"); wl.acquire(); // TODO: Что-то делаем wl.release(); } public void ToggleAlarm(Context context, Boolean fire) { AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, AlarmClock.class); PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); if (fire) { am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 3600000, pi); } else { am.cancel(pi); } } } |
Start a simple Thread, which let's say every N seconds starts up some kind of crap. Like that:
public class Waiter extends Thread { private static final String TAG=Waiter.class.getName(); private long period; private boolean stop; public Waiter(long period) { this.period=period; stop=false; } public void run() { do { try { Thread.sleep(period); } catch (InterruptedException e) { Log.d(TAG, "Waiter interrupted!"); stop=true; break; } //запускаем свою хрень } while(!stop); Log.d(TAG, "Finishing Waiter thread"); } public synchronized void forceStop() { this.stop=true; } } |