简体   繁体   中英

Lock The Phone in Android programmatically?

I was trying to lock the device and trying to enable it by using the following code but it is not working.I have also taken the two following permisson and not showing that that phone is locked...I also tried to unlock it again.

public class LockPhoneActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */

    Button lock, unlock;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        lock = (Button) findViewById(R.id.button1);
        unlock = (Button) findViewById(R.id.button2);

        lock.setOnClickListener(this);
        unlock.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {

        case R.id.button1:

            KeyguardManager mgr = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
            KeyguardLock lock = mgr.newKeyguardLock(KEYGUARD_SERVICE);
            lock.reenableKeyguard();

            Toast.makeText(getApplicationContext(), "Locked", Toast.LENGTH_LONG)
                    .show();

            break;

        case R.id.button2:

            KeyguardManager mgr1 = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
            KeyguardLock lock1 = mgr1.newKeyguardLock(KEYGUARD_SERVICE);

            lock1.disableKeyguard();

            break;
        }
    }
}

I have also taken the following permission...

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

you also could do it over device admin

DevicePolicyManager mDPM;
mDPM.lockNow();

If you want to Lock Android Phone Screen Programmaticllay, just check below tutorial.

Lock Android Phone Screen Programmtically

i have written simple application to achieve this.

let me comment if you get any trouble with my solution

Try this:

mKeyGuardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
mLock = mKeyGuardManager.newKeyguardLock("alarmRecieve");
((KeyguardLock) mLock).reenableKeyguard();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM