我尝试使用RecoverySystem类在Android中执行恢复出厂设置的操作,但出现权限错误,由于它们是系统权限,因此无法覆盖。我想知道是否还有另一种方法可以恢复出厂设置?
最佳答案
第三方应用程序绝对可以做到这一点。
在2.2+设备(包括最新的4.x)上,您必须使用DevicePolicyManager并在AndroidManifest.xml中包含权限。对于较旧的设备,您可以使用其他答案中所述的外部上下文加载器。
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
DevicePolicyManager mDPM;
ComponentName mDeviceAdmin;
在“创建”上确定存在Android版本并获取对象的句柄
currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.FROYO) {
//2.2+
mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
mDeviceAdmin = new ComponentName(this, WipeDataReceiver.class);
}
WipeDataReceiver类是用于实现DeviceAdminReceiver的类,但没有任何替代或代码更新。
public static class WipeDataReceiver extends DeviceAdminReceiver {
}
恢复时,首先必须确认恢复出厂设置。当Activity返回结果时,它将执行wipeData。如果是Froyo或更少,则可以跳过库存恢复出厂设置的 Activity 。
if (currentAPIVersion >= android.os.Build.VERSION_CODES.FROYO) {
// 2.2+
if (!mDPM.isAdminActive(mDeviceAdmin)) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdmin);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Process will remove user installed applications, settings, wallpaper and sound settings. Are you sure you want to wipe device?");
startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN);
} else {
// device administrator, can do security operations
mDPM.wipeData(0);
}
} else {
// 2.1
try {
Context foreignContext = this.createPackageContext("com.android.settings", Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
Class<?> yourClass = foreignContext.getClassLoader().loadClass("com.android.settings.MasterClear");
Intent i = new Intent(foreignContext, yourClass);
this.startActivityForResult(i, REQUEST_CODE_ENABLE_ADMIN);
} catch (ClassNotFoundException e) {
}
}