Key lock screen of one Android Program
(1) The layout file activity_main.xml is as follows:
(2) MainActivity. java
Package com. xuliugen. lockscreen; import com. itheima. lockscreen. r; 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; import android. widget. toast; public class MainActivity extends Activity {/*** Device Policy Service */private DevicePolicyManager dpm; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); dpm = (DevicePolicyManager) getSystemService (DEVICE_POLICY_SERVICE);}/*** use code to enable administrator */public void openAdmin (View view) {// create an Intent intent = new Intent (DevicePolicyManager. ACTION_ADD_DEVICE_ADMIN); // The ComponentName mDeviceAdminSample = new ComponentName (this, MyAdmin. class); intent. putExtra (DevicePolicyManager. EXTRA_DEVICE_ADMIN, mDeviceAdminSample); // persuade the user to enable the administrator privileges intent. putExtra (DevicePolicyManager. EXTRA_ADD_EXPLANATION, "If you enable this function, you can lock the screen with one click, and your button will not always fail."); startActivity (intent );} /*** one-click lock screen */public void lockscreen (View view) {ComponentName who = new ComponentName (this, MyAdmin. class); if (dpm. isAdminActive (who) {dpm. lockNow (); // lock screen dpm. resetPassword ("", 0); // set the blocked password // clear the data on the Sdcard // dpm. wipeData (DevicePolicyManager. WIPE_EXTERNAL_STORAGE); // restore factory settings // dpm. wipeData (0);} else {Toast. makeText (this, "you have not enabled the Administrator permission", 1 ). show (); return ;}}/*** uninstall the current software */public void uninstall (View view) {// 1. first clear the Administrator permission ComponentName mDeviceAdminSample = new ComponentName (this, MyAdmin. class); dpm. removeActiveAdmin (mDeviceAdminSample); // 2. intent intent = new Intent (); intent. setAction ("android. intent. action. VIEW "); intent. addCategory ("android. intent. category. DEFAULT "); intent. setData (Uri. parse ("package:" + getPackageName (); startActivity (intent );}}
(3) According to the API documentation, a class is required to inherit DeviceAdminReceiver:
Package com. xuliugen. lockscreen; import android. app. admin. DeviceAdminReceiver;/*** special broadcast receiver ** @ author xuliugen **/public class MyAdmin extends DeviceAdminReceiver {}
(5) settings of the broadcast receiver (list file ):
Running effect: