首页 > 解决方案 > 来自外部存储的 Android 文件选择器不适用于 API 级别 > 24

问题描述

我有运行选择代码的代码filefile manager它工作正常,API level 23但之后它在最新设备上出现问题。现在通过谷歌我知道要在最新设备上使用它我需要使用内容提供程序,我应用了一些代码但它不起作用。我只想要selected file and file will be audio.

显现:

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.example.contentproviderfilechoose"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

Java代码:

  if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {


                Uri uri = null;
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setDataAndType(uri, "*/*");
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(intent);
            } else {
                requestStoragePermission();
            }




 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

             Uri selectedFileUri = data.getData();
            //selectedFilePath = FilePath.getPath(MainActivity.this, selectedFileUri);


        } else { // Result was a failure
            Toast.makeText(this, "Picture wasn't taken!", Toast.LENGTH_SHORT).show();
        }
    }
}

标签: javaandroidandroid-studioandroid-contentproviderandroid-camera-intent

解决方案


请在 AndroidManifist.xml 文件中添加 READ_EXTERNAL_STORAGE 权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

推荐阅读