以编程方式在Android中锁定手机?

时间:2012-07-02 10:02:55

标签: java android

我试图锁定设备并试图通过使用以下代码启用它但它不起作用。我还采取了以下两个允许并且没有显示该手机被锁定...我也尝试解锁再一次。

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;
        }
    }
}

我还获得了以下许可......

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

3 个答案:

答案 0 :(得分:3)

你也可以通过设备管理员来做这件事

DevicePolicyManager mDPM;
mDPM.lockNow();

答案 1 :(得分:3)

如果你想锁定Android手机屏幕Programmaticllay, 请查看以下教程。

Lock Android Phone Screen Programmtically

我已经编写了简单的应用程序来实现这一目标。

如果您对我的解决方案有任何问题,请让我发表评论

答案 2 :(得分:1)

试试这个:

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