前言
本文主要介绍了关于android实现一键锁屏和一键卸载的相关内容,分享出来供大家参考学习,这两个功能也是大家在开发中会遇到的两个需求,下面话不多说了,来一起看看详细的介绍吧。
一.设备管理器操作步骤
1.创建类DeviceAdminReceiver的子类
如:com.itheima62.lockscreen.DeviceAdminSample
2.在清单文件中配置广播接收者
3.配置字符串相关信息
设备管理员 管理员 开启设备管理员,不开启扣2000块
4.在res目录下创建xml文件夹,在该文件夹下创建device_admin_sample.xml文件,内容:
5.在代码中创建设备管理器和组件
dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE); ComponentName who = new ComponentName(this, DeviceAdminSample.class);
6.写功能
dpm.lockNow();一键锁屏
二.源代码
创建类DeviceAdminReceiver的子类
package com.example.suoping; import android.app.admin.DeviceAdminReceiver; public class DeviceAdminSample extends DeviceAdminReceiver { }
MainActivity
package com.example.suoping; import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; public class MainActivity extends Activity { private DevicePolicyManager dpm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE); lockScreen(null); } /** * @param v * 一键锁屏 */ public void lockScreen(View v) { //如果没有激活设备管理员,提醒给用户做事 ComponentName who = new ComponentName(this, DeviceAdminSample.class); if (dpm.isAdminActive(who)) { dpm.lockNow();//一键锁屏 finish(); } else { Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, who); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "设备管理器,,,,,,,,,,,,,,,,"); startActivityForResult(intent, 1); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
RemoveActivity
package com.example.suoping; import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; public class RemoveActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); remove(null); } /** * 一键卸载 * @param v */ public void remove(View v) { // 取消激活设备管理 DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE); ComponentName who = new ComponentName(this, DeviceAdminSample.class); dpm.removeActiveAdmin(who);//取消激活管理设备 //卸载 Intent remove = new Intent("android.intent.action.DELETE"); remove.addCategory("android.intent.category.DEFAULT"); remove.setData(Uri.parse("package:" + getPackageName())); startActivity(remove);//卸载用户apk的界面 } }
布局文件
MainActivity.xml
RemoveActivity.xml
AndroidManifest.xml
device_admin_sample.xml
strings.xml
一键锁屏 Settings Hello world! 设备管理员 管理员 开启设备管理员,不开启扣2000块