static Task <ScreenshotResult> PlatformCaptureAsync() { if (Platform.WindowManager?.DefaultDisplay?.Flags.HasFlag(DisplayFlags.Secure) == true) { throw new UnauthorizedAccessException("Unable to take a screenshot of a secure window."); } var view = Platform.GetCurrentActivity(true)?.Window?.DecorView?.RootView; if (view == null) { throw new NullReferenceException("Unable to find the main window."); } var bitmap = Bitmap.CreateBitmap(view.Width, view.Height, Bitmap.Config.Argb8888); using (var canvas = new Canvas(bitmap)) { var drawable = view.Background; if (drawable != null) { drawable.Draw(canvas); } else { canvas.DrawColor(Color.White); } view.Draw(canvas); } var result = new ScreenshotResult(bitmap); return(Task.FromResult(result)); }
static async Task <FileResult> PlatformCaptureAsync(MediaPickerOptions options, bool photo) { await Permissions.EnsureGrantedAsync <Permissions.Camera>(); await Permissions.EnsureGrantedAsync <Permissions.StorageWrite>(); var capturePhotoIntent = new Intent(photo ? MediaStore.ActionImageCapture : MediaStore.ActionVideoCapture); if (capturePhotoIntent.ResolveActivity(Platform.AppContext.PackageManager) != null) { try { var activity = Platform.GetCurrentActivity(true); var storageDir = Platform.AppContext.ExternalCacheDir; var tmpFile = Java.IO.File.CreateTempFile(Guid.NewGuid().ToString(), photo ? ".jpg" : ".mp4", storageDir); tmpFile.DeleteOnExit(); capturePhotoIntent.AddFlags(ActivityFlags.GrantReadUriPermission); capturePhotoIntent.AddFlags(ActivityFlags.GrantWriteUriPermission); var result = await IntermediateActivity.StartAsync(capturePhotoIntent, Platform.requestCodeMediaCapture, tmpFile); var outputUri = result.GetParcelableExtra(IntermediateActivity.OutputUriExtra) as global::Android.Net.Uri; return(new FileResult(outputUri)); } catch (OperationCanceledException) { return(null); } } return(null); }
static Task <bool> PlatformOpenAsync(Uri uri, BrowserLaunchOptions options) { var nativeUri = AndroidUri.Parse(uri.AbsoluteUri); switch (options.LaunchMode) { case BrowserLaunchMode.SystemPreferred: var tabsBuilder = new CustomTabsIntent.Builder(); tabsBuilder.SetShowTitle(true); if (options.PreferredToolbarColor.HasValue) { tabsBuilder.SetToolbarColor(options.PreferredToolbarColor.Value.ToInt()); } if (options.TitleMode != BrowserTitleMode.Default) { tabsBuilder.SetShowTitle(options.TitleMode == BrowserTitleMode.Show); } var tabsIntent = tabsBuilder.Build(); var flags = ActivityFlags.ClearTop | ActivityFlags.NewTask; #if __ANDROID_24__ if (Platform.HasApiLevelN) { flags |= ActivityFlags.LaunchAdjacent; } #endif tabsIntent.Intent.SetFlags(flags); #if __ANDROID_25__ tabsIntent.LaunchUrl(Platform.AppContext, nativeUri); #else tabsIntent.LaunchUrl(Platform.GetCurrentActivity(true), nativeUri); #endif break; case BrowserLaunchMode.External: var intent = new Intent(Intent.ActionView, nativeUri); flags = ActivityFlags.ClearTop | ActivityFlags.NewTask; #if __ANDROID_24__ if (Platform.HasApiLevelN) { flags |= ActivityFlags.LaunchAdjacent; } #endif intent.SetFlags(flags); if (!Platform.IsIntentSupported(intent)) { throw new FeatureNotSupportedException(); } Platform.AppContext.StartActivity(intent); break; } return(Task.FromResult(true)); }
static async Task <FileResult> PlatformCaptureAsync(MediaPickerOptions options, bool photo) { await Permissions.EnsureGrantedAsync <Permissions.Camera>(); await Permissions.EnsureGrantedAsync <Permissions.StorageWrite>(); var capturePhotoIntent = new Intent(photo ? MediaStore.ActionImageCapture : MediaStore.ActionVideoCapture); if (!Platform.IsIntentSupported(capturePhotoIntent)) { throw new FeatureNotSupportedException($"Either there was no camera on the device or '{capturePhotoIntent.Action}' was not added to the <queries> element in the app's manifest file. See more: https://developer.android.com/about/versions/11/privacy/package-visibility"); } capturePhotoIntent.AddFlags(ActivityFlags.GrantReadUriPermission); capturePhotoIntent.AddFlags(ActivityFlags.GrantWriteUriPermission); try { var activity = Platform.GetCurrentActivity(true); // Create the temporary file var ext = photo ? FileSystem.Extensions.Jpg : FileSystem.Extensions.Mp4; var fileName = Guid.NewGuid().ToString("N") + ext; var tmpFile = FileSystem.GetEssentialsTemporaryFile(Platform.AppContext.CacheDir, fileName); // Set up the content:// uri AndroidUri outputUri = null; void OnCreate(Intent intent) { // Android requires that using a file provider to get a content:// uri for a file to be called // from within the context of the actual activity which may share that uri with another intent // it launches. outputUri ??= FileProvider.GetUriForFile(tmpFile); intent.PutExtra(MediaStore.ExtraOutput, outputUri); } // Start the capture process await IntermediateActivity.StartAsync(capturePhotoIntent, Platform.requestCodeMediaCapture, OnCreate); // Return the file that we just captured return(new FileResult(tmpFile.AbsolutePath)); } catch (OperationCanceledException) { return(null); } }
static void PlatformOpenSettings() { var context = Platform.GetCurrentActivity(false) ?? Platform.AppContext; var settingsIntent = new Intent(); settingsIntent.SetAction(global::Android.Provider.Settings.ActionApplicationDetailsSettings); settingsIntent.AddCategory(Intent.CategoryDefault); settingsIntent.SetData(global::Android.Net.Uri.Parse("package:" + PlatformGetPackageName())); settingsIntent.AddFlags(ActivityFlags.NewTask); settingsIntent.AddFlags(ActivityFlags.NoHistory); settingsIntent.AddFlags(ActivityFlags.ExcludeFromRecents); context.StartActivity(settingsIntent); }
public override bool ShouldShowRationale() { if (RequiredPermissions == null || RequiredPermissions.Length <= 0) { return(false); } var activity = Platform.GetCurrentActivity(true); foreach (var(androidPermission, isRuntime) in RequiredPermissions) { if (isRuntime && ActivityCompat.ShouldShowRequestPermissionRationale(activity, androidPermission)) { return(true); } } return(false); }
static void PlatformShowSettingsUI() { var context = Platform.GetCurrentActivity(false) ?? Platform.AppContext; var settingsIntent = new Intent(); settingsIntent.SetAction(global::Android.Provider.Settings.ActionApplicationDetailsSettings); settingsIntent.AddCategory(Intent.CategoryDefault); settingsIntent.SetData(global::Android.Net.Uri.Parse("package:" + PlatformGetPackageName())); var flags = ActivityFlags.NewTask | ActivityFlags.NoHistory | ActivityFlags.ExcludeFromRecents; #if __ANDROID_24__ if (Platform.HasApiLevelN) { flags |= ActivityFlags.LaunchAdjacent; } #endif settingsIntent.SetFlags(flags); context.StartActivity(settingsIntent); }
static async Task <bool> StartCustomTabsActivity(Uri url) { // Is only set to true if BindServiceAsync succeeds and no exceptions are thrown var success = false; var parentActivity = Platform.GetCurrentActivity(true); var customTabsActivityManager = CustomTabsActivityManager.From(parentActivity); try { if (await BindServiceAsync(customTabsActivityManager)) { var customTabsIntent = new CustomTabsIntent.Builder(customTabsActivityManager.Session) .SetShowTitle(true) .Build(); customTabsIntent.Intent.SetData(global::Android.Net.Uri.Parse(url.OriginalString)); if (customTabsIntent.Intent.ResolveActivity(parentActivity.PackageManager) != null) { WebAuthenticatorIntermediateActivity.StartActivity(parentActivity, customTabsIntent.Intent); success = true; } } } finally { try { customTabsActivityManager.Client?.Dispose(); } finally { } } return(success); }
protected virtual async Task <PermissionResult> DoRequest(string[] permissions) { TaskCompletionSource <PermissionResult> tcs; lock (locker) { tcs = new TaskCompletionSource <PermissionResult>(); requestCode = Platform.NextRequestCode(); requests.Add(requestCode, tcs); } if (!MainThread.IsMainThread) { throw new PermissionException("Permission request must be invoked on main thread."); } ActivityCompat.RequestPermissions(Platform.GetCurrentActivity(true), permissions.ToArray(), requestCode); var result = await tcs.Task; return(result); }
static Task <bool> PlatformOpenAsync(Uri uri, BrowserLaunchOptions options) { var nativeUri = AndroidUri.Parse(uri.AbsoluteUri); switch (options.LaunchMode) { case BrowserLaunchMode.SystemPreferred: var tabsBuilder = new CustomTabsIntent.Builder(); tabsBuilder.SetShowTitle(true); if (options.PreferredToolbarColor.HasValue) #pragma warning disable CS0618 // Type or member is obsolete { tabsBuilder.SetToolbarColor(options.PreferredToolbarColor.Value.ToInt()); } #pragma warning restore CS0618 // Type or member is obsolete if (options.TitleMode != BrowserTitleMode.Default) { tabsBuilder.SetShowTitle(options.TitleMode == BrowserTitleMode.Show); } var tabsIntent = tabsBuilder.Build(); ActivityFlags?tabsFlags = null; Context context = Platform.GetCurrentActivity(false); if (context == null) { context = Platform.AppContext; // If using ApplicationContext we need to set ClearTop/NewTask (See #225) tabsFlags = ActivityFlags.ClearTop | ActivityFlags.NewTask; } #if __ANDROID_24__ if (Platform.HasApiLevelN && options.HasFlag(BrowserLaunchFlags.LaunchAdjacent)) { if (tabsFlags.HasValue) { tabsFlags |= ActivityFlags.LaunchAdjacent | ActivityFlags.NewTask; } else { tabsFlags = ActivityFlags.LaunchAdjacent | ActivityFlags.NewTask; } } #endif // Check if there's flags specified to use if (tabsFlags.HasValue) { tabsIntent.Intent.SetFlags(tabsFlags.Value); } tabsIntent.LaunchUrl(context, nativeUri); break; case BrowserLaunchMode.External: var intent = new Intent(Intent.ActionView, nativeUri); var flags = ActivityFlags.ClearTop | ActivityFlags.NewTask; #if __ANDROID_24__ if (Platform.HasApiLevelN && options.HasFlag(BrowserLaunchFlags.LaunchAdjacent)) { flags |= ActivityFlags.LaunchAdjacent; } #endif intent.SetFlags(flags); if (!Platform.IsIntentSupported(intent)) { throw new FeatureNotSupportedException(); } Platform.AppContext.StartActivity(intent); break; } return(Task.FromResult(true)); }
static async Task <WebAuthenticatorResult> PlatformAuthenticateAsync(WebAuthenticatorOptions webAuthenticatorOptions) { var url = webAuthenticatorOptions?.Url; var callbackUrl = webAuthenticatorOptions?.CallbackUrl; var packageName = Platform.AppContext.PackageName; // Create an intent to see if the app developer wired up the callback activity correctly var intent = new Intent(Intent.ActionView); intent.AddCategory(Intent.CategoryBrowsable); intent.AddCategory(Intent.CategoryDefault); intent.SetPackage(packageName); intent.SetData(global::Android.Net.Uri.Parse(callbackUrl.OriginalString)); // Try to find the activity for the callback intent if (!Platform.IsIntentSupported(intent, packageName)) { throw new InvalidOperationException($"You must subclass the `{nameof(WebAuthenticatorCallbackActivity)}` and create an IntentFilter for it which matches your `{nameof(callbackUrl)}`."); } // Cancel any previous task that's still pending if (tcsResponse?.Task != null && !tcsResponse.Task.IsCompleted) { tcsResponse.TrySetCanceled(); } tcsResponse = new TaskCompletionSource <WebAuthenticatorResult>(); currentRedirectUri = callbackUrl; var parentActivity = Platform.GetCurrentActivity(true); var customTabsActivityManager = CustomTabsActivityManager.From(parentActivity); try { if (await BindServiceAsync(customTabsActivityManager)) { var customTabsIntent = new CustomTabsIntent.Builder(customTabsActivityManager.Session) .SetShowTitle(true) .Build(); customTabsIntent.Intent.SetData(global::Android.Net.Uri.Parse(url.OriginalString)); WebAuthenticatorIntermediateActivity.StartActivity(parentActivity, customTabsIntent.Intent); } else { // Fall back to opening the system browser if necessary var browserIntent = new Intent(Intent.ActionView, global::Android.Net.Uri.Parse(url.OriginalString)); Platform.CurrentActivity.StartActivity(browserIntent); } return(await tcsResponse.Task); } finally { try { customTabsActivityManager.Client?.Dispose(); } finally { } } }
static Task <WebAuthenticatorResult> PlatformAuthenticateAsync(Uri url, Uri callbackUrl) { var packageName = Platform.AppContext.PackageName; // Create an intent to see if the app developer wired up the callback activity correctly var intent = new Intent(Intent.ActionView); intent.AddCategory(Intent.CategoryBrowsable); intent.AddCategory(Intent.CategoryDefault); intent.SetPackage(packageName); intent.SetData(global::Android.Net.Uri.Parse(callbackUrl.OriginalString)); // Try to find the activity for the callback intent var c = intent.ResolveActivity(Platform.AppContext.PackageManager); if (c == null || c.PackageName != packageName) { throw new InvalidOperationException($"You must subclass the `{nameof(WebAuthenticatorCallbackActivity)}` and create an IntentFilter for it which matches your `{nameof(callbackUrl)}`."); } // Cancel any previous task that's still pending if (tcsResponse?.Task != null && !tcsResponse.Task.IsCompleted) { tcsResponse.TrySetCanceled(); } tcsResponse = new TaskCompletionSource <WebAuthenticatorResult>(); tcsResponse.Task.ContinueWith(t => { // Cleanup when done if (CustomTabsActivityManager != null) { CustomTabsActivityManager.NavigationEvent -= CustomTabsActivityManager_NavigationEvent; CustomTabsActivityManager.CustomTabsServiceConnected -= CustomTabsActivityManager_CustomTabsServiceConnected; try { CustomTabsActivityManager?.Client?.Dispose(); } finally { CustomTabsActivityManager = null; } } }); uri = url; RedirectUri = callbackUrl; CustomTabsActivityManager = CustomTabsActivityManager.From(Platform.GetCurrentActivity(true)); CustomTabsActivityManager.NavigationEvent += CustomTabsActivityManager_NavigationEvent; CustomTabsActivityManager.CustomTabsServiceConnected += CustomTabsActivityManager_CustomTabsServiceConnected; if (!CustomTabsActivityManager.BindService()) { // Fall back to opening the system browser if necessary var browserIntent = new Intent(Intent.ActionView, global::Android.Net.Uri.Parse(url.OriginalString)); Platform.CurrentActivity.StartActivity(browserIntent); } return(WebAuthenticator.ResponseTask); }
static void PlatformRequestRelease() { var activity = Platform.GetCurrentActivity(true); activity.Window?.ClearFlags(WindowManagerFlags.KeepScreenOn); }