java - 来自外部存储的 Android 文件选择器不适用于 API 级别 > 24
问题描述
我有运行选择代码的代码file
,file 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();
}
}
}
解决方案
请在 AndroidManifist.xml 文件中添加 READ_EXTERNAL_STORAGE 权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
推荐阅读
- r - 基于匹配多个数据集中的多个条件和日期范围添加列
- python - 如何使用 scrapy 抓取 Instagram 查询?
- python - 为什么在 Pandas 数据框中使用 Z 分数进行归一化会生成 NaN 列?
- javascript - JSX 中的条件渲染
- ruby-on-rails - 使用 Mailchimp 3.0 API 和 Gibbon [rails] 检查成员是否存在
- node.js - shelljs“未找到”错误
- javascript - 函数包装器如何交互?
- ios - CoreData 更新 Model.xcdatamodeld 后删除所有对象
- c# - SonarLint 是否比 SonarAnalyzer.CSharp 提供任何优势
- jsf - 如何在primefaces中的任何形式之外更新tabView