0

我希望我的应用程序在单击按钮时锁定手机!以下是我的代码。

public class MainActivity extends Activity implements OnClickListener {

    Button b;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b = (Button) findViewById(R.id.button);

        b.setOnClickListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
        case R.id.button:
        KeyguardManager km = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
            KeyguardLock kl = km.newKeyguardLock(KEYGUARD_SERVICE);
            kl.reenableKeyguard();


            break;
        }

    }

}

这是行不通的。我还尝试在 onClick 事件中使用以下代码。

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
         wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
        wl.release();

这也行不通。谁能帮我 ?

4

2 回答 2

1

您需要设置一个设备管理组件,然后调用lockNow().DevicePolicyManager

此示例项目从编码的角度显示了所需的内容。安装后,用户必须同意让您的应用成为设备管理员。如果应用程序不是设备管理员,则活动会将用户路由到“设置”应用程序中的正确屏幕:

public class LockMeNowActivity extends Activity {
  private DevicePolicyManager mgr=null;
  private ComponentName cn=null;

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

    setContentView(R.layout.main);
    cn=new ComponentName(this, AdminReceiver.class);
    mgr=(DevicePolicyManager)getSystemService(DEVICE_POLICY_SERVICE);
  }

  public void lockMeNow(View v) {
    if (mgr.isAdminActive(cn)) {
      mgr.lockNow();
    }
    else {
      Intent intent=
          new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
      intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, cn);
      intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                      getString(R.string.device_admin_explanation));
      startActivity(intent);
    }
  }
}
于 2013-07-09T14:22:40.767 回答
0

Use this code in your onCreate() method of activity to initialize DevicePolicyManager :

 myDevicePolicyManager = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
                mDeviceAdminSample = new ComponentName(Controller.this,
                        adminActivity.class);

To lock the device write the code in the event where you use to lock set a boolean enable :

if (enable) {
myDevicePolicyManager.lockNow();
}

May be you have to enable the device admin, the DevicePolicyManager intent is called and it should be enabled by the user. Follow this code :

Intent myIntent = new   Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);  
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, securemeAdmin); 
于 2013-07-09T14:26:23.520 回答