-
Notifications
You must be signed in to change notification settings - Fork 493
Expand file tree
/
Copy pathFolderPickerImplementation.android.cs
More file actions
62 lines (50 loc) · 2.11 KB
/
FolderPickerImplementation.android.cs
File metadata and controls
62 lines (50 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System.Diagnostics;
using System.Runtime.Versioning;
using System.Web;
using Android.Content;
using Android.Provider;
using CommunityToolkit.Maui.Core.Essentials;
using CommunityToolkit.Maui.Core.Extensions;
using CommunityToolkit.Maui.Core.Primitives;
using Microsoft.Maui.ApplicationModel;
using AndroidUri = Android.Net.Uri;
namespace CommunityToolkit.Maui.Storage;
/// <inheritdoc />
[SupportedOSPlatform("Android26.0")]
public sealed partial class FolderPickerImplementation : IFolderPicker
{
static async Task<Folder> InternalPickAsync(string initialPath, CancellationToken cancellationToken)
{
if (!OperatingSystem.IsAndroidVersionAtLeast(26) && !string.IsNullOrEmpty(initialPath))
{
Trace.WriteLine("Specifying an initial path is only supported on Android 26 and later.");
}
Folder? folder = null;
if (Android.OS.Environment.ExternalStorageDirectory is not null)
{
initialPath = initialPath.Replace(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, string.Empty, StringComparison.InvariantCulture);
}
var initialFolderUri = AndroidUri.Parse(AndroidStorageConstants.ExternalStorageBaseUrl + HttpUtility.UrlEncode(initialPath));
var intent = new Intent(Intent.ActionOpenDocumentTree);
intent.PutExtra(DocumentsContract.ExtraInitialUri, initialFolderUri);
await IntermediateActivity.StartAsync(intent, (int)AndroidRequestCode.RequestCodeFolderPicker, onResult: OnResult).WaitAsync(cancellationToken);
return folder ?? throw new FolderPickerException("Unable to get folder.");
void OnResult(Intent resultIntent)
{
var path = EnsurePhysicalPath(resultIntent.Data);
folder = new Folder(path, Path.GetFileName(path));
}
}
static Task<Folder> InternalPickAsync(CancellationToken cancellationToken)
{
return InternalPickAsync(AndroidPathExtensions.GetExternalDirectory(), cancellationToken);
}
static string EnsurePhysicalPath(AndroidUri? uri)
{
if (uri is null)
{
throw new FolderPickerException("Path is not selected.");
}
return uri.ToPhysicalPath() ?? throw new FolderPickerException($"Unable to resolve absolute path or retrieve contents of URI '{uri}'.");
}
}