Hello,
Welcome to our Microsoft Q&A platform!
Based on my research, I find this issue is related this line: Android.Net.Uri path = Android.Net.Uri.FromFile(file);
.
After android 7.0, You should use FileProvider to generate the Android.Net.Uri
.
Firstly, If you want to use it. please add <provider>
code in your AndroidManifest.xml
like following code.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.startactivitydemo11">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="30" />
<application android:label="StartActivityDemo11.Android" android:theme="@style/MainTheme">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.companyname.startactivitydemo11.fileProvider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
Then create a xml folder, add file_paths.xml
.
add following code.
<?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
Here is my edited code.
var documentsDirectry = Android.App.Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDocuments);
Java.IO.File file = new Java.IO.File(documentsDirectry, "icon1.txt");
file.CreateNewFile();
Context context = Android.App.Application.Context;
if (file.Exists())
{
Android.Net.Uri path = FileProvider.GetUriForFile(global::Android.App.Application.Context, global::Android.App.Application.Context.PackageName + ".fileProvider", file);
// Android.Net.Uri path = Android.Net.Uri.FromFile(file);
string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
Intent intent = new Intent(Intent.ActionOpenDocument);
intent.SetDataAndType(path, mimeType);
context.StartActivity(Intent.CreateChooser(intent, "Choose App").AddFlags(ActivityFlags.NewTask));
}
Here is my running screenshot.
Best Regards,
Leon Lu
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.