Android 注册系统组件并锁屏
Android实现锁屏功能只需要先注册成为系统组件,就可以简单实现。
首先,注册一个继承自DeviceAdminReceiver的receiver:
package com.jikexueyuan.lockscreen;
import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by Administrator on 2015/12/13 0013.
*/
public class DeviceManagerBC extends DeviceAdminReceiver {
@Override
public void onEnabled(Context context, Intent intent) {
super.onEnabled(context, intent);
System.out.println("已经注册为系统组件");
Toast.makeText(context,"已经注册为系统组件",Toast.LENGTH_SHORT).show();
}
@Override
public void onDisabled(Context context, Intent intent) {
super.onDisabled(context, intent);
System.out.println("已经注销系统组件");
Toast.makeText(context,"已经注销系统组件",Toast.LENGTH_SHORT).show();
}
}
为了获取权限,我们需要创建一个device-admin的xml文件。在res目录创建一个xml文件夹,再创建一个device-admin.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<force-lock/>
</uses-policies>
</device-admin>
在manifest文件注册receiver时添加device-admin:
<receiver android:name=".DeviceManagerBC">
<meta-data android:name="android.app.device_admin" android:resource="@xml/device_admin"/>
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED"/>
</intent-filter>
</receiver>
在Activity中通过DevicePolicyManager进行注册、锁屏:
package com.jikexueyuan.lockscreen; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private DevicePolicyManager devicePolicyManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE); findViewById(R.id.btnLockScreen).setOnClickListener(this); findViewById(R.id.btnRegDeviceAdmin).setOnClickListener(this); findViewById(R.id.btnUnRegDeviceAdmin).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btnRegDeviceAdmin: //注册成为系统组件 Intent i = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); i.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,new ComponentName(this,DeviceManagerBC.class)); startActivity(i); break; case R.id.btnLockScreen: //锁屏 devicePolicyManager.lockNow(); break; case R.id.btnUnRegDeviceAdmin: //取消系统组件权限 devicePolicyManager.removeActiveAdmin(new ComponentName(this,DeviceManagerBC.class)); break; } } }