天天看點

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;
	    }