0

I am calling a service from an AlarmManager onReceive, below is the implementation. I want to know if this implementation of a wake lock is fine and will it suffice my needs?

This is the onStart function in my Service Class:

@Override
public void onStart(Intent intent, int startId) {
    WakeLock wakeLock = null;
    try{
        PowerManager mgr = (PowerManager)getApplicationContext()
            .getSystemService(Context.POWER_SERVICE);
        wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
        wakeLock.acquire();
        //For time consuming an long tasks you can launch a new thread here
        Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
    }catch(Exception e){
    }finally{
        wakeLock.release();
    }
}
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
User3
  • 2,465
  • 8
  • 41
  • 84
  • Have you actually tried it? If so, does it work? You haven't explained anything about how your service works or what it does or what your "needs" are. Also `onStart(...)` was deprecated in API 5 - you should be using `onStartCommand(...)`. – Squonk Jan 21 '14 at 09:10
  • Yes I have tried it and that is why I posted it here to know if i am missing something, this works under normal conditions but the prime reason of posting was to know about its execution in cases other than the 'normal' ones. – User3 Jan 21 '14 at 09:52
  • See like you pointed out about deprecation :) I have isolated the code into a second project, to check on functionality, right now thge service only displays a toast message but in actual program it will be implemented to do some huge database manuplation which I intend to be doing in a background thread, also in this case I want to know if I can use an async task and cancel the wakelock in postExecute? – User3 Jan 21 '14 at 09:54
  • 1
    You may need a null check in finally - also do not catch Exception it is considered bad style - catch the specific exceptions thrown – Mr_and_Mrs_D Jan 21 '14 at 14:49

1 Answers1

0

Yep, that should work fine. Although it won't work if you spin up a new Thread, in that case wakelock.release() will be called before the Thread finishes.

You might want to check CommonsWare's Wakeful service though. That services handles the wakelock for you, ensuring that you have a Wakelock during the service, and it'll release it as soon as you stop the service.

fifarunnerr
  • 617
  • 4
  • 12
  • Thanks for the insight mate :) can I implement an async task and just cancel the wake lock in onPostExecute? – User3 Jan 21 '14 at 09:54
  • 1
    @user2822178: Yes go for [WakefulIntentService](https://github.com/commonsguy/cwac-wakeful) - do not reinvent the wheel - moreover there are various subtle points : http://stackoverflow.com/questions/20074035/wakefulintentservice-implementation-clarifications – Mr_and_Mrs_D Jan 21 '14 at 13:48
  • Thanks, that is an insightful post! – User3 Jan 22 '14 at 03:21