Android一键锁屏(附源码)

无聊弄了个一键锁屏,图片没有处理,生成的apk有点大。签过名的apk

部分代码:

  1. public class MainActivity extends Activity {  
  2.     private DevicePolicyManager policyManager;  
  3.     private ComponentName componentName;  
  4.       
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.             super.onCreate(savedInstanceState);  
  8.             setContentView(R.layout.activity_main);  
  9.               
  10.             //获取设备管理服务  
  11.             policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);  
  12.               
  13.             //AdminReceiver 继承自 DeviceAdminReceiver  
  14.             componentName = new ComponentName(this, myDeviceAdminReceiver.class);  
  15.               
  16.             mylock();  
  17.         //  killMyself ,锁屏之后就立即kill掉我们的Activity,避免资源的浪费;     
  18.               
  19.             Intent intent = new Intent(Intent.ACTION_MAIN);  
  20.             intent.addCategory(Intent.CATEGORY_HOME);  
  21.             intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  22.             startActivity(intent);  
  23.             android.os.Process.killProcess(android.os.Process.myPid());  
  24.                   
  25.               
  26.           /*  ActivityManager activityMgr= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE ); 
  27.              
  28.             activityMgr.restartPackage(getPackageName()); 
  29.             */  
  30.     }  
  31.     private void mylock(){  
  32.           
  33.         boolean active = policyManager.isAdminActive(componentName);  
  34.         if(!active){//若无权限  
  35.             activeManage();//去获得权限  
  36.             policyManager.lockNow();//并锁屏  
  37.         }  
  38.         if (active) {  
  39.                 policyManager.lockNow();//直接锁屏  
  40.         }  
  41.     }  
  42.     private void activeManage() {  
  43.         // 启动设备管理(隐式Intent) – 在AndroidManifest.xml中设定相应过滤器  
  44.         Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);  
  45.           
  46.         //权限列表  
  47.         intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);  
  48.   
  49.         //描述(additional explanation)  
  50.                 intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, “一键锁屏”);  
  51.   
  52.                 startActivityForResult(intent, 0);  
  53. }  
  54.     @Override  
  55.     public boolean onCreateOptionsMenu(Menu menu) {  
  56.         // Inflate the menu; this adds items to the action bar if it is present.  
  57.         getMenuInflater().inflate(R.menu.main, menu);  
  58.         return true;  
  59.     }  
  60.   
  61. }  

工程下载

未经允许不得转载:ganlei的个人博客 » Android一键锁屏(附源码)

赞 (0)
分享到:更多 ()