android 判断手机中是不是有SD卡,USB。静态判断

android 判断手机中是否有SD卡,USB。静态判断

对SD卡的判断分静态和动态,动态通过注册广播,网上很多人都在写,这里就不做过多的阐述。对于这种静态的判断我在网上找的都是 Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);写代码验证之后发现判断不成功。

以下这种方法算是一种可行的判断,希望对你们有所帮助。

<pre name="code" class="java">    public static boolean USBExist(Context context) {
        boolean ret = false;
        StorageManager storageManager = (StorageManager) context
                .getSystemService(Context.STORAGE_SERVICE);

        if (storageManager == null) {
            Log.e(TAG, "Invalid reference to StorageManager received.");
            return ret;
        }

        try {
            if (storageManager.getVolumeState(getUSBPath(context)).equals(
                    android.os.Environment.MEDIA_MOUNTED)) {
                ret = true;
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }

        return ret;
    }


    public static String getSDPath(Context context) {
        String sd = null;
        StorageManager storageManager = (StorageManager) context
                .getSystemService(Context.STORAGE_SERVICE);
        StorageVolume[] volumes = storageManager.getVolumeList();
        for (int i = 0; i < volumes.length; i++) {
            if (volumes[i].isRemovable() && volumes[i].allowMassStorage()
                    && volumes[i].getDescription(context).contains("SD")) {
                sd = volumes[i].getPath();
            }
        }
        return sd;
    }




以下是对USB的判断。OTG功能一般有用到

public static boolean USBExist(Context context) {
	        boolean ret = false;
	        StorageManager storageManager = (StorageManager) context
	                .getSystemService(Context.STORAGE_SERVICE);

	        if (storageManager == null) {
	            Log.e(TAG, "Invalid reference to StorageManager received.");
	            return ret;
	        }

	        try {
	            if (storageManager.getVolumeState(getUSBPath(context)).equals(
	                    android.os.Environment.MEDIA_MOUNTED)) {
	                ret = true;
	            }
	        } catch (Exception e) {
	            Log.e(TAG, e.toString());
	        }

	        return ret;
	    }
	    public static String getUSBPath(Context context) {
	        String usb = null;
	        StorageManager storageManager = (StorageManager) context
	                .getSystemService(Context.STORAGE_SERVICE);
	        StorageVolume[] volumes = storageManager.getVolumeList();

	        for (int i = 0; i < volumes.length; i++) {

	            if (volumes[i].isRemovable() && volumes[i].allowMassStorage()
	                    && volumes[i].getDescription(context).contains("USB")) {
	                usb = volumes[i].getPath();
	            }
	        }
	        return usb;
	    }













版权声明:本文为博主原创文章,未经博主允许不得转载。