android: require password when uninstall app

ⅰ亾dé卋堺 提交于 2019-12-02 08:14:49

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!