Scoped目录访问API抛出NullPointerException

时间:2016-07-29 05:26:19

标签: android android-7.0-nougat

我目前正在尝试为我的应用添加Android N支持。我使用新的Scoped Directory Access API在外部存储上读取应用的应用存储目录,如下所示:

public void requestExternalStoragePermissions(int requestCode) {
    StorageManager sm = (StorageManager)getContext().getSystemService(Context.STORAGE_SERVICE);
    StorageVolume volume = sm.getPrimaryStorageVolume();
    Intent intent = volume.createAccessIntent("MyApp");
    startActivityForResult(intent, requestCode);
}

但是,我在NullPointerException上获得了startActivityForResult

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Intent.migrateExtraStreamToClipData()' on a null object reference
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1635)
    at android.app.Activity.startActivityForResult(Activity.java:4858)
    at android.app.Activity.startActivityFromFragment(Activity.java:4844)
    at android.app.Activity$HostCallbacks.onStartActivityFromFragment(Activity.java:7125)
    at android.app.Fragment.startActivityForResult(Fragment.java:1150)
    at android.app.Fragment.startActivityForResult(Fragment.java:1139)
    ....

我做错了什么?

用户必须可以在文件管理器中轻松访问这些文件,因此getExternalFilesDir() NOT 是一个选项。

1 个答案:

答案 0 :(得分:1)

原来新的Scoped Directory Access API仅支持标准媒体目录(DocumentsMusicPictures等。

来自API reference for StorageVolume.createAccessIntent(String directoryName)

directoryName:必须是DIRECTORY_MUSICDIRECTORY_PODCASTSDIRECTORY_RINGTONESDIRECTORY_ALARMSDIRECTORY_NOTIFICATIONSDIRECTORY_PICTURES之一{ {1}},DIRECTORY_MOVIESDIRECTORY_DOWNLOADSDIRECTORY_DCIMDIRECTORY_DOCUMENTS请求访问整个卷。