Commonsware's WakefulIntentService works beautifully but there are some things I do not quite get. Below is the core of the service - a stripped down version of the source :
class WIS extends IntentService { private static final String NAME = WIS.class.getName() + ".Lock"; private static volatile WakeLock lockStatic = null; synchronized private static PowerManager.WakeLock getLock(Context context) { if (lockStatic == null) { PowerManager mgr = (PowerManager) context .getSystemService(Context.POWER_SERVICE); lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NAME); lockStatic.setReferenceCounted(true); } return (lockStatic); } public static void startWIS(Context ctxt, Intent i) { getLock(ctxt.getApplicationContext()).acquire(); ctxt.startService(i); } public WIS(String name) { super(name); setIntentRedelivery(true); } @Override public int onStartCommand(Intent intent, int flags, int startId) { PowerManager.WakeLock lock = getLock(this.getApplicationContext()); if (!lock.isHeld() || (flags & START_FLAG_REDELIVERY) != 0) { // ? lock.acquire(); } super.onStartCommand(intent, flags, startId); return (START_REDELIVER_INTENT); } @Override protected void onHandleIntent(Intent intent) { try { // do your thing } finally { PowerManager.WakeLock lock = getLock(this.getApplicationContext()); if (lock.isHeld()) lock.release(); } } }
Questions
- What happens if the process is killed just after the
onReceive()
of our alarm receiver returns ? That is if serviceonCreate()
(if the service is not already instantiated) oronStartCommand()
never run. AFAIK a process killed takes its locks with it. Or is this an impossible scenario ? - In view of the previous should
(flags & START_FLAG_RETRY)
be added ? - Why the
if (!lock.isHeld())
check ? - Why is
this.getApplicationContext()
needed ? is notthis
enough ?