簡體   English   中英

以編程方式清除應用程序數據無效

[英]Clear app data programatically doesnt work

我有一個“注銷”按鈕,單擊它們后,我想清除所有數據和應用程序緩存。 我在此站點的類似主題中找到了刪除數據的方法:

   public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if(appDir.exists()){
        String[] children = appDir.list();
        for(String s : children){
            if(!s.equals("lib")){
                deleteDir(new File(appDir, s));
            }
        }
    }
}

public 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;
            }
        }
    }

    return dir.delete();
}

但是當我使用代碼時:

logoutButton.setOnClickListener(new View.OnClickListener() {
          @Override
           public void onClick(View v) {
           clearApplicationData();
           finish();
           startActivity(new Intent(ProfileActivity.this, MainActivity.class));
       }
      });

我的應用程序重新啟動,但是應用程序數據沒有刪除。 那么,如何以編程方式刪除應用程序的所有緩存和數據?

首先,您的代碼不一定刪除存儲SharedPreferences的文件。 它的位置是未記錄的IIRC,並且不一定位於您要刪除的范圍內。

其次, SharedPreferences緩存在您的進程中。 即使您確實成功刪除了文件,緩存的SharedPreferences也不會知道您已刪除它。 在過程終止之前,您將繼續有權訪問“已刪除” SharedPreferences數據。

如果您的目標是能夠刪除數據,則僅將數據存儲在您控制的位置以及控制如何緩存數據的位置。 將您對SharedPreferences的使用替換為其他內容(例如,SQLite數據庫或您自己管理的某些文件)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM