android: require password when uninstall app

前端 未结 1 1071
半阙折子戏
半阙折子戏 2021-01-26 10:33

I want to build app like parental control, so when child try to uninstall/remove my app I would like to require that a user type a password before being allowed to uninstall/rem

相关标签:
1条回答
  • 2021-01-26 11:13

    You can lock the device if you use device administration. Users can't uninstall active device admins, then you can lock the device if they try to disable device admin, then the parent could type in the password to unlock it.

    In your manifest:

      <receiver android:name=".AdminReceiver"
            android:label="Administration"
            android:description="@string/descript"
            android:permission="android.permission.BIND_DEVICE_ADMIN">
                <meta-data android:name="android.app.device_admin"
                           android:resource="@xml/deviceadmin" />
                <intent-filter>
                    <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
                </intent-filter>
            </receiver>
    

    Then in @xml/deviceadmin

    <device-admin xmlns:android="http://schemas.android.com/apk/res/android">
      <uses-policies>
        <reset-password />
        <force-lock />
      </uses-policies>
    </device-admin>
    

    Then

    public class AdminReceiver extends DeviceAdminReceiver {
    @Override
            public CharSequence onDisableRequested(final Context context, Intent intent) {
    
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(startMain); //switch to the home screen, not totally necessary
                lockPhone(context, secPassword);
                //Log.i(TAG, "DEVICE ADMINISTRATION DISABLE REQUESTED & LOCKED PHONE");
    
                return "haha. i locked your phone.";
            }
        public static boolean lockPhone(Context context, String password){
            devAdminReceiver = new ComponentName(context, AdminReceiver.class);
            dpm = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
            boolean pwChange = dpm.resetPassword(password, 0);
            dpm.lockNow();
            return pwChange;
        }   
    }
    

    To enable your app as a device administrator:

    devAdminReceiver = new ComponentName(context, AdminReceiver.class);
            dpm = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
            pref = PreferenceManager.getDefaultSharedPreferences(context);
            dpm.isAdminActive(devAdminReceiver);
    
    0 讨论(0)
提交回复
热议问题