Android

个人Android学习总结


Android判断SD卡

<p>Android判断SD卡</p> <pre><code class="language-java">最近程序中需要查看sd卡是否挂载,在网上看到有用Environment.MEDIA_MOUNTED来判断是否有sd卡,但实际上Environment.getExternalStorageState()得到的手机内置sd卡的状态。这里有一种方法查看外置sd卡,使用StorageVolume类,这里需要通过反射实现。StorageManager调用getVolumeList方法返回StorageVolume对象StorageVolume对象保存着卷信息,StorageVolume的isRemovable判断是否可以卸载,如果可以卸载则是sd卡。代码如下:</code></pre> <pre><code class="language-java">private boolean isSDMounted() { boolean isMounted = false; StorageManager sm = (StorageManager) getSystemService(Context.STORAGE_SERVICE); try { Method getVolumList = StorageManager.class.getMethod(&amp;quot;getVolumeList&amp;quot;, null); getVolumList.setAccessible(true); Object[] results = (Object[])getVolumList.invoke(sm, null); if (results != null) { for (Object result : results) { Method mRemoveable = result.getClass().getMethod(&amp;quot;isRemovable&amp;quot;, null); Boolean isRemovable = (Boolean) mRemoveable.invoke(result, null); if (isRemovable) { Method getPath = result.getClass().getMethod(&amp;quot;getPath&amp;quot;, null); String path = (String) getPath.invoke(result, null); Method getState = sm.getClass().getMethod(&amp;quot;getVolumeState&amp;quot;, String.class); String state = (String)getState.invoke(sm, path); if (state.equals(Environment.MEDIA_MOUNTED)) { isMounted = true; break; } } } } } catch (NoSuchMethodException e){ e.printStackTrace(); } catch (IllegalAccessException e){ e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return isMounted; } </code></pre> <pre><code class="language-java"> /** *这里其实判断到的是getExternalStorageState : mounted *getPath : /storage/emulated/0 *getAbsolutePath : /storage/emulated/0 * 判断是否有SD卡是否存在 */ public static boolean hasSDCard() { boolean hasSdCard = Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState()) ; LogUtil.d(TAG, &amp;quot;hasSdCard : &amp;quot; + hasSdCard); return hasSdCard ; }</code></pre>

页面列表

ITEM_HTML