开发者

How to get an Android WakeLock to work?

开发者 https://www.devze.com 2022-12-16 12:41 出处:网络
My WakeLock isn\'t keeping my device awake. In OnCreate() I\'ve got: PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

My WakeLock isn't keeping my device awake.

In OnCreate() I've got:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "My Tag");
mWakeLock.acquire();

then:

new CountDownTimer(1320000, 200) {

    public void onTick(long millisUntilFinished) {
        开发者_如何学编程// I update a progress bar here.                                         
    }

    public void onFinish() {
        // I finish updating the progress bar.
        mWakeLock.release();
    }
}.start();

The screen turns off before the timer finishes, how can I make the screen stay visible?

mWakeLock is a field previously declared like so:

private PowerManager.WakeLock mWakeLock;

My device uses Android 1.6. I would really appreciate any help to resolve this.


WakeLock doesn't usually cause Reboot problems. There may be some other issues in your coding. WakeLock hogs battery heavily, if not released after usage.

WakeLock is an Inefficient way of keeping the screen on. Instead use the WindowManager to do the magic. The following one line will suffice the WakeLock. The WakeLock Permission is also needed for this to work. Also this code is more efficient than the wakeLock.

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

You need not relase the WakeLock Manually. This code will allow the Android System to handle the Lock Automatically. When your application is in the Foreground then WakeLock is held and else android System releases the Lock automatically.

Try this and post your comment...


Do you have the required permission set in your Manifest?

<uses-permission android:name="android.permission.WAKE_LOCK" />


You just have to write this:

 private PowerManager.WakeLock wl;

    protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNjfdhotDimScreen");
    }//End of onCreate

            @Override
        protected void onPause() {
            super.onPause();
            wl.release();
        }//End of onPause

        @Override
        protected void onResume() {
            super.onResume();
            wl.acquire();
        }//End of onResume

and then add permission in the manifest file

 <uses-permission android:name="android.permission.WAKE_LOCK" />

Now your activity will always be awake. You can do other things like w1.release() as per your requirement.


Keep the Screen On

First way:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Second way:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>

Keep the CPU On:

<uses-permission android:name="android.permission.WAKE_LOCK" />

and

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
wakeLock.acquire();

To release the wake lock, call wakelock.release(). This releases your claim to the CPU. It's important to release a wake lock as soon as your app is finished using it to avoid draining the battery.

Docs here.


Add permission in AndroidManifest.xml, as given below

<uses-permission android:name="android.permission.WAKE_LOCK" />

preferably BEFORE your <application> declaration tags but AFTER the <manifest> tags, afterwards, try making your onCreate() method contain only the WakeLock instantiation.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "My Tag");
}

and then in your onResume() method place

@Override
public void onResume() {
   mWakeLock.aquire();
}

and in your onFinish() method place

@Override
public void onFinish() {
   mWakeLock.release();
}


To achieve the same programmatic you can use following

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

or adding following in layout also will perform the above task

 android:keepScreenOn="true"

The details you can get from following url http://developer.android.com/training/scheduling/wakelock.html

I have used combination of following to wake my screen when keyguard locked and keep my screen on

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);


I am having a similar problem. I can get the screen to stay on, but if I use a partial wake lock and the screen is turned off, my onFinish function isn't called until the screen is turned on.

You can check your wake lock using mWakeLock.isHeld(), first of all, to make sure you're getting it. Easiest way is to add that to the code, set a breakpoint on it in the debugger, and then check it.

In my case, I'm getting it, but the partial wake lock doesn't seem to be doing anything. Here's my working code for the screen dim lock.

protected void setScreenLock(boolean on){
        if(mWakeLock == null){
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |
                                        PowerManager.ON_AFTER_RELEASE, TAG);
        }
        if(on){
         mWakeLock.acquire();
        }else{
            if(mWakeLock.isHeld()){
                mWakeLock.release();
            }
         mWakeLock = null;
        }

    }

ADDENDUM:

Droid Eris and DROID users are reporting to me that this DOES NOT work on their devices, though it works fine on my G1. What device are you testing on? I think this may be an Android bug.


Try using the ACQUIRE_CAUSES_WAKEUP flag when you create the wake lock. The ON_AFTER_RELEASE flag just resets the activity timer to keep the screen on a bit longer.

http://developer.android.com/reference/android/os/PowerManager.html#ACQUIRE_CAUSES_WAKEUP


Thank you for this thread. I've been having a hard time implementing a Timer in my code for 5 minutes to run an activity, because my phone I have set to screen off/sleep around 2 minutes. With the above information it appears I have been able to get the work around.

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /* Time Lockout after 5 mins */
    getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

       public void run() {

        Intent i = new Intent(AccountsList.this, AppEntryActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        finish();
        return;

       }

    }, 300000); 
    /* Time Lockout END */
 }


sample code snippet from android developers site

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  }

Best Practices for Background Jobs


{PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MyWakeLock"); 
wakeLock.acquire();}

use this code and don't forget to permit wakelock in android manifest


Make sure that mWakeLock isn't accidentally cleaned up before you're ready to release it. If it's finalized, the lock is released. This can happen, for example, if you set it to null and the garbage collector subsequently runs. It can also happen if you accidentally set a local variable of the same name instead of the method-level variable.

I'd also recommend checking LogCat for entries that have the PowerManagerService tag or the tag that you pass to newWakeLock.


Add permission in AndroidManifest.xml:

<uses-permission android:name="android.permission.WAKE_LOCK" />

Then add code in my.xml:

android:keepScreenOn="true"

in this case will never turn off the page! You can read more this


If your use-case is making the screen (activity) ON while doing an action, you shouldn't use WakeLock.

The best way to do that is by enabling the flag FLAG_KEEP_SCREEN_ON.

You can do it programmatically:

class MainActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }
}

Or in your application's layout XML file, by using the android:keepScreenOn attribute:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>

Keep the screen on


If that's not the case, check these alternative solutions according to your use-case Alternatives to using wake locks

0

精彩评论

暂无评论...
验证码 换一张
取 消