如何以编程方式清除应用程序数据

use*_*603 148 android

我正在开发一个Android应用程序的自动化测试(使用Robotium).为了确保测试的一致性和可靠性,我想以干净状态(被测试的应用程序)开始每个测试.为此,我需要清除应用数据.这可以在设置/应用程序/管理应用程序/ [我的应用程序] /清除数据中手动完成

以编程方式完成此操作的推荐方法是什么?

edo*_*ino 170

您可以使用包管理器工具清除已安装应用程序的数据(类似于按设备上应用程序设置中的"清除数据"按钮).所以使用adb你可以做到:

adb shell pm clear my.wonderful.app.package
Run Code Online (Sandbox Code Playgroud)


Seb*_*ano 34

在@ edovino的回答之后,以编程方式清除所有应用程序首选项的方式将是

private void clearPreferences() {
    try {
        // clearing app data
        Runtime runtime = Runtime.getRuntime();
        runtime.exec("pm clear YOUR_APP_PACKAGE_GOES HERE");

    } catch (Exception e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

警告:应用程序将强制关闭.

  • 如果在此之后运行任何测试代码,则会失败. (5认同)
  • 如果我不想强制关闭应用程序呢? (2认同)

gul*_*yuz 21

您可以使用此清除SharedPreferences应用程序数据

Editor editor = 
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
Run Code Online (Sandbox Code Playgroud)

并且为了清除app db,这个答案是正确的 - > 清除应用程序数据库


小智 14

从API版本19开始,可以调用ActivityManager.clearApplicationUserData().

((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).clearApplicationUserData();
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,称这将终止您的应用程序. (12认同)

Har*_*hna 8

检查此代码:

@Override
protected void onDestroy() {
// closing Entire Application
    android.os.Process.killProcess(android.os.Process.myPid());
    Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
    editor.clear();
    editor.commit();
    trimCache(this);
    super.onDestroy();
}


public static void trimCache(Context context) {
    try {
        File dir = context.getCacheDir();
        if (dir != null && dir.isDirectory()) {
            deleteDir(dir);

        }
    } catch (Exception e) {
        // TODO: handle exception
    }
}


public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    // <uses-permission
    // android:name="android.permission.CLEAR_APP_CACHE"></uses-permission>
    // The directory is now empty so delete it

    return dir.delete();
}
Run Code Online (Sandbox Code Playgroud)


Tho*_*ler 6

如果你只有几个共享偏好要清除,那么这个解决方案要好得多.

@Override
protected void setUp() throws Exception {
    super.setUp();
    Instrumentation instrumentation = getInstrumentation();
    SharedPreferences preferences = instrumentation.getTargetContext().getSharedPreferences(...), Context.MODE_PRIVATE);
    preferences.edit().clear().commit();
    solo = new Solo(instrumentation, getActivity());
}
Run Code Online (Sandbox Code Playgroud)