Cache Size and Cache Cleaning Interface Method of Android 8.0

  • 2021-10-11 19:33:15
  • OfStack

Get cache size interface

Mainly, the method here is no longer compatible with 7.0.


import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Process;
import android.os.storage.StorageManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import android.app.usage.StorageStats;
import android.app.usage.StorageStatsManager;

  public static long getCacheSizeByAndroidO(Context mContext, String mPackageName) {
    StorageManager storageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
    StorageStatsManager storageStatsManager = (StorageStatsManager) mContext.getSystemService(Context.STORAGE_STATS_SERVICE);

    try {
      StorageStats storageStats = storageStatsManager.queryStatsForPackage(StorageManager.UUID_DEFAULT, mPackageName, Process.myUserHandle());
      return storageStats.getCacheBytes();
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return 0L;
  }

Clear the cache interface

The interface here and 7.0 keep 1 to


        PackageManager mPm = mContext.getPackageManager();
        // need android.permission.DELETE_CACHE_FILES
        mPm.deleteApplicationCacheFiles(cacheItem.packageName, new IPackageDataObserver.Stub() {

          @Override
          public void onRemoveCompleted(final String packageName, final boolean succeeded) throws RemoteException {
              ///
            }
          }
        });

Andorid 8.0 Setting Module Source Reference

Cache size of source code


import com.android.internal.util.Preconditions;
import com.android.settings.utils.AsyncLoader;
import com.android.settingslib.applications.StorageStatsSource;
import com.android.settingslib.applications.StorageStatsSource.AppStorageStats;

import java.io.IOException;

/**
 * Fetches the storage stats using the StorageStatsManager for a given package and user tuple.
 */
public class FetchPackageStorageAsyncLoader extends AsyncLoader<AppStorageStats> {
  private static final String TAG = "FetchPackageStorage";
  private final StorageStatsSource mSource;
  private final ApplicationInfo mInfo;
  private final UserHandle mUser;

  @Override
  public AppStorageStats loadInBackground() {
    AppStorageStats result = null;
    try {
      result = mSource.getStatsForPackage(mInfo.volumeUuid, mInfo.packageName, mUser);
    } catch (NameNotFoundException | IOException e) {
      Log.w(TAG, "Package may have been removed during query, failing gracefully", e);
    }
    return result;
  }

========================================================================================
package com.android.settings.applications;

public class AppStorageSettings extends AppInfoWithHeader

  @Override
  public void onLoadFinished(Loader<AppStorageStats> loader, AppStorageStats result) {
    mSizeController.setResult(result);
    updateUiWithSize(result);
  }

    private void updateUiWithSize(AppStorageStats result) {
      } else {
      long codeSize = result.getCodeBytes();
      long cacheSize = result.getCacheBytes();
      long dataSize = result.getDataBytes() - cacheSize;

Cleaning cache interface of source code

mPm.deleteApplicationCacheFiles


package com.android.settings.applications;

public class AppStorageSettings extends AppInfoWithHeader
    implements OnClickListener, Callbacks, DialogInterface.OnClickListener,
    LoaderManager.LoaderCallbacks<AppStorageStats> {
  private static final String TAG = AppStorageSettings.class.getSimpleName();

  private ClearCacheObserver mClearCacheObserver;

  @Override
  public void onClick(View v) {
    //  Clean cache button 
    if (v == mClearCacheButton) {
      if (mAppsControlDisallowedAdmin != null && !mAppsControlDisallowedBySystem) {
        RestrictedLockUtils.sendShowAdminSupportDetailsIntent(
            getActivity(), mAppsControlDisallowedAdmin);
        return;
      } else if (mClearCacheObserver == null) { // Lazy initialization of observer
        mClearCacheObserver = new ClearCacheObserver();
      }
      mMetricsFeatureProvider.action(getContext(),
          MetricsEvent.ACTION_SETTINGS_CLEAR_APP_CACHE);
      //  Clean up the cache 
      mPm.deleteApplicationCacheFiles(mPackageName, mClearCacheObserver);

  class ClearCacheObserver extends IPackageDataObserver.Stub {
    public void onRemoveCompleted(final String packageName, final boolean succeeded) {
      final Message msg = mHandler.obtainMessage(MSG_CLEAR_CACHE);
      msg.arg1 = succeeded ? OP_SUCCESSFUL : OP_FAILED;
      mHandler.sendMessage(msg);
    }
  }

Cache Size Interface for Android 7.0


  PackageManager mPm = mContext.getPackageManager();
  mPm.getPackageSizeInfo(mPackageName, new IPackageStatsObserver.Stub() {

    @Override
    public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {

      cacheTotalSize = pStats.cacheSize + pStats.externalCacheSize;
    }
  }


Related articles: