在开发文档的Device Administration中有对一键锁屏详细的信息介绍。
采用一个Broadcastreceiver来接收监听相关事件。
步骤1 ;在AndroidManifest.xml中添加相关权限:
<receiver android:name=".DeviceAdminstration" android:label="@string/sample_device_admin" android:description="@string/sample_device_admin_description" android:permission="android.permission.BIND_DEVICE_ADMIN"> <meta-data android:name="android.app.device_admin" android:resource="@xml/device_admin_sample" /> <intent-filter> <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter> </receiver>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android"> <uses-policies> <limit-password /> <watch-login /> <reset-password /> <force-lock /> <wipe-data /> <expire-password /> <encrypted-storage /> <disable-camera /> </uses-policies> </device-admin>
package com.example.text; import android.app.admin.DeviceAdminReceiver; import android.content.Context; import android.content.Intent; //不做任何处理 public class DeviceAdminstration extends DeviceAdminReceiver { }
步骤3:添加相关代码:
package com.example.text; import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { private DevicePolicyManager mDPM; private ComponentName mDeviceAdminSample; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); mDeviceAdminSample = new ComponentName(MainActivity.this, DeviceAdminstration.class); // 组件名称 //mDPM.resetPassword("", 0); } public void LockScreen(View view) { boolean adminActive = mDPM.isAdminActive(mDeviceAdminSample); if(adminActive) mDPM.lockNow(); } public void ActiveAdmin(View view) { Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "测试程序 !"); startActivity(intent); } public void removeAdmin(View view) { mDPM.removeActiveAdmin(mDeviceAdminSample); } }