BroadcastReceiver, Service and Wakelock

im gets the intent in the broadcast receiver, and then I start the service to do more work. Now, what if the device is sleeping and it happens, I have to get Wakelock (AlarmManger?) and why do I need it? my service will stop working if the device goes to sleep without receiving wakelock.

+4
source share
3 answers

Now, what if the device falls asleep and this happens, I need to get Wakelock (AlarmManger?) and why do I need it?

If the device is sleeping from the very beginning, you will not “receive the intent in the broadcast receiver” because the device is sleeping.

I need to get Wakelock (AlarmManger?) And why do I need it?

You do not need it if you do not want the device to work while you are doing some work.

my service will stop working if the device goes to sleep without receiving wakelock.

Yes.

+5
source

It seems that the native WakefulBroadcastReceiver would be the perfect solution for you. You need to expand this, not the regular BroadcastReceiver, and start the service in onReceive () in wake mode:

startWakefulService(context, service); 

and let your work be done in the onHandleIntent () service by calling

 MyWakefulReceiver.completeWakefulIntent(intent); 
+1
source
 public class WakeLockManager extends BroadcastReceiver { private static WakeLock mWakeLock; private String LCLT; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Consts.WAKELOCK_INTENT)) { Log.v("wakelock", "GOT THE wakelock INTENT"); boolean on = intent.getExtras().getBoolean("on"); if (mWakeLock == null) { PowerManager pm = (PowerManager) context .getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Breeze WakeLock"); } if (on) { if (!mWakeLock.isHeld()) { mWakeLock.acquire(); Log.v("wakelock", "acquiring wakelock"); } } else { if (mWakeLock.isHeld()) { Log.v("wakelock", "releasing wakelock"); mWakeLock.release(); } mWakeLock = null; } } } } 

look at the code above. Paste it into a separate class file and in your manifest define it for some kind of user intention ... now that this class will respond to user intentions ... just pass this intention and you can turn wakelock on or off throughout your application, since wakelock is static. For instance:

 public void setWakeup(boolean status) { Intent wakelock_Intent = new Intent(CUSTOM_INTENT); wakelock_Intent.putExtra("on", status); this.sendBroadcast(wakelock_Intent); } 

above would be defined in your alarm code so that it plans to call

0
source

All Articles