问题描述
我想以编程方式清除应用程序的数据.
I want to clear my application's data programmatically.
应用程序的数据可能包含数据库,共享首选项,内部-外部文件或在应用程序内创建的任何其他文件之类的东西.
Application's data may contain anything like databases, shared preferences, Internal-External files or any other files created within the application.
我知道我们可以通过以下方式清除移动设备中的数据:
I know we can clear data in the mobile device through:
但是我需要通过Android程序来完成上述操作吗?
But I need to do the above thing through an Android Program?
推荐答案
API 19(KitKat)中引入了新的API: ActivityManager.clearApplicationUserData().
There's a new API introduced in API 19 (KitKat):ActivityManager.clearApplicationUserData().
我强烈建议在新应用程序中使用它:
I highly recommend using it in new applications:
import android.os.Build.*;
if (VERSION_CODES.KITKAT <= VERSION.SDK_INT) {
((ActivityManager)context.getSystemService(ACTIVITY_SERVICE))
.clearApplicationUserData(); // note: it has a return value!
} else {
// use old hacky way, which can be removed
// once minSdkVersion goes above 19 in a few years.
}
如果您不想采用骇人听闻的方式,还可以隐藏UI上的按钮,以便该功能仅在旧手机上不可用.
If you don't want the hacky way you can also hide the button on the UI, so that functionality is just not available on old phones.
对于使用 android:manageSpaceActivity
.
每当我使用它时,我都会从具有android:process=":manager"
的manageSpaceActivity
中进行操作.在这里,我手动终止了我应用程序的所有 other 进程.这样,我就可以让UI保持运行状态,并让用户决定下一步要去哪里.
Whenever I use this, I do so from a manageSpaceActivity
which has android:process=":manager"
. There, I manually kill any other processes of my app. This allows me to let a UI stay running and let the user decide where to go next.
private static void killProcessesAround(Activity activity) throws NameNotFoundException {
ActivityManager am = (ActivityManager)activity.getSystemService(Context.ACTIVITY_SERVICE);
String myProcessPrefix = activity.getApplicationInfo().processName;
String myProcessName = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0).processName;
for (ActivityManager.RunningAppProcessInfo proc : am.getRunningAppProcesses()) {
if (proc.processName.startsWith(myProcessPrefix) && !proc.processName.equals(myProcessName)) {
android.os.Process.killProcess(proc.pid);
}
}
}
这篇关于以编程方式清除应用程序的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!