2016-10-12 46 views
3

我想在Android Marshmallow 6.0中以編程方式清除我的應用程序緩存。我想下面的代碼,但它不是在Marshmallow.I工作閱讀棧溢出,下面的代碼是從API級別19.棄用我在Manifests.xml添加CLEAR_APP_CACHE許可如何以編程方式在棉花糖中清除應用程序緩存

public void trimCache(Context context) { 
     try { 
      File dir = context.getCacheDir(); 
      if (dir != null && dir.isDirectory()) { 
       deleteDir(dir); 
      } 
     } catch (Exception e) { 
      // TODO: handle exception 
     } 
    } 

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

     // The directory is now empty so delete it 
     return dir.delete(); 
    } 
+0

它是如何不加工?你的應用程序崩潰了嗎?請詳細說明,以便人們可以更好地幫助你。 –

+0

@HadiSatrio感謝您的回覆。我在Android Studio的「監視器」選項卡中看到過。它不釋放內存。而且它也會導致我的應用程序出現內存不足的錯誤。我沒有存儲卡,而且我的手機中只有500MB可用內存。 –

+0

我面臨同樣的問題。如果有人解決了請幫助。謝謝 –

回答

0
add permission: 
<uses-permission android:name="android.permission.CLEAR_APP_CACHE" /> 

you should check for external cache dir also. 

public void trimCache(Context context) { 
     try { 
      File dir = context.getCacheDir(); 
      if (dir != null && dir.isDirectory()) { 
       deleteDir(dir); 
      } 
      File exDir = context.getExternalCacheDir(); 
      if (exDir != null && exDir.isDirectory()) { 
       deleteDir(exDir); 
      } 
     } catch (Exception e) { 
      // TODO: handle exception 
     } 
    } 
+0

我忘了添加我的問題,但我已經添加了權限。 –

+0

但您還沒有清除getExternalCacheDir() –

相關問題