本文章亲测有效,有部分参考自网络后测试改动,雷同请告知
//通过过滤日志输出可发现,内外存储的removable:true---state:unmounted是存在变化的我们可以通过 该removable为true state为 mounted 判断出外置存储是否挂载详情见下面函数isStorageMounted()
//
/* 2019-06-19 17:55:51.004 2330-2330/com.dami.filemanager D/LHW: path:/storage/emulated/0----removable:false---state:mounted
2019-06-19 17:55:51.004 2330-2330/com.dami.filemanager D/LHW: path:/storage/03DB-0FEC----removable:true---state:unmounted
2019-06-19 17:55:51.064 2330-2330/com.dami.filemanager D/LHW: path:/storage/emulated/0----removable:false---state:mounted
2019-06-19 17:55:51.064 2330-2330/com.dami.filemanager D/LHW: path:/storage/03DB-0FEC----removable:true---state:unmounted*/
}
public static void testVolume(Context context){
ArrayList list_volume =getVolume(context);
for (int i = 0; i < list_volume.size(); i++) {
LogUtils.D("LHW", "path:" + list_volume.get(i).getPath() + "----" + "removable:" + list_volume.get(i).isRemovable() + "---" + "state:" + list_volume.get(i).getState());
}
/*
获取全部存储设备信息封装对象
*/
public static ArrayList getVolume(Context context) {
ArrayList list_storagevolume = new ArrayList();
StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
try {
Method method_volumeList = StorageManager.class.getMethod("getVolumeList");
method_volumeList.setAccessible(true);
Object[] volumeList = (Object[]) method_volumeList.invoke(storageManager);
if (volumeList != null) {
Volume volume;
for (int i = 0; i < volumeList.length; i++) {
try {
volume = new Volume();
volume.setPath((String) volumeList[i].getClass().getMethod("getPath").invoke(volumeList[i]));
volume.setRemovable((boolean) volumeList[i].getClass().getMethod("isRemovable").invoke(volumeList[i]));
volume.setState((String) volumeList[i].getClass().getMethod("getState").invoke(volumeList[i]));
list_storagevolume.add(volume);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
} else {
LogUtils.D("null-------------------------------------");
}
} catch (Exception e1) {
e1.printStackTrace();
}
return list_storagevolume;
}
/**
* 通过反射调用获取内置存储和外置sd卡根路径(通用)
*
* @param mContext 上下文
* @param is_removale 是否可移除,false返回内部存储,true返回外置sd卡
* @return
*/
private static String getStoragePath(Context mContext, boolean is_removale) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class> storageVolumeClazz = null;
String path="";
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (is_removale == removable) {
return path;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return path;
}
/**
* 判断外置sd卡是否挂载
*/
public static boolean isStorageMounted(Context mContext) {
boolean isMounted = false;
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Method getState = storageVolumeClazz.getMethod("getState");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
String state = (String) getState.invoke(storageVolumeElement);
if (removable && state.equals(Environment.MEDIA_MOUNTED)) {
isMounted =removable ;
break;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return isMounted;
}
/**
* 获取手机内部剩余存储空间
*
* @return
*/
public static long getAvailableInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
}
/**
* 获取手机内部总的存储空间
*
* @return
*/
public static long getTotalInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
}
/**
* 获取SDCARD剩余存储空间
*
* @return
*/
public static long getAvailableExternalMemorySize() {
if (externalMemoryAvailable()) {
// File path = Environment.getExternalStorageDirectory();
// StatFs stat = new StatFs(path.getPath());
StatFs stat = new StatFs(getStoragePath(context,true));//path.getPath()
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
} else {
return ERROR;
}
}
/**
* 获取SDCARD总的存储空间
*
* @return
*/
public static long getTotalExternalMemorySize() {
if (externalMemoryAvailable()) {
// File path = Environment.getExternalStorageDirectory();
// StatFs stat = new StatFs(path.getPath());
StatFs stat = new StatFs(getStoragePath(context,true));//path.getPath()
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
} else {
return ERROR;
}
}
/**
* 获取系统总内存
*
* @param context 可传入应用程序上下文。
* @return 总内存大单位为B。
*/
public static long getTotalMemorySize(Context context) {
String dir = "/proc/meminfo";
try {
FileReader fr = new FileReader(dir);
BufferedReader br = new BufferedReader(fr, 2048);
String memoryLine = br.readLine();
String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
br.close();
return Integer.parseInt(subMemoryLine.replaceAll("\\D+", "")) * 1024l;
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
/**
* 获取当前可用内存,返回数据以字节为单位。
*
* @param context 可传入应用程序上下文。
* @return 当前可用内存单位为B。
*/
public static long getAvailableMemory(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
am.getMemoryInfo(memoryInfo);
return memoryInfo.availMem;
}
private static DecimalFormat fileIntegerFormat = new DecimalFormat("#0");
private static DecimalFormat fileDecimalFormat = new DecimalFormat("#0.#");
/**
* 单位换算
*
* @param size 单位为B
* @param isInteger 是否返回取整的单位
* @return 转换后的单位
*/
public static String formatFileSize(long size, boolean isInteger) {
DecimalFormat df = isInteger ? fileIntegerFormat : fileDecimalFormat;
String fileSizeString = "0M";
if (size < 1024 && size > 0) {
fileSizeString = df.format((double) size) + "B";
} else if (size < 1024 * 1024) {
fileSizeString = df.format((double) size / 1024) + "K";
} else if (size < 1024 * 1024 * 1024) {
fileSizeString = df.format((double) size / (1024 * 1024)) + "M";
} else {
fileSizeString = df.format((double) size / (1024 * 1024 * 1024)) + "G";
}
return fileSizeString;
}
}
//初始化receiver
protected void onResume()
{
super.onResume();
IntentFilter intentFilter = new IntentFilter(
Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
intentFilter.addDataScheme("file");
// install an intent filter to receive SD card related events.
mReceiver = new BroadcastReceiver()
{
public void onReceive(Context arg0, Intent arg1)
{
onReceiveSdCardBroadCast(arg1);
}
};
registerReceiver(mReceiver, intentFilter);
initUI(!isUnMount);
}
//接到广播后处理
private void onReceiveSdCardBroadCast(Intent intent)
{
String action = intent.getAction();
Log.i(TAG, "receive broadcast " + action);
if (Intent.ACTION_MEDIA_MOUNTED.equals(action))
{
initUI(true);
}
else if (Intent.ACTION_MEDIA_UNMOUNTED.equals(action))
{
initUI(false);
}
else if (Intent.ACTION_MEDIA_EJECT.equals(action))
{
initUI(false);
}
}
//注销receiver
protected void onDestroy()
{
Log.i(TAG, TAG + " is onDestroy");
super.onDestroy();
if (mReceiver != null)
{
unregisterReceiver(mReceiver);
mReceiver = null;
}
}