下面列出了怎么用android.os.storage.StorageManager的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public int movePackage(String packageName, VolumeInfo vol) {
try {
final String volumeUuid;
if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
} else if (vol.isPrimaryPhysical()) {
volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
} else {
volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
}
return mPM.movePackage(packageName, volumeUuid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Returns the file categorization result for the primary internal storage UUID.
*
* @param context
*/
public static MeasurementResult getMeasurementResult(Context context) {
MeasurementResult result = new MeasurementResult();
StorageStatsManager ssm =
(StorageStatsManager) context.getSystemService(Context.STORAGE_STATS_SERVICE);
ExternalStorageStats stats = null;
try {
stats =
ssm.queryExternalStatsForUser(
StorageManager.UUID_PRIVATE_INTERNAL,
UserHandle.of(context.getUserId()));
result.imagesSize = stats.getImageBytes();
result.videosSize = stats.getVideoBytes();
result.audioSize = stats.getAudioBytes();
result.miscSize =
stats.getTotalBytes()
- result.imagesSize
- result.videosSize
- result.audioSize;
} catch (IOException e) {
throw new IllegalStateException("Could not query storage");
}
return result;
}
@Override
public int movePackage(String packageName, VolumeInfo vol) {
try {
final String volumeUuid;
if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
} else if (vol.isPrimaryPhysical()) {
volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
} else {
volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
}
return mPM.movePackage(packageName, volumeUuid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public @NonNull List<VolumeInfo> getPrimaryStorageCandidateVolumes() {
final StorageManager storage = mContext.getSystemService(StorageManager.class);
final VolumeInfo currentVol = getPrimaryStorageCurrentVolume();
final List<VolumeInfo> vols = storage.getVolumes();
final List<VolumeInfo> candidates = new ArrayList<>();
if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL,
storage.getPrimaryStorageUuid()) && currentVol != null) {
// TODO: support moving primary physical to emulated volume
candidates.add(currentVol);
} else {
for (VolumeInfo vol : vols) {
if (Objects.equals(vol, currentVol) || isPrimaryStorageCandidateVolume(vol)) {
candidates.add(vol);
}
}
}
return candidates;
}
@Override
public int movePackage(String packageName, VolumeInfo vol) {
try {
final String volumeUuid;
if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
} else if (vol.isPrimaryPhysical()) {
volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
} else {
volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
}
return mPM.movePackage(packageName, volumeUuid);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
@Override
public int movePrimaryStorage(VolumeInfo vol) {
try {
final String volumeUuid;
if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
} else if (vol.isPrimaryPhysical()) {
volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
} else {
volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
}
return mPM.movePrimaryStorage(volumeUuid);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
/**
* API 26 android O
* 获取总共容量大小,包括系统大小
*/
@RequiresApi(Build.VERSION_CODES.O)
public static long getTotalSize(Context context, String fsUuid) {
try {
UUID id;
if (fsUuid == null) {
id = StorageManager.UUID_DEFAULT;
} else {
id = UUID.fromString(fsUuid);
}
StorageStatsManager stats = context.getSystemService(StorageStatsManager.class);
return stats.getTotalBytes(id);
} catch (NoSuchFieldError | NoClassDefFoundError | NullPointerException | IOException e) {
e.printStackTrace();
return -1;
}
}
@Override
public int movePrimaryStorage(VolumeInfo vol) {
try {
final String volumeUuid;
if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
} else if (vol.isPrimaryPhysical()) {
volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
} else {
volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
}
return mPM.movePrimaryStorage(volumeUuid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public int movePackage(String packageName, VolumeInfo vol) {
try {
final String volumeUuid;
if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
} else if (vol.isPrimaryPhysical()) {
volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
} else {
volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
}
return mPM.movePackage(packageName, volumeUuid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
private static int isSdcardMounted(String path, Context context) {
StorageManager managerStorage = (StorageManager) context.getSystemService("storage");
if (managerStorage == null) {
return -1;
}
try {
Method method = managerStorage.getClass().getDeclaredMethod("getVolumeState", new Class[]{String.class});
method.setAccessible(true);
if ("mounted".equalsIgnoreCase((String) method.invoke(managerStorage, new Object[]{path}))) {
return 1;
}
return 0;
} catch (NoSuchMethodException e) {
e.printStackTrace();
return -1;
} catch (IllegalArgumentException e2) {
e2.printStackTrace();
return -1;
} catch (IllegalAccessException e3) {
e3.printStackTrace();
return -1;
} catch (InvocationTargetException e4) {
e4.printStackTrace();
return -1;
}
}
@Override
public int movePrimaryStorage(VolumeInfo vol) {
try {
final String volumeUuid;
if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
} else if (vol.isPrimaryPhysical()) {
volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
} else {
volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
}
return mPM.movePrimaryStorage(volumeUuid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public @NonNull List<VolumeInfo> getPrimaryStorageCandidateVolumes() {
final StorageManager storage = mContext.getSystemService(StorageManager.class);
final VolumeInfo currentVol = getPrimaryStorageCurrentVolume();
final List<VolumeInfo> vols = storage.getVolumes();
final List<VolumeInfo> candidates = new ArrayList<>();
if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL,
storage.getPrimaryStorageUuid()) && currentVol != null) {
// TODO: support moving primary physical to emulated volume
candidates.add(currentVol);
} else {
for (VolumeInfo vol : vols) {
if (Objects.equals(vol, currentVol) || isPrimaryStorageCandidateVolume(vol)) {
candidates.add(vol);
}
}
}
return candidates;
}
/**
* 获取外置 SD根目录
*
* @return
*/
private static String getSDCardStoragePath(Context appContext) {
if (TextUtils.isEmpty(SDCardPath)) {
try {
StorageManager sm =
(StorageManager) appContext.getSystemService(Context.STORAGE_SERVICE);
Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths");
String[] paths = (String[]) getVolumePathsMethod.invoke(sm);
// second element in paths[] is secondary storage path
SDCardPath = paths.length <= 1 ? paths[0] : null;
return SDCardPath;
} catch (Exception e) {
Log.e(TAG, "getSecondaryStoragePath() failed", e);
}
} else {
return SDCardPath;
}
return null;
}
@Override
public int movePackage(String packageName, VolumeInfo vol) {
try {
final String volumeUuid;
if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
} else if (vol.isPrimaryPhysical()) {
volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
} else {
volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
}
return mPM.movePackage(packageName, volumeUuid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public int movePrimaryStorage(VolumeInfo vol) {
try {
final String volumeUuid;
if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
} else if (vol.isPrimaryPhysical()) {
volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
} else {
volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
}
return mPM.movePrimaryStorage(volumeUuid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
private void showEncryptionNotification(UserHandle user, CharSequence title,
CharSequence message, CharSequence detail, PendingIntent intent) {
if (DEBUG) Slog.v(TAG, "showing encryption notification, user: " + user.getIdentifier());
// Suppress all notifications on non-FBE devices for now
if (!StorageManager.isFileEncryptedNativeOrEmulated()) return;
Notification notification =
new Notification.Builder(mContext, SystemNotificationChannels.SECURITY)
.setSmallIcon(com.android.internal.R.drawable.ic_user_secure)
.setWhen(0)
.setOngoing(true)
.setTicker(title)
.setColor(mContext.getColor(
com.android.internal.R.color.system_notification_accent_color))
.setContentTitle(title)
.setContentText(message)
.setSubText(detail)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(intent)
.build();
mNotificationManager.notifyAsUser(null, SystemMessage.NOTE_FBE_ENCRYPTED_NOTIFICATION,
notification, user);
}
@Override
public @NonNull List<VolumeInfo> getPrimaryStorageCandidateVolumes() {
final StorageManager storage = mContext.getSystemService(StorageManager.class);
final VolumeInfo currentVol = getPrimaryStorageCurrentVolume();
final List<VolumeInfo> vols = storage.getVolumes();
final List<VolumeInfo> candidates = new ArrayList<>();
if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL,
storage.getPrimaryStorageUuid()) && currentVol != null) {
// TODO: support moving primary physical to emulated volume
candidates.add(currentVol);
} else {
for (VolumeInfo vol : vols) {
if (Objects.equals(vol, currentVol) || isPrimaryStorageCandidateVolume(vol)) {
candidates.add(vol);
}
}
}
return candidates;
}
/**
* API 26 android O
* 获取总共容量大小,包括系统大小
*/
@SuppressLint("NewApi")
public static long getTotalSize(Context context, String fsUuid) {
try {
UUID id;
if (fsUuid == null) {
id = StorageManager.UUID_DEFAULT;
} else {
id = UUID.fromString(fsUuid);
}
StorageStatsManager stats = context.getSystemService(StorageStatsManager.class);
return stats.getTotalBytes(id);
} catch (NoSuchFieldError | NoClassDefFoundError | NullPointerException | IOException e) {
e.printStackTrace();
return -1;
}
}
/**
* Ensure that given directories exist, trying to create them if missing. If
* unable to create, they are filtered by replacing with {@code null}.
*/
private File[] ensureExternalDirsExistOrFilter(File[] dirs) {
final StorageManager sm = getSystemService(StorageManager.class);
final File[] result = new File[dirs.length];
for (int i = 0; i < dirs.length; i++) {
File dir = dirs[i];
if (!dir.exists()) {
if (!dir.mkdirs()) {
// recheck existence in case of cross-process race
if (!dir.exists()) {
// Failing to mkdir() may be okay, since we might not have
// enough permissions; ask vold to create on our behalf.
try {
sm.mkdirs(dir);
} catch (Exception e) {
Log.w(TAG, "Failed to ensure " + dir + ": " + e);
dir = null;
}
}
}
}
result[i] = dir;
}
return result;
}
@Override
public @NonNull List<VolumeInfo> getPrimaryStorageCandidateVolumes() {
final StorageManager storage = mContext.getSystemService(StorageManager.class);
final VolumeInfo currentVol = getPrimaryStorageCurrentVolume();
final List<VolumeInfo> vols = storage.getVolumes();
final List<VolumeInfo> candidates = new ArrayList<>();
if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL,
storage.getPrimaryStorageUuid()) && currentVol != null) {
// TODO: support moving primary physical to emulated volume
candidates.add(currentVol);
} else {
for (VolumeInfo vol : vols) {
if (Objects.equals(vol, currentVol) || isPrimaryStorageCandidateVolume(vol)) {
candidates.add(vol);
}
}
}
return candidates;
}
private static Uri getFileUri(StorageManager sm, String type, String[] split) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
if (volumes == null) {
Method getVolumeListMethod = sm.getClass().getMethod("getVolumeList", new Class[0]);
volumes = (Object[]) getVolumeListMethod.invoke(sm);
}
for (Object volume : volumes) {
Method getUuidMethod = volume.getClass().getMethod("getUuid", new Class[0]);
String uuid = (String) getUuidMethod.invoke(volume);
if (uuid != null && uuid.equalsIgnoreCase(type)) {
Method getPathMethod = volume.getClass().getMethod("getPath", new Class[0]);
String path = (String) getPathMethod.invoke(volume);
File file = new File(path, split[1]);
return Uri.fromFile(file);
}
}
return null;
}
/**
* 得到所有的存储路径(内部存储+外部存储)
*
* @param context context
* @return 路径列表
*/
public static List<String> getAllSdPaths(Context context) {
Method mMethodGetPaths = null;
String[] paths = null;
//通过调用类的实例mStorageManager的getClass()获取StorageManager类对应的Class对象
//getMethod("getVolumePaths")返回StorageManager类对应的Class对象的getVolumePaths方法,这里不带参数
StorageManager mStorageManager = (StorageManager) context
.getSystemService(context.STORAGE_SERVICE);//storage
try {
mMethodGetPaths = mStorageManager.getClass().getMethod("getVolumePaths");
paths = (String[]) mMethodGetPaths.invoke(mStorageManager);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (paths != null) {
return Arrays.asList(paths);
}
return new ArrayList<String>();
}
@Override
public int movePrimaryStorage(VolumeInfo vol) {
try {
final String volumeUuid;
if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
} else if (vol.isPrimaryPhysical()) {
volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
} else {
volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
}
return mPM.movePrimaryStorage(volumeUuid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* API 26 android O
* 获取总共容量大小,包括系统大小
*/
@RequiresApi(api = 26)
public long getTotalSize(String fsUuid) {
try {
UUID id;
if (fsUuid == null) {
id = StorageManager.UUID_DEFAULT;
} else {
id = UUID.fromString(fsUuid);
}
StorageStatsManager stats = (StorageStatsManager) getSystemService(Context.STORAGE_STATS_SERVICE);
return stats.getTotalBytes(id);
} catch (NoSuchFieldError | NoClassDefFoundError | NullPointerException | IOException e) {
e.printStackTrace();
ToastUtils.show(this, "获取存储大小失败");
return -1;
}
}
public static ArrayList<String> getStorageData(Context pContext) {
final StorageManager storageManager = (StorageManager) pContext.getSystemService(Context.STORAGE_SERVICE);
try {
final Method getVolumeList = storageManager.getClass().getMethod("getVolumeList");
final Class<?> storageValumeClazz = Class.forName("android.os.storage.StorageVolume");
final Method getPath = storageValumeClazz.getMethod("getPath");
final Object invokeVolumeList = getVolumeList.invoke(storageManager);
final int length = Array.getLength(invokeVolumeList);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < length; i++) {
final Object storageValume = Array.get(invokeVolumeList, i);//得到StorageVolume对象
final String path = (String) getPath.invoke(storageValume);
list.add(path);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public void forgetAllVolumes() {
enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
synchronized (mLock) {
for (int i = 0; i < mRecords.size(); i++) {
final String fsUuid = mRecords.keyAt(i);
final VolumeRecord rec = mRecords.valueAt(i);
if (!TextUtils.isEmpty(rec.partGuid)) {
mHandler.obtainMessage(H_PARTITION_FORGET, rec).sendToTarget();
}
mCallbacks.notifyVolumeForgotten(fsUuid);
}
mRecords.clear();
if (!Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)) {
mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
}
writeSettingsLocked();
mHandler.obtainMessage(H_RESET).sendToTarget();
}
}
public static long getExternalStorageSize(Context context) {
long j = 0;
try {
String[] paths = (String[]) StorageManager.class.getMethod("getVolumePaths", new Class[0]).invoke((StorageManager) context.getSystemService("storage"), new Object[0]);
if (paths != null && paths.length >= 2) {
StatFs statFs = new StatFs(paths[1]);
j = ((((long) statFs.getBlockCount()) * ((long) statFs.getBlockSize())) / 1024) / 1024;
}
} catch (Exception e) {
LogTool.e(TAG, "getExternalStorageSize. " + e.toString());
}
return j;
}
@Override
public SharedPreferences getSharedPreferences(File file, int mode) {
checkMode(mode);
if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) {
if (isCredentialProtectedStorage()
&& !getSystemService(StorageManager.class).isUserKeyUnlocked(
UserHandle.myUserId())
&& !isBuggy()) {
throw new IllegalStateException("SharedPreferences in credential encrypted "
+ "storage are not available until after user is unlocked");
}
}
SharedPreferencesImpl sp;
synchronized (ContextImpl.class) {
final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
sp = cache.get(file);
if (sp == null) {
sp = new SharedPreferencesImpl(file, mode);
cache.put(file, sp);
return sp;
}
}
if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
// If somebody else (some other process) changed the prefs
// file behind our back, we reload it. This has been the
// historical (if undocumented) behavior.
sp.startReloadIfChangedUnexpectedly();
}
return sp;
}
private void updateBroadcasts(VolumeInfo vol, int oldLevel, int newLevel, int seq) {
if (!Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, vol.getFsUuid())) {
// We don't currently send broadcasts for secondary volumes
return;
}
final Intent lowIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_LOW)
.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
| Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
| Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS)
.putExtra(EXTRA_SEQUENCE, seq);
final Intent notLowIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_OK)
.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
| Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
| Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS)
.putExtra(EXTRA_SEQUENCE, seq);
if (State.isEntering(State.LEVEL_LOW, oldLevel, newLevel)) {
getContext().sendStickyBroadcastAsUser(lowIntent, UserHandle.ALL);
} else if (State.isLeaving(State.LEVEL_LOW, oldLevel, newLevel)) {
getContext().removeStickyBroadcastAsUser(lowIntent, UserHandle.ALL);
getContext().sendBroadcastAsUser(notLowIntent, UserHandle.ALL);
}
final Intent fullIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_FULL)
.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT)
.putExtra(EXTRA_SEQUENCE, seq);
final Intent notFullIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_NOT_FULL)
.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT)
.putExtra(EXTRA_SEQUENCE, seq);
if (State.isEntering(State.LEVEL_FULL, oldLevel, newLevel)) {
getContext().sendStickyBroadcastAsUser(fullIntent, UserHandle.ALL);
} else if (State.isLeaving(State.LEVEL_FULL, oldLevel, newLevel)) {
getContext().removeStickyBroadcastAsUser(fullIntent, UserHandle.ALL);
getContext().sendBroadcastAsUser(notFullIntent, UserHandle.ALL);
}
}
@VisibleForTesting
protected @NonNull List<VolumeInfo> getPackageCandidateVolumes(ApplicationInfo app,
StorageManager storageManager, IPackageManager pm) {
final VolumeInfo currentVol = getPackageCurrentVolume(app, storageManager);
final List<VolumeInfo> vols = storageManager.getVolumes();
final List<VolumeInfo> candidates = new ArrayList<>();
for (VolumeInfo vol : vols) {
if (Objects.equals(vol, currentVol)
|| isPackageCandidateVolume(mContext, app, vol, pm)) {
candidates.add(vol);
}
}
return candidates;
}