Android 一键屏锁的实现

1.activity里的代码 获取设备管理器

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        registerReceiver();
        devicePolicyManager =(DevicePolicyManager)getSystemService(DEVICE_POLICY_SERVICE);
        //若未注册设备管理器,跳转到配置界面
        //若已注册设备管理器,显示取消设备管理器页面
        if(devicePolicyManager.isAdminActive(new ComponentName(this, DeviceMangerBroadCast.class))){
            devicePolicyManager.lockNow();
            finish();
        }else{
            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, new ComponentName(this, DeviceMangerBroadCast.class));
            startActivityForResult(intent, 1);
        }
    }

2.动态注册设备管理器的授权广播

 public void registerReceiver(){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.app.action.DEVICE_ADMIN_ENABLED");
        intentFilter.addAction("android.app.action.DEVICE_ADMIN_DISABLED");
        registerReceiver(deviceMangerBroadCast,intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(deviceMangerBroadCast);
    }

3.广播接收器

public class DeviceMangerBroadCast extends DeviceAdminReceiver {
    @Override
    public void onEnabled(Context context, Intent intent) {
        super.onEnabled(context, intent);
        Toast.makeText(context, "已获取设备管理者权限", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        super.onDisabled(context, intent);
        Toast.makeText(context, "已取消设备管理者权限", Toast.LENGTH_SHORT).show();
    }
}

4.menifest文件

     很关键

            

            
                
                
            

        

        
            
                
                
            
        

5.device_admin 文件

   
  
      
          
          
          
          
           
          
          
           
           
            
      
  

android一键锁屏代码-CSDN博客

你可能感兴趣的:(android)