Using a wakelock in a service Android 1.5

2019-03-20 19:41发布

问题:

Hello I am trying to use a service to control a wakelock so I can permanently leave the screen on when my application is running. I create the wakelock and activate it in onCreate() and release it in onDestroy() however I get the error "wl cannot be resolved". Can someone explain how I can get over this? Code below:

public class WakeLockService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }  
    @Override
    public void onCreate() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
        wl.acquire();
    }
    @Override
    public void onDestroy() {
        wl.release();
    }
}

回答1:

Aren't you missing the line

    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");

in onDestroy()? It is a local variable in onCreate(), but it is not declared in onDestroy() at all.

Or, more probable, you may want to make it a field of class WakeLockService instead of a local variable.



回答2:

Well, even if you would use an instance variable I would think this is not the way to do it. Who is gonna call destroy()? I hope not you, it's the OS job to do so. But when you are holding a wake lock it is highly unlikely that your destroy() method get called, because the OS will first destroy other activities/services.

Besides that, it's way too late to acquire the wake lock in the onCreate() method. Before onCreate() is reached the phone might have gone to sleep already when you trigger the Service from an alarm vs. from an activity that is in the background.

It's hard to say what you should make differently as you don't give much context. The usual course of events is this. A BroadcastReceiver gets called and in the onReceive() you acquire the wake lock and put it in a static variable on your service. When the service is done it should call stopSelf(), release the wake lock and then null the static variable that keeps a reference to the lock.

Also, if you use a Service a full wake lock is very likely not what you want, but a partial wake lock is. You don't need the screen to stay on, right?

Sorry, but wake locks are really complicated to use, because of exactly the issues I described above. It's definitively an advanced topic and it's easy to screw up. If you do, your app will get very ugly comments, because holding on for too long is a major offense as it drains the battery. Don't take this the wrong way please, but given the nature of the problem you posted here (syntax / compiler error) I would strongly suggest to search for a solution without a Service and wake lock.