我正试图在Android 11+上的另一个应用程序中打开存储在外部存储根目录中的文件.
在FileProvider个文档之后,我编写了以下代码:
AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:label="@string/app_name"
android:requestLegacyExternalStorage="true">
<activity
android:name=".MainActivity"
android:exported="true">
<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.hmdm.fileprovidertest.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
Res/xml/Provider_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths><external-path name="external_files" path="."/></paths>
MainActivity.java:
private static final String FILE_PATH = "/storage/emulated/0/sample.jpg";
private static final int PERMISSIONS_REQUEST = 1000;
private static final String LOG_TAG = "FileProviderTest";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.action);
button.setOnClickListener(view -> openFile());
}
@Override
protected void onResume() {
super.onResume();
if (ContextCompat.checkSelfPermission(
this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE
}, PERMISSIONS_REQUEST);
}
}
private void openFile() {
Intent i = new Intent(Intent.ACTION_VIEW);
Uri uri;
File file = new File(FILE_PATH);
try {
uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
} catch (/*IllegalArgument*/Exception e) {
Toast.makeText(this, "Can't get URI for file: " + file.getPath(), Toast.LENGTH_LONG).show();
return;
}
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Log.d(LOG_TAG, "Opening Content Provider URI: " + uri.toString());
i.setData(uri);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Failed to find activity for VIEW intent!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
该项目的完整代码可在此处找到:https://github.com/h-mdm/FileProviderTest
问题是,当我try 为现有图像文件调用OpenFile()方法时,收到来自系统图像查看器的"Media Not Found"消息.
日志(log)cat 将显示以下消息:
Failed to find provider info for com.hmdm.fileprovidertest.provider
该应用程序能够访问该文件(如果您运行该应用程序并创建/storage/emulated/0/sample.jpg
文件,则该文件将由该应用程序本身显示).
同样的代码在安卓10及更低版本上运行良好.
我做错了什么?有没有在Android 11+上使用FileProvider的实际例子?