第三方应用程序绝对可以做到这一点。
在 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 或更少,您可以跳过库存恢复出厂设置活动。
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) {
}
}