【问题标题】:Clearing app data and cache when releasing new update发布新更新时清除应用数据和缓存
【发布时间】:2018-09-10 20:24:49
【问题描述】:

我正在发布一个新的更新,这将完全改变我的应用程序构建从上一个版本。我希望应用程序是新鲜的,并为当前用户删除所有旧的 unceccery 缓存和数据。 我怎样才能做到这一点?使用什么正确的代码,以及在哪里添加它,我不是 android 开发专家,所以请更具体地指导我。我检查了this question,但没有提及实际用于清除数据和缓存的代码。

我的设置(以防万一):

// Android Studio 3.0        
compileSdkVersion 26
buildToolsVersion '27.0.3' (Gradle)
minSdkVersion 16
targetSdkVersion 26

【问题讨论】:

    标签: android


    【解决方案1】:

    当您的应用程序更新时,您可以在广播接收器类中收听事件并在广播接收器的 onReceive 中进行清理。

    您分享的链接中的以下评论 :) 包含所有详细信息。

    https://stackoverflow.com/a/48520332/8312634

    【讨论】:

    • 即使我在之前的版本中没有声明接收者,它也能工作吗?什么是清除数据和缓存的正确方法?这是我最关心的问题。
    • 我相信你会在应用程序更新之后得到这个事件,而不是之前。因此,您可以在该事件上执行清除代码。另外,数据和缓存是什么意思?如果它是一个文件,你需要删除它们,或者如果它像 sharedprefs 一样,你可以像这样清除它们developer.android.com/reference/android/content/…
    • 旧版本使用Webview缓存,数据与Webview相关。
    • 试试这个清除WebView的缓存:developer.android.com/reference/android/webkit/…
    【解决方案2】:

    将它添加到我的 MainActivity 对我来说可以清除缓存和数据。

       @Override
       protected void onDestroy() {
          super.onDestroy();
          try {
             trimCache(this);
          } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
          }
       }
    
       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;
                }
             }
          }
    
          // The directory is now empty so delete it
          return dir.delete();
       }
    
    }
    

    在这里找到答案:Clear Application cache on exit in android

    现在每次都清除缓存,用户关闭应用程序,它适用于 我,因为我不想保留 webview 的缓存,对于其他人 只想在更新时清除它,使用 onReceive 实现它 应该可以。

    【讨论】:

      猜你喜欢
      • 2018-07-09
      • 2015-05-29
      • 2019-09-01
      • 2012-08-02
      • 2021-05-02
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 2012-09-21
      相关资源
      最近更新 更多