title: Get Cached data storage programmatically
body: <p>I want to get cached data size at "Internal storage" in "settings", like this:</p>
  
  <p><img src="https://i.stack.imgur.com/BqLO3.jpg" alt="Cache Data size"></p>
  
  <p>I tried to get all application cache by invoking <strong>getPackageSizeInfo</strong> using Java Reflection. Yes it did got all cached size of apps, but the size is smaller than the cached data size in "settings" above. This is the picture when I used this method:</p>
  
  <p><img src="https://i.stack.imgur.com/A3atZ.jpg" alt="get cached data"></p>
  
  <p>in settings, the cached data size 840 MB, but when in my app is 493 MB.</p>
  
  <p>These are my codes</p>
  
  <p><strong>Main Activity</strong></p>
  
  <pre><code>public class MainActivity extends AppCompatActivity implements View.OnClickListener {
      public static final int FETCH_PACKAGE_SIZE_COMPLETED = 100;
      public static final int ALL_PACKAGE_SIZE_COMPLETED = 200;
      IDataStatus onIDataStatus;
      TextView lbl_cache_size;
      ProgressDialog pd;
      long packageSize = 0, size = 0, dataSize = 0, data = 0;
      AppDetails cAppDetails;
      public ArrayList&lt;AppDetails.PackageInfoStruct&gt; res;
      int totalSize;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          findViewById(R.id.btn_get_cacheSize).setOnClickListener(this);
          findViewById(R.id.btn_delete_cache).setOnClickListener(this);
          lbl_cache_size = (TextView) findViewById(R.id.lbl_cache_size);
  
  
      }
  
      private void showProgress(String message) {
          pd = new ProgressDialog(this);
          pd.setIcon(R.mipmap.ic_launcher);
          pd.setTitle("Please wait...");
          pd.setMessage(message);
          pd.setCancelable(false);
          pd.show();
      }
  
      private void getPackageSize() {
          cAppDetails = new AppDetails(this);
          res = cAppDetails.getPackages();
          if (res == null)
              return;
          for (int m = 0; m &lt; res.size(); m++) {
              PackageManager pm = getPackageManager();
              Method getPackageSizeInfo;
              try {
                  getPackageSizeInfo = pm.getClass().getMethod(
                          "getPackageSizeInfo", String.class,
                          IPackageStatsObserver.class);
                  getPackageSizeInfo.invoke(pm, res.get(m).pname,
                          new cachePackState());
              } catch (SecurityException e) {
                  e.printStackTrace();
              } catch (NoSuchMethodException e) {
                  e.printStackTrace();
              } catch (IllegalArgumentException e) {
                  e.printStackTrace();
              } catch (IllegalAccessException e) {
                  e.printStackTrace();
              } catch (InvocationTargetException e) {
                  e.printStackTrace();
              }
  
          }
          handle.sendEmptyMessage(ALL_PACKAGE_SIZE_COMPLETED);
          Log.v("Total Cache Size", " " + packageSize);
  
      }
  
      @Override
      public void onClick(View v) {
          switch (v.getId()) {
              case R.id.btn_get_cacheSize:
                  size = 0;
                  packageSize = 0;
                  dataSize = 0;
                  data = 0;
                  showProgress("Calculating Cache Size..!!!");
                  /*
                  * You can also use sync task
                   */
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          getPackageSize();
                      }
                  }).start();
  
                  //getPackageSize();
  
                  break;
              case R.id.btn_delete_cache:
                  deleteCache();
                  break;
              default:
                  break;
  
          }
      }
  
      private Handler handle = new Handler() {
          @Override
          public void handleMessage(Message msg) {
              switch (msg.what) {
                  case FETCH_PACKAGE_SIZE_COMPLETED:
                      String sizeInHuman = "";
                      if (packageSize &gt; 0) {
                         // size = (packageSize / 1024000);
                          //data = (dataSize / 1024000); //boy
                          sizeInHuman = humanReadableByteCount(packageSize, true);
                      }
                      //lbl_cache_size.setText("Cache Size : " + size + " MB and Data Size : "+ data + " MB");
                      lbl_cache_size.setText("Cache Size : " + sizeInHuman);
                      break;
                  case ALL_PACKAGE_SIZE_COMPLETED:
                      if (null != pd)
                          if (pd.isShowing())
                              pd.dismiss();
                      break;
                  default:
                      break;
              }
          }
      };
  
      private class cachePackState extends IPackageStatsObserver.Stub {
  
          @Override
          public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
              Log.d("Package Size", pStats.packageName + "");
              Log.i("Cache Size", pStats.cacheSize + "");
              Log.w("Data Size", pStats.dataSize + "");
              packageSize = packageSize + pStats.cacheSize;
              Log.v("Total Cache Size", " " + packageSize );
              handle.sendEmptyMessage(FETCH_PACKAGE_SIZE_COMPLETED);
  
          }
      }
  
      private void deleteCache() {
          PackageManager pm = getPackageManager();
          //Get all methods on the packageManager
          Method[] methods = pm.getClass().getDeclaredMethods();
          for (Method m : methods) {
              if (m.getName().equals("freeStorage")) {
                  //Found the method I want to use
                  try {
                      m.invoke(pm, Long.MAX_VALUE, null);
                  } catch (IllegalAccessException e) {
                      e.printStackTrace();
                  } catch (InvocationTargetException e) {
                      e.printStackTrace();
                  }
                  break;
              }
          }
      }
  
      public static String humanReadableByteCount(long bytes, boolean si) {
          int unit = si ? 1000 : 1024;
          if (bytes &lt; unit) return bytes + " B";
          int exp = (int) (Math.log(bytes) / Math.log(unit));
          String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
          return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
      }
  }
  </code></pre>
  
  <p><strong>AppDetails</strong></p>
  
  <pre><code>public class AppDetails {
  
      Activity mActivity;
      public ArrayList&lt;PackageInfoStruct&gt; res = new ArrayList&lt;PackageInfoStruct&gt;();
      public ListView list;
      public String app_labels[];
  
      public AppDetails(Activity mActivity) {
          this.mActivity = mActivity;
  
      }
  
      public ArrayList&lt;PackageInfoStruct&gt; getPackages() {
          ArrayList&lt;PackageInfoStruct&gt; apps = getInstalledApps(true); /*
                                                                       * false =
                                                                       * no system
                                                                       * packages
                                                                       */
          final int max = apps.size();
          for (int i = 0; i &lt; max; i++) {
              apps.get(i);
          }
          return apps;
      }
  
      private ArrayList&lt;PackageInfoStruct&gt; getInstalledApps(boolean getSysPackages) {
  
          List&lt;PackageInfo&gt; packs = mActivity.getPackageManager()
                  .getInstalledPackages(0);
          try {
              app_labels = new String[packs.size()];
          } catch (Exception e) {
              Toast.makeText(mActivity.getApplicationContext(), e.getMessage(),
                      Toast.LENGTH_SHORT).show();
          }
          for (int i = 0; i &lt; packs.size(); i++) {
              PackageInfo p = packs.get(i);
              //if ((!getSysPackages) &amp;&amp; (p.versionName == null)) {
               //   continue;
              //}
              PackageInfoStruct newInfo = new PackageInfoStruct();
              newInfo.appname = p.applicationInfo.loadLabel(
                      mActivity.getPackageManager()).toString();
              newInfo.pname = p.packageName;
              newInfo.datadir = p.applicationInfo.dataDir;
              newInfo.versionName = p.versionName;
              newInfo.versionCode = p.versionCode;
              newInfo.icon = p.applicationInfo.loadIcon(mActivity
                      .getPackageManager());
              res.add(newInfo);
  
              app_labels[i] = newInfo.appname;
          }
          return res;
      }
  
      class PackageInfoStruct {
          String appname = "";
          String pname = "";
          String versionName = "";
          int versionCode = 0;
          Drawable icon;
          String datadir = "";
      }
  }
  </code></pre>
  
  <p>Is there any way to get cached data size in storage?</p>
  
  <p>The reference: 
  <a href="https://stackoverflow.com/questions/28407799/how-to-programmatically-calculate-all-cache-size-of-installed-application/28408453#28408453">reference</a></p>