Environment.getExternalStorageState()上的NPE?

时间:2014-04-16 16:45:03

标签: android android-external-storage

找不到我得到的原因"空指针异常" 。我可以给出一个明确的检查,看看" getStorageState是否为空"但这并不能解释为什么我会收到此错误。 错误是:

java.lang.NullPointerException
at android.os.Environment.getStorageState(Environment.java:719)
at android.os.Environment.getExternalStorageState(Environment.java:694)
at com.ciqual.android.insight.sessionService.RemoveFiles(SessionService.java:664)
com.vyshas.android.sessionService.onEndSession(SessionService.java:460)

at :(错误指向的行是这个:)(见于豆豆4.3和kitkat)

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //
        }

2 个答案:

答案 0 :(得分:0)

Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState)不会导致NPE,而Environment.getExternalStorageState()。equals(Environment.MEDIA_MOUNTED)确实会导致NPE并导致应用程序崩溃。

我仍然不知道为什么getExternalStorageState为null虽然我已经设置了权限,但atleast解决方案不会使应用程序崩溃。

答案 1 :(得分:0)

我从Android 4.3获得了类似的报告。

源代码是:

    /**
     * Gets the current state of the primary "external" storage device.
     *
     * @see #getExternalStorageDirectory()
     */
    public static String getExternalStorageState() {
        try {
            IMountService mountService = IMountService.Stub.asInterface(ServiceManager
                    .getService("mount"));
            final StorageVolume primary = getPrimaryVolume();
            return mountService.getVolumeState(primary.getPath());
        } catch (RemoteException rex) {
            Log.w(TAG, "Failed to read external storage state; assuming REMOVED: " + rex);
            return Environment.MEDIA_REMOVED;
        }
    }

我无所事事,只能抓住它。