1、简介
获取手机,内置存储、内置sd卡 ,外置SD 卡 路径
2、功能实现
package com.example.ts.myapplication;
import android.content.Context;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String TAG = "lum: ";
String path = "";
Button buttonNC,buttonNZSD,buttonWZSD;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonNC = (Button) findViewById(R.id.but_nz_id); //内部存储
buttonNZSD = (Button) findViewById(R.id.but_nzsd_id); //内置SD卡
buttonWZSD = (Button) findViewById(R.id.but_wz_id); //外置SD 卡
buttonNC.setOnClickListener(this);
buttonNZSD.setOnClickListener(this);
buttonWZSD.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.but_nz_id: //获取内部存储 路径
path = Environment.getDataDirectory().toString();
Log.i(TAG,"内部存储路径 " + path);
break;
case R.id.but_nzsd_id: //获取 内置 SD 卡路径
path = getStoragePath(this,false); //一种方法
Log.i(TAG,"内置SD 卡的路径 方法 1: " + path);
path = Environment.getExternalStorageDirectory().toString(); //另一种方法
Log.i(TAG,"内置SD 卡的路径 方法 2: " + path);
break;
case R.id.but_wz_id: // 获取 外置 sd 卡路径
path = getStoragePath(this,true);
Log.i(TAG,"外置SD 卡的路径: " + path);
break;
}
}
/**
* 通过反射调用获取内置存储和外置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;
}
}