프로그래밍 방식으로 응용 프로그램 데이터를 지우는 방법 깨끗한 상태 (테스트중인 응용 프로그램)로

Android 응용 프로그램 (Robotium 사용)에 대한 자동 테스트를 개발 중입니다. 테스트의 일관성과 신뢰성을 보장하기 위해 각 테스트를 깨끗한 상태 (테스트중인 응용 프로그램)로 시작하고 싶습니다. 그렇게하려면 앱 데이터를 지워야합니다. 설정 / 응용 프로그램 / 응용 프로그램 관리 / [내 응용 프로그램] / 데이터 지우기에서 수동으로 수행 할 수 있습니다.

프로그래밍 방식으로이 작업을 수행하는 데 권장되는 방법은 무엇입니까?



답변

패키지 관리자 도구를 사용하여 설치된 앱의 데이터를 지울 수 있습니다 (장치의 앱 설정에서 ‘데이터 지우기’버튼을 누르는 것과 유사). 따라서 adb를 사용하면 다음을 수행 할 수 있습니다.

adb shell pm clear my.wonderful.app.package

답변

@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();
    }
}

경고 : 응용 프로그램이 강제로 종료됩니다.


답변

이것으로 SharedPreferences 앱 데이터를 지울 수 있습니다.

Editor editor =
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();

그리고 app db를 지우려면이 대답은 정확합니다-> Clearing Application database


답변

API 버전 19부터 ActivityManager.clearApplicationUserData ()를 호출 할 수 있습니다.

((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).clearApplicationUserData();

답변

이 코드를 확인하여 다음을 수행하십시오.

@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();
}

답변

몇 가지 공유 환경 설정을 지울 경우이 솔루션이 훨씬 좋습니다.

@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());
}

답변

컨텍스트를 사용하여 환경 설정, 데이터베이스 파일과 같은 앱 특정 파일을 지울 수 있습니다. Espresso를 사용한 UI 테스트에 아래 코드를 사용했습니다.

    @Rule
    public ActivityTestRule<HomeActivity> mActivityRule = new ActivityTestRule<>(
            HomeActivity.class);

    public static void clearAppInfo() {
        Activity mActivity = testRule.getActivity();
        SharedPreferences prefs =
                PreferenceManager.getDefaultSharedPreferences(mActivity);
        prefs.edit().clear().commit();
        mActivity.deleteDatabase("app_db_name.db");
    }