一、項目簡介:
項目:《Android 一鍵鎖屏》
開發周期:4天
代碼量:100行
二、項目流程:
三、項目代碼
1、主程序代碼:
- private DevicePolicyManager policyManager;
- private ComponentName componentName;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.locklayout);
-
- //獲取設備管理服務
- policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
-
- //AdminReceiver 繼承自 DeviceAdminReceiver
- componentName = new ComponentName(this, AdminReceiver.class);
-
- mylock();
- // killMyself ,鎖屏之後就立即kill掉我們的Activity,避免資源的浪費;
- android.os.Process.killProcess(android.os.Process.myPid());
-
- }
2、其中,mylock()為:
- private void mylock(){
-
- boolean active = policyManager.isAdminActive(componentName);
- if(!active){//若無權限
- activeManage();//去獲得權限
- policyManager.lockNow();//並鎖屏
- }
- if (active) {
- policyManager.lockNow();//直接鎖屏
- }
- }
3、activeManage()代碼為:
- private void activeManage() {
- // 啟動設備管理(隱式Intent) - 在AndroidManifest.xml中設定相應過濾器
- Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
-
- //權限列表
- intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
-
- //描述(additional explanation)
- intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "------ 其他描述 ------");
-
- startActivityForResult(intent, 0);
- }
4、AndroidManifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="cn.hnu"
- android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".LockFirst"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <!-- 設備管理 -->
- <receiver android:name=".AdminReceiver"
- android:label="@string/app_name"
- android:description="@string/app_name"
- android:permission="android.permission.BIND_DEVICE_ADMIN">
- <meta-data android:name="android.app.device_admin"
- android:resource="@xml/lock_screen" />
- <intent-filter>
- <action
- android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
- </intent-filter>
- </receiver>
- </application>
-
-
- </manifest>
5、其中lock_screen.xml(lock_screen.xml文件放在res/xml文件夾下)代碼為:
- <?xml version="1.0" encoding="UTF-8"?>
- <device-admin
- xmlns:android="http://schemas.android.com/apk/res/android">
- <uses-policies>
- <!-- 強行鎖定 在裡僅這個是需要的-->
- <force-lock />
- <!-- 清除所有數據(恢復出廠設置) -->
- <wipe-data />
- <!-- 重置密碼 -->
- <reset-password />
- <!-- 限制密碼選擇 -->
- <limit-password />
- <!-- 監控登錄嘗試 -->
- <watch-login />
- </uses-policies>
- </device-admin>