How to lock the screen of an android device

后端 未结 3 1472
遥遥无期
遥遥无期 2020-12-01 08:59

I want to implement the screen lock functionality in my application, but currently I can\'t get it to work. I have an alertDialog which will request input from the user thro

相关标签:
3条回答
  • 2020-12-01 09:08

    There are two way you can lock the screen:

    PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    
    // Choice 1
    manager.goToSleep(int amountOfTime);
    
    // Choice 2
    PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Your Tag");
    wl.acquire();
    wl.release();
    

    This permission is needed:

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

    UPDATE:

    The screenbrightness has a value between 0 and 1. If the value is set to a negative number, it will be set to the default screen brightness. By changing the brightness to 0, the brightness will be low enough that the screen will automatically turn off.

    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.screenBrightness = 0;
    getWindow().setAttributes(params);
    

    This and this might help you further.

    UPDATE 2:

    Here are some links to methods that have been used for locking the screen:

    http://rdcworld-android.blogspot.in/2012/03/lock-phone-screen-programmtically.html

    http://developer.android.com/guide/topics/admin/device-admin.html#lock

    0 讨论(0)
  • 2020-12-01 09:20

    Try to override it like this:

     @Override
     protected void onResume() {
        // TODO Auto-generated method stub
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.screenBrightness = 1;
        getWindow().setAttributes(params);
        super.onResume();
    }
    

    It does help me :D

    0 讨论(0)
  • 2020-12-01 09:26

    I just spent an entire day deciding whether to just change the screen brightness to 0 or just proc the lock itself.

    Here is an entire example on github for those of you who would like to see all of the required code in action! Don't forget to check out the lock.xml file! That is where all of the uses-policies goes! looks a bit like this exactly!

    <?xml version="1.0" encoding="UTF-8"?>
    <device-admin xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <uses-policies>
    
            <force-lock />
        </uses-policies>
    
    </device-admin>
    
    0 讨论(0)
提交回复
热议问题