Example #1
0
        protected override void OnResume()
        {
            base.OnResume();

            if (!started)
            {
                started = true;
                var uri  = Android.Net.Uri.Parse(Intent.GetStringExtra(BrowserImpl.StartUrlKey));
                var name = CustomTabsHelper.GetPackageNameToUse(this);
                if (name != null)
                {
                    var manager = new CustomTabsActivityManager(this);
                    var intent  = new CustomTabsIntent.Builder(manager.Session).Build();
                    intent.Intent.SetPackage(name);
                    intent.Intent.AddFlags(ActivityFlags.NoHistory);
                    intent.LaunchUrl(this, uri);
                }
                else
                {
                    var intent = new Intent(Intent.ActionView, uri);
                    StartActivity(intent);
                }
                return;
            }

            started = false;
            Callbacks?.Invoke(Intent.DataString ?? BrowserImpl.UserCancelResponse);
            Finish();
        }
        public void LaunchNativeEmbeddedBrowser(string url)
        {
            // TODO: We need the current actiivty. Forms.Context is deprecated, but I had issues
            // trying to use Android.App.Appllication.Context when castign to Activity, sooo...?
            var activity = Forms.Context as Activity;

            if (activity == null)
            {
                return;
            }

            customTabs = new CustomTabsActivityManager(activity);
            customTabs.CustomTabsServiceConnected += (name, client) =>
            {
                // Add custom options here, such as Share
            };

            var mgr = new CustomTabsActivityManager(activity);

            mgr.CustomTabsServiceConnected += delegate {
                mgr.LaunchUrl(url);
            };

            mgr.BindService();
        }
Example #3
0
        public void LaunchNativeEmbeddedBrowser(string url)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            var activity = Forms.Context as Activity;
#pragma warning restore CS0618 // Type or member is obsolete

            if (activity == null)
            {
                return;
            }

            var mgr = new CustomTabsActivityManager(activity);

            mgr.CustomTabsServiceConnected += (name, client) =>
            {
                mgr.LaunchUrl(url);
            };

            if (!mgr.BindService())
            {
                var uri    = Android.Net.Uri.Parse(url);
                var intent = new Intent(Intent.ActionView, uri);
                activity.StartActivity(intent);
            }
        }
Example #4
0
        public Task <string> InvokeAsync(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentException("Missing url", nameof(url));
            }

            // Use a TCS to set the task result after the intent finishes
            var tcs = new TaskCompletionSource <string>();

            customTabs = new CustomTabsActivityManager(activity);
            var builder = new CustomTabsIntent.Builder(customTabs.Session)
                          .SetToolbarColor(Color.Argb(255, 52, 152, 219))
                          .SetShowTitle(true)
                          .EnableUrlBarHiding();
            var customTabsIntent = builder.Build();

            // Ensure the intent is not kept in the history stack, which ensures navigating away will close it
            customTabsIntent.Intent.AddFlags(ActivityFlags.NoHistory);

            //MainActivity.CustomUrlSchemeCallbackHandler = (response) =>
            //{
            //    activity.StartActivity(typeof(MainActivity));
            //    tcs.SetResult(response);
            //};

            // Launch
            customTabsIntent.LaunchUrl(activity, Android.Net.Uri.Parse(url));

            return(tcs.Task);
        }
Example #5
0
        internal CustomTabsManager(Activity activity, bool warmup = false)
        {
            this.activity = activity;
            this.fallback = new WebViewFallback();
            this.customTabsActivityManager = new CustomTabsActivityManager(activity);
            this.serviceConnected          = new ManualResetEvent(false);

            if (warmup)
            {
                this.customTabsActivityManager.Warmup();
            }

            var packageForCustomTabs = PackageManagerHelper.PackagesSupportingCustomTabs?.FirstOrDefault().Value;

            if (String.IsNullOrEmpty(packageForCustomTabs))
            {
                this.fallbackNeccessary = true;
            }
            else
            {
                this.customTabsActivityManager.CustomTabsServiceConnected += (name, client) =>
                {
                    this.serviceConnected.Set();
                };

                this.fallbackNeccessary = this.customTabsActivityManager.BindService(packageForCustomTabs);
            }
        }
Example #6
0
        public Task <InvokeResult> InvokeAsync(InvokeOptions options)
        {
            if (string.IsNullOrWhiteSpace(options.StartUrl))
            {
                throw new ArgumentException("Missing StartUrl", nameof(options));
            }

            if (string.IsNullOrWhiteSpace(options.EndUrl))
            {
                throw new ArgumentException("Missing EndUrl", nameof(options));
            }

            // must be able to wait for the intent to be finished to continue
            // with setting the task result
            var _tcs = new TaskCompletionSource <InvokeResult>();

            // create & open chrome custom tab
            _customTabs = new CustomTabsActivityManager(_context);

            // build custom tab
            var builder = new CustomTabsIntent.Builder(_customTabs.Session)
                          .SetToolbarColor(Color.Argb(255, 52, 152, 219))
                          .SetShowTitle(true)
                          .EnableUrlBarHiding();

            var customTabsIntent = builder.Build();

            // ensures the intent is not kept in the history stack, which makes
            // sure navigating away from it will close it
            customTabsIntent.Intent.AddFlags(ActivityFlags.NoHistory);

            ActivityMediator.MessageReceivedEventHandler callback = null;
            callback = (response) =>
            {
                // remove handler
                AndroidClientChromeCustomTabsApplication
                .Mediator.ActivityMessageReceived -= callback;

                // set result
                _tcs.SetResult(new InvokeResult
                {
                    Response   = response,
                    ResultType = InvokeResultType.Success
                });

                // start MainActivity (will close the custom tab)
                _context.StartActivity(typeof(MainActivity));
            };

            // attach handler
            AndroidClientChromeCustomTabsApplication.Mediator.ActivityMessageReceived
                += callback;

            // launch
            customTabsIntent.LaunchUrl(_context, Android.Net.Uri.Parse(options.StartUrl));

            // need an intent to be triggered when browsing to the "io.identitymodel.native://callback"
            // scheme/URI => CallbackInterceptorActivity
            return(_tcs.Task);
        }
        private void LaunchCustomTabs(string url)
        {
            var packageName = CustomTabsHelper.GetPackageNameToUse(this);

            if (string.IsNullOrEmpty(packageName))
            {
                // in case custom tabs are not supported, use the browser

                StartActivity(new Intent(Intent.ActionView, Android.Net.Uri.Parse(url)));
            }
            else
            {
                // use custom tabs

                var mgr              = new CustomTabsActivityManager(this);
                var builder          = new CustomTabsIntent.Builder(mgr.Session);
                var customTabsIntent = builder
                                       .SetToolbarColor(new Color(0x34, 0x98, 0xDB))
                                       .SetShowTitle(true)
                                       .EnableUrlBarHiding()
                                       .Build();
                customTabsIntent.Intent.AddFlags(ActivityFlags.NoHistory);
                customTabsIntent.Intent.SetPackage(packageName);

                customTabsIntent.LaunchUrl(this, Android.Net.Uri.Parse(url));
            }
        }
        public static void Initialize(global::Android.App.Activity a)
        {
            activity = a;
            CustomTabsActivityManager = new CustomTabsActivityManager(a);
            CustomTabsIntentBuilder   = new CustomTabsIntent.Builder(CustomTabsActivityManager.Session);
            CustomTabActivityHelper   = new CustomTabActivityHelper();

            return;
        }
Example #9
0
        void UseCustomTabsActivityManagerOnly()
        {
            CustomTabsActivityManager mgr = new CustomTabsActivityManager(this);

            mgr.CustomTabsServiceConnected += delegate
            {
                mgr.LaunchUrl(url);
            };
            mgr.BindService();
        }
Example #10
0
        private void LoginActivity_Click(object sender, EventArgs e)
        {
            View dialogLayout = LayoutInflater.Inflate(Resource.Layout.DialogButtonsX2, null);
            var  termsButton  = dialogLayout.FindViewById <Button>(Resource.Id.dialogBtn1);

            termsButton.Text   = Resources.GetString(Resource.String.LoginOpenTerms);
            termsButton.Click += (args, o) =>
            {
                Intent browserIntent =
                    new Intent(Intent.ActionView, global::Android.Net.Uri.Parse(
                                   ConfidentialData.api + "terms"));
                StartActivity(browserIntent);
            };

            var privacyButton = dialogLayout.FindViewById <Button>(Resource.Id.dialogBtn2);

            privacyButton.Text   = Resources.GetString(Resource.String.LoginOpenPrivacy);
            privacyButton.Click += (args, o) =>
            {
                Intent browserIntent =
                    new Intent(Intent.ActionView, global::Android.Net.Uri.Parse(
                                   ConfidentialData.api + "privacypolicy"));
                StartActivity(browserIntent);
            };

            new global::Android.Support.V7.App.AlertDialog.Builder(this)
            .SetTitle(Resource.String.LoginTermsTitle)
            .SetMessage(Resource.String.LoginTerms)
            .SetView(dialogLayout)
            .SetNegativeButton(Resource.String.dialog_cancel, (a, args) => { })
            .SetPositiveButton(Resource.String.LoginAgreeTerms, (a, args) =>
            {
                string buttonText = ((Button)sender).Text;

                ExternalLogin chosen = providers.FirstOrDefault(prov => prov.Name == buttonText);

                if (chosen == null)
                {
                    return;
                }

                chromeManager = new CustomTabsActivityManager(this);

                // build custom tab
                var builder = new CustomTabsIntent.Builder(chromeManager.Session)
                              .SetShowTitle(true)
                              .EnableUrlBarHiding();

                var customTabsIntent = builder.Build();
                customTabsIntent.Intent.AddFlags(ActivityFlags.NoHistory);
                chromeManager.Warmup(0L);
                customTabsIntent.LaunchUrl(this, global::Android.Net.Uri.Parse(ConfidentialData.api + chosen.Url));
            })
            .Show();
        }
Example #11
0
    /// <summary>
    /// OpenBrowser
    /// </summary>
    /// <param name="url"></param>
    public static void OpenUrl(Activity activity, string url)
    {
        var builder = new CustomTabsIntent.Builder()
                      .SetToolbarColor(System.Drawing.Color.Black.ToArgb());
        var intent = builder.Build();
        var mgr    = new CustomTabsActivityManager(activity);

        mgr.CustomTabsServiceConnected += delegate {
            mgr.LaunchUrl(url, intent);
        };
        mgr.BindService();
    }
        protected override void OnAttachedToWindow()
        {
            base.OnAttachedToWindow();

            var mgr = new CustomTabsActivityManager(Context as Activity);

            mgr.CustomTabsServiceConnected += (name, client) =>
            {
                mgr.LaunchUrl(_loginUrl.AbsoluteUri);
            };

            mgr.BindService();
        }
Example #13
0
        //CustomTabsActivityManager customTabs;

        public void LaunchNativeEmbeddedBrowser(string url)
        {
            // TODO: We need the current actiivty. Forms.Context is deprecated, but I had issues
            // trying to use Android.App.Appllication.Context
            var activity = Forms.Context as Activity;

            if (activity == null)
            {
                return;
            }

            var mgr = new CustomTabsActivityManager(activity);

            mgr.CustomTabsServiceConnected += delegate {
                mgr.LaunchUrl(url);
            };

            mgr.BindService();
        }
Example #14
0
        public static void Initialize(global::Android.App.Activity a)
        {
            activity = a;

            List <string> packages = PackageManagerHelper.GetPackageNameToUse
                                     (
                global::Android.App.Application.Context,
                "http://xamarin.com"
                                     );

            PackagesSupportingCustomTabs = PackageManagerHelper.PackagesSupportingCustomTabs;
            PackageForCustomTabs         = PackagesSupportingCustomTabs.FirstOrDefault().Value;

            CustomTabsActivityManager = new CustomTabsActivityManager(a);
            CustomTabsIntentBuilder   = new CustomTabsIntent.Builder(CustomTabsActivityManager.Session);
            CustomTabActivityHelper   = new CustomTabActivityHelper();

            return;
        }
Example #15
0
        void BeginLoadingInitialUrl()
        {
            var initalUri = state.Authenticator.GetInitialUrlAsync().Result;
            var mgr       = new CustomTabsActivityManager(this);

            mgr.CustomTabsServiceConnected += delegate {
                var builder = new CustomTabsIntent.Builder(mgr.Session);
                builder.EnableUrlBarHiding();
                builder.SetStartAnimations(this, Resource.Animation.slide_in_right, Resource.Animation.slide_out_left);
                builder.SetExitAnimations(this, global::Android.Resource.Animation.SlideInLeft, global::Android.Resource.Animation.SlideOutRight);
                mgr.LaunchUrl(initalUri.AbsoluteUri, builder.Build());
            };
            if (!mgr.BindService())
            {
                var intent = new Intent(Intent.ActionView);
                intent.SetData(global::Android.Net.Uri.Parse(initalUri.AbsoluteUri));
                StartActivity(intent);
            }
        }
        static Task <bool> BindServiceAsync(CustomTabsActivityManager manager)
        {
            var tcs = new TaskCompletionSource <bool>();

            manager.CustomTabsServiceConnected += OnCustomTabsServiceConnected;

            if (!manager.BindService())
            {
                manager.CustomTabsServiceConnected -= OnCustomTabsServiceConnected;
                tcs.TrySetResult(false);
            }

            return(tcs.Task);

            void OnCustomTabsServiceConnected(ComponentName name, CustomTabsClient client)
            {
                manager.CustomTabsServiceConnected -= OnCustomTabsServiceConnected;
                tcs.TrySetResult(true);
            }
        }
Example #17
0
        /// <summary>
        /// Opens the URL on a Custom Tab if possible. Otherwise fallsback to opening it on a WebView.
        /// </summary>
        /// <param name="activity"> The host activity. </param>
        /// <param name="custom_tabs_intent"> a CustomTabsIntent to be used if Custom Tabs is available. </param>
        /// <param name="uri"> the Uri to be opened. </param>
        /// <param name="fallback"> a CustomTabFallback to be used if Custom Tabs is not available. </param>
        public /*static*/ void LaunchUrlWithCustomTabsOrFallback
        (
            Activity a,
            CustomTabsIntent custom_tabs_intent,
            Android.Net.Uri u,
            ICustomTabFallback fallback
        )
        {
            uri      = u;
            activity = a;
            string packageName = PackageManagerHelper.GetPackageNameToUse(activity, uri.ToString());

            //If we cant find a package name, it means theres no browser that supports
            //Chrome Custom Tabs installed. So, we fallback to the webview
            if (packageName == null)
            {
                if (fallback != null)
                {
                    fallback.OpenUri(activity, uri);
                }
            }
            else
            {
                custom_tabs_intent.Intent.SetPackage(packageName);

                // direct call to CustomtTasIntent.LaunchUrl was ported from java samples and refactored
                // seems like API changed
                //
                // custom_tabs_intent.LaunchUrl(activity, uri);
                custom_tabs_activit_manager = new CustomTabsActivityManager(activity);
                custom_tabs_activit_manager.CustomTabsServiceConnected += custom_tabs_activit_manager_CustomTabsServiceConnected;
                service_bound = custom_tabs_activit_manager.BindService();

                if (service_bound == false)
                {
                    // No Packages that support CustomTabs
                }
            }

            return;
        }
Example #18
0
        void UseCustomTabsActivityManagerWithIntent()
        {
            // create & open chrome custom tab
            CustomTabsActivityManager mgr = new CustomTabsActivityManager(this);

            // build custom tab
            CustomTabsIntent.Builder builder = null;
            builder = new CustomTabsIntent.Builder(mgr.Session)
                      .SetToolbarColor(Android.Graphics.Color.Argb(255, 52, 152, 219))
                      .SetShowTitle(true)
                      .EnableUrlBarHiding();

            CustomTabsIntent customTabsIntent = builder.Build();

            // ensures the intent is not kept in the history stack, which makes
            // sure navigating away from it will close it
            customTabsIntent.Intent.AddFlags(Android.Content.ActivityFlags.NoHistory);
            customTabsIntent.LaunchUrl(this, Android.Net.Uri.Parse(url));

            return;
        }
        private Task <WebAuthenticatorResult> AuthenticateAsync(Uri url, Uri callbackUrl)
        {
            if (_tcs?.Task != null && !_tcs.Task.IsCompleted)
            {
                _tcs.TrySetCanceled();
            }

            _tcs = new TaskCompletionSource <WebAuthenticatorResult>();
            _tcs.Task.ContinueWith(t =>
            {
                // Cleanup when done
                if (_customTabs != null)
                {
                    _customTabs.CustomTabsServiceConnected -= CustomTabsActivityManager_CustomTabsServiceConnected;

                    try
                    {
                        _customTabs?.Client?.Dispose();
                    }
                    finally
                    {
                        _customTabs = null;
                    }
                }
            });

            _uri = url;

            _customTabs = CustomTabsActivityManager.From(Platform.CurrentActivity);
            _customTabs.CustomTabsServiceConnected += CustomTabsActivityManager_CustomTabsServiceConnected;

            if (!_customTabs.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(_tcs.Task);
        }
        internal static Task <AuthResult> NavigateAsync(Uri navigateUri, Uri redirectUri, global::Android.App.Activity parentActivity)
        {
            isWaiting = true;

            tcsResponse    = new TaskCompletionSource <AuthResult>();
            uri            = navigateUri;
            ParentActivity = parentActivity;
            RedirectUri    = redirectUri;

            CustomTabsActivityManager = new CustomTabsActivityManager(ParentActivity);
            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("http://www.google.com"));
                parentActivity.StartActivity(browserIntent);
            }

            return(WebAuthenticator.ResponseTask);
        }
        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);
        }
        public void LaunchNativeEmbeddedBrowser(string url)
        {
            var activity = CrossCurrentActivity.Current.Activity;

            if (activity == null)
            {
                return;
            }

            var customTabsActivityManager = new CustomTabsActivityManager(activity);

            customTabsActivityManager.CustomTabsServiceConnected += (name, client) =>
            {
                customTabsActivityManager.LaunchUrl(url);
            };

            if (!customTabsActivityManager.BindService())
            {
                var uri    = Android.Net.Uri.Parse(url);
                var intent = new Intent(Intent.ActionView, uri);
                activity.StartActivity(intent);
            }
        }
        public static void Init(Activity activity)
        {
            if (isInitialised)
            {
                return;
            }

            OnLaunchRequested += (uri, accentColour) =>
            {
                var manager = CustomTabsActivityManager.From(activity);
                manager.CustomTabsServiceConnected += customTabServiceConnected;
                if (!manager.BindService())
                {
                    // Fall back to opening the system browser if necessary
                    var browserIntent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(uri));
                    activity.StartActivity(browserIntent);
                }

                void customTabServiceConnected(ComponentName name, CustomTabsClient client)
                {
                    manager.CustomTabsServiceConnected -= customTabServiceConnected;
                    var intent = new CustomTabsIntent.Builder()
                                 .SetDefaultColorSchemeParams(new CustomTabColorSchemeParams.Builder()
                                                              .SetToolbarColor(accentColour)
                                                              .SetNavigationBarColor(accentColour)
                                                              .Build())
                                 .Build();

                    intent.Intent.AddFlags(ActivityFlags.SingleTop | ActivityFlags.NoHistory | ActivityFlags.NewTask);
                    CustomTabsHelper.AddKeepAliveExtra(activity, intent.Intent);
                    intent.LaunchUrl(activity, Android.Net.Uri.Parse(uri));
                }
            };

            isInitialised = true;
        }
    }
Example #24
0
 protected override void OnDestroy()
 {
     chromeManager = null;
     UnregisterReceiver(receiver);
     base.OnDestroy();
 }
Example #25
0
 public ChromeCustomTabsBrowser(Activity context)
 {
     _context = context;
     _manager = new CustomTabsActivityManager(_context);
 }
        /// <summary>
        /// Opens the URL on a Custom Tab if possible. Otherwise fallsback to opening it on a WebView.
        /// </summary>
        /// <param name="activity"> The host activity. </param>
        /// <param name="custom_tabs_intent"> a CustomTabsIntent to be used if Custom Tabs is available. </param>
        /// <param name="uri"> the Uri to be opened. </param>
        /// <param name="fallback"> a CustomTabFallback to be used if Custom Tabs is not available. </param>
        public /*static*/ void LaunchUrlWithCustomTabsOrFallback
        (
            Activity a,
            CustomTabsIntent custom_tabs_intent,
            string package_name_for_custom_tabs,
            Android.Net.Uri u,
            ICustomTabFallback fallback
        )
        {
            uri      = u;
            activity = a;
            bool fallback_neccessary = false;

            //If we cant find a package name, it means theres no browser that supports
            //Chrome Custom Tabs installed. So, we fallback to the webview
            if (package_name_for_custom_tabs == null)
            {
                fallback_neccessary = true;
            }
            else
            {
                custom_tabs_activity_manager = new CustomTabsActivityManager(this.activity);

                custom_tabs_activity_manager.BindService(package_name_for_custom_tabs);
                //custom_tabs_intent.Intent.SetPackage(package_name_for_custom_tabs);

                custom_tabs_session = custom_tabs_activity_manager.Session;

                custom_tabs_intent_builder = new CustomTabsIntent.Builder(custom_tabs_session);


                // direct call to CustomtTasIntent.LaunchUrl was ported from java samples and refactored
                // seems like API changed
                //------------------------------------------------------------------------------
                //custom_tabs_intent.LaunchUrl(activity, uri);
                //return;
                //------------------------------------------------------------------------------
                custom_tabs_activity_manager = new CustomTabsActivityManager(activity);
                custom_tabs_intent           = custom_tabs_intent_builder.Build();

                CustomTabsHelper.AddKeepAliveExtra(activity, custom_tabs_intent.Intent);

                custom_tabs_intent.LaunchUrl(activity, uri);
                custom_tabs_activity_manager.CustomTabsServiceConnected +=
                    // custom_tabs_activit_manager_CustomTabsServiceConnected
                    delegate
                {
                    System.Diagnostics.Debug.WriteLine("CustomTabsActivityManager.CustomTabsServiceConnected");

                    custom_tabs_activity_manager.LaunchUrl(uri.ToString());

                    System.Diagnostics.Debug.WriteLine("CustomTabsActivityManager.LaunchUrl");

                    return;
                }
                ;
                System.Diagnostics.Debug.WriteLine($"CustomTabsActivityManager.BindService({package_name_for_custom_tabs})");
                service_bound = custom_tabs_activity_manager.BindService(package_name_for_custom_tabs);
                //custom_tabs_activity_manager.LaunchUrl(uri.ToString());
                //------------------------------------------------------------------------------

                if (service_bound == false)
                {
                    System.Diagnostics.Debug.WriteLine($"FALLBACK: No Packages that support CustomTabs");
                    // No Packages that support CustomTabs
                    fallback_neccessary = true;
                }
            }

            if (fallback_neccessary == true && fallback != null)
            {
                fallback.OpenUri(activity, uri);
            }

            return;
        }
Example #27
0
        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);
        }
 public ChromeCustomTabsBrowser(Activity context)
 {
     this.context = context;
     manager      = new CustomTabsActivityManager(this.context);
 }
Example #29
0
 public ChromeCustomTabBrowser(Activity context)
 {
     this.context = context;
     manager      = new CustomTabsActivityManager(context);
     //manager = CustomTabsActivityManager.From(context);
 }
Example #30
0
        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
                {
                }
            }
        }