WakefulIntentService Implementation Enhancements

Commonsware WakefulIntentService works beautifully, but there are some things that I don’t quite understand. 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 immediately after the return of onReceive()our emergency receiver? That is, if the service onCreate()(if the service has not yet been created) or onStartCommand()never starts. AFAIK killed the process by running its locks. Or is this an impossible scenario?
  • Given the previous should be added (flags & START_FLAG_RETRY)?
  • Why check if (!lock.isHeld())?
  • Why is it required this.getApplicationContext()? not enough this?
+4
2

AFAIK, , .

.

?

, , , .

START_FLAG_RETRY?

START_FLAG_REDELIVERY. AFAIK, START_REDELIVER_INTENT, RETRY REDELIVERY. , .

if (! lock.isHeld())?

release() WakeLock, , . , . ; .

this.getApplicationContext()? ?

WakeLock, . , getSystemService() Context, PowerManager. , , Context WakeLock. , , getApplicationContext(), WakeLock , , Context, "", - singleton, , , -leaked.: -)

+5

, , , , () (!). ref volatile , .

, . , Lock = new Object() , . , , . , . .

+1

All Articles