无聊弄了个一键锁屏,图片没有处理,生成的apk有点大。签过名的apk
- public class MainActivity extends Activity {
- private DevicePolicyManager policyManager;
- private ComponentName componentName;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //获取设备管理服务
- policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
- //AdminReceiver 继承自 DeviceAdminReceiver
- componentName = new ComponentName(this, myDeviceAdminReceiver.class);
- mylock();
- // killMyself ,锁屏之后就立即kill掉我们的Activity,避免资源的浪费;
- Intent intent = new Intent(Intent.ACTION_MAIN);
- intent.addCategory(Intent.CATEGORY_HOME);
- intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- startActivity(intent);
- android.os.Process.killProcess(android.os.Process.myPid());
- /* ActivityManager activityMgr= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE );
- activityMgr.restartPackage(getPackageName());
- */
- }
- private void mylock(){
- boolean active = policyManager.isAdminActive(componentName);
- if(!active){//若无权限
- activeManage();//去获得权限
- policyManager.lockNow();//并锁屏
- }
- if (active) {
- policyManager.lockNow();//直接锁屏
- }
- }
- 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);
- }
- @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;
- }
- }