Android笔记--App缓存

 获取应用缓存方式如下:

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 android.app.usage.StorageStats;
import android.app.usage.StorageStatsManager;
import android.content.pm.IPackageStatsObserver;


//高版本
  public static long getCacheSizeHight(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;
  }
  
 //低版本 
      private static long getAppCacheSizeLow(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        try {
            tempAppCacheAllSize = 0;
            Method getPackageSizeInfo = packageManager.getClass().getMethod("getPackageSizeInfo", String.class,
                    IPackageStatsObserver.class);
            getPackageSizeInfo.invoke(packageManager, packageName, new CacheSizeObserver());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
	
	
	
    static class CacheSizeObserver extends IPackageStatsObserver.Stub {

        @Override
        public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
            tempAppCacheAllSize += pStats.cacheSize+pStats.externalCacheSize;
        }
    }

你可能感兴趣的:(android,笔记,缓存)