Android: How to release resources when the application terminates?

前端 未结 5 1412
独厮守ぢ
独厮守ぢ 2020-12-18 22:13

I created an application which uses camera and during the appplication execution the screen is always on.

In the onCreate() method I added the lock:

         


        
5条回答
  •  不思量自难忘°
    2020-12-18 22:41

    It sounds as though your application is never calling release on the Wakelock - is it possible that it's throwing an exception earlier in onStop or onPause? I'd include some logging where you're calling release to confirm it's being executed.

    In any case, you'll definitely want to move the acquire and release methods into onResume and onPause respectively. The code you've got will only acquire the WakeLock the first time your application is started.

    Thanks the Android's background processing your code has a potential imbalance. If the user presses the home key to switch applications the lock will be released. If they switch back to your app onCreate won't be called, so the lock will never be acquired.

    Your best bet is to construct the WakeLock in onCreate (as you have), acquire the lock in onResume and release it in onPause (including the call to isHeld). This will guarantee that the lock will be held whenever your application is in the foreground.

提交回复
热议问题