简体   繁体   中英

Micro Sd card detection

Is there a way to detect a micro sd card in android? I know the Environment class gives external storage details. But it just gives the in built sd card details. Is there a way around?

You can use isExternalStorageEmulated() to find out if the current "external" storage is actually a real external storage or just part of the internal storage. If it's real then you should get the properties of the removable card.

Try this:

boolean canSaveExternal = false;
String storageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(storageState))
    canSaveExternal = true;
else
    canSaveExternal = false;

Environment.getExternalStorageState() and Environment.getExternalStorageDirectory() will provide the built-in SD card, which is almost existing on all currently Android devices now.

Two methods to get the "real" external SD card (or USB disk).

  1. Use the getVolumeList() function to list all removable storages, remember to check the mount state before you access it.

     private static String getExtendedMemoryPath(Context context) { StorageManager mStorageManager = (StorageManager) context.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); 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); if (removable) { return path; } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } 
  2. Register android.intent.action.MEDIA_MOUNTED event, when a storage is mounted, will broadcast this intent with the mounted disk path.

     <receiver android:enabled="true" android:name=".MountStatusReceiver"> <intent-filter> <action android:name="android.intent.action.MEDIA_MOUNTED"/> <data android:scheme="file"/> </intent-filter> </receiver> @Override public void onReceive(Context context, Intent intent) { if (intent != null) { if (Intent.ACTION_MEDIA_MOUNTED.equals(intent.getAction())) { path = intent.getDataString().replace("file://", ""); } } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM