下面列出了怎么用android.app.usage.StorageStats的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_START_LOADING_SIZES: {
List<PackageStats> stats = new ArrayList<>();
List<UserInfo> users = mUm.getUsers();
for (int userCount = 0, userSize = users.size();
userCount < userSize; userCount++) {
UserInfo user = users.get(userCount);
final List<ApplicationInfo> apps = mPm.getInstalledApplicationsAsUser(
PackageManager.MATCH_DISABLED_COMPONENTS, user.id);
for (int appCount = 0, size = apps.size(); appCount < size; appCount++) {
ApplicationInfo app = apps.get(appCount);
if (!Objects.equals(app.volumeUuid, mVolume.getFsUuid())) {
continue;
}
try {
StorageStats storageStats =
mStorageStatsManager.queryStatsForPackage(app.storageUuid,
app.packageName, user.getUserHandle());
PackageStats packageStats = new PackageStats(app.packageName,
user.id);
packageStats.cacheSize = storageStats.getCacheBytes();
packageStats.codeSize = storageStats.getAppBytes();
packageStats.dataSize = storageStats.getDataBytes();
stats.add(packageStats);
} catch (NameNotFoundException | IOException e) {
Log.e(TAG, "An exception occurred while fetching app size", e);
}
}
}
mStats.complete(stats);
}
}
}
/**
* 获取应用的大小
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private static void getAppSizeAboveO(Context context, @NonNull OnGetSizeListener listener) {
StorageStatsManager storageStatsManager = (StorageStatsManager) context
.getSystemService(Context.STORAGE_STATS_SERVICE);
StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
// 获取所有应用的StorageVolume列表
List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
for (StorageVolume item : storageVolumes) {
String uuidStr = item.getUuid();
UUID uuid;
if (uuidStr == null) {
uuid = StorageManager.UUID_DEFAULT;
} else {
uuid = UUID.fromString(uuidStr);
}
int uid = getUid(context, context.getPackageName());
// 通过包名获取uid
StorageStats storageStats;
try {
storageStats = storageStatsManager.queryStatsForUid(uuid, uid);
AppSizeInfo ctAppSizeInfo = new AppSizeInfo();
ctAppSizeInfo.cacheSize = storageStats.getCacheBytes();
ctAppSizeInfo.dataSize = storageStats.getDataBytes();
ctAppSizeInfo.codeSize = storageStats.getAppBytes();
listener.onGetSize(ctAppSizeInfo);
} catch (IOException e) {
listener.onError(e);
}
}
}