//MainActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "zwm, onCreate");
setContentView(R.layout.activity_main);
Log.d(TAG, "zwm, external sdcard path: " + getStoragePath(this, true));
Log.d(TAG, "zwm, internal sdcard path: " + getStoragePath(this, false));
}
/**
* 通过反射调用获取内置存储和外置sd卡根路径(通用)
*
* @param mContext 上下文
* @param is_removale 是否可移除,false返回内部存储路径,true返回外置SD卡路径
* @return
*/
private static String getStoragePath(Context mContext, boolean is_removale) {
String path = "";
//使用getSystemService(String)检索一个StorageManager用于访问系统存储功能。
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");
Object result = getVolumeList.invoke(mStorageManager);
for (int i = 0; i < Array.getLength(result); 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 (Exception e) {
e.printStackTrace();
}
return path;
}
}
网友评论