Deep linking Using Rivets with Xamarins.Forms - xamarin

So when a user in my site request a new password I'm sending a link to his email address that leads to my site where I've this headers. My mobile app should open then.
I installed through NuGet the Rivets package in my Android Xamarin project.
This is my MainActivity.cs code:
using System;
using Android.App;
using Android.Content.PM;
using Android.OS;
using TinyIoC;
using XLabs.Forms;
using XLabs.Ioc;
using XLabs.Platform.Device;
using Android.Content;
using Android.Preferences;
using XLabs.Platform.Services;
using XLabs.Platform.Services.Media;
namespace HalliganTL.Droid
{
[Activity(Label = "Halligan",
Icon = "#drawable/icon",
MainLauncher = true,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[IntentFilter(new[] { Android.Content.Intent.ActionView },
DataScheme = "halligan",
DataHost = "resetpassword",
Categories = new[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable })]
public class MainActivity : XFormsApplicationDroid, IDeviceStorage
{
#region IDeviceStorage implementation
public string LoadString(string key, string def = null)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
return prefs.GetString(key, def);
}
public void SaveString(string key, string value)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString(key, value);
editor.Apply();
}
#endregion
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
if (!Resolver.IsSet) SetIoc();
//We're gonna check if we opened the app from a web link
var resetPasswordToken = string.Empty;
Rivets.AppLinkUrl alUrl = null;
// Parse our AppLinkUrl from the Intent Data Uri
if (Intent.Data != null)
{
alUrl = new Rivets.AppLinkUrl(Intent.Data.ToString());
}
if (alUrl != null && alUrl.TargetQueryParameters.ContainsKey("token"))
resetPasswordToken = alUrl.TargetQueryParameters["token"];
if (string.IsNullOrEmpty(resetPasswordToken))
{
LoadApplication(new App());
}
else
{
LoadApplication(new App(resetPasswordToken));
}
}
private void SetIoc()
{
var container = TinyIoCContainer.Current;
container.Register<IDeviceStorage>(this);
container.Register<IDevice>(AndroidDevice.CurrentDevice);
container.Register<IMediaPicker, MediaPicker>();
container.Register<ISecureStorage>(new KeyVaultStorage(container.Resolve<IDevice>().Id.ToCharArray()));
Resolver.SetResolver(new XLabs.Ioc.TinyIOC.TinyResolver(container));
}
}
}
And well nothing is happening.
BTW I'm using the Rivets 1.0.2 version because the newer ones thrown an "assembly references error" saying that my project which has "MonoAndroid, Version=v6.0"
Any tip would be useful,

Related

How can I enable video autoplay in WKWebView on iOS

I have a WebView that contains an iframe (an HTML element). this iframe has a Peertube video plyaer, I pass &autoplay=1 to that iframe and it works good on android, iPad and browser, but on iPhone the video can not be autoplayed.
I tried custom render with WKWebView with this code:
class FullScreenEnabledWebViewRenderer : WkWebViewRenderer
{
WKUserContentController userController;
public FullScreenEnabledWebViewRenderer() : this(new WKWebViewConfiguration() { MediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypes.None, AllowsInlineMediaPlayback = true, MediaPlaybackRequiresUserAction = false, RequiresUserActionForMediaPlayback = false })
{
}
public FullScreenEnabledWebViewRenderer(WKWebViewConfiguration config) : base(config)
{
config.AllowsInlineMediaPlayback = true;
config.AllowsAirPlayForMediaPlayback = true;
config.AllowsPictureInPictureMediaPlayback = true;
config.MediaPlaybackAllowsAirPlay = true;
config.MediaPlaybackRequiresUserAction = false;
config.RequiresUserActionForMediaPlayback = false;
config.MediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypes.None;
}
}
and still does not work.
Can you help me with that please.
Webview in iOS couldn't support iframe very well . So it could better to use <video> like
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = #"<html><body><video width='300' height='500' muted='muted' controls autoplay='autoplay'><source src='https://ia800201.us.archive.org/12/items/BigBuckBunny_328/BigBuckBunny_512kb.mp4' type='video/mp4'></video></body></html>";
webview.Source = htmlSource;
If it still could not auto play in iOS , we could invoked JS to play it .
using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using App4;
using App4.iOS;
using WebKit;
using ObjCRuntime;
[assembly: ExportRenderer(typeof(WebView), typeof(FullScreenEnabledWebViewRenderer))]
namespace App4.iOS
{
public class FullScreenEnabledWebViewRenderer: ViewRenderer<WebView, WKWebView>
{
WKWebView wkWebView;
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var config = new WKWebViewConfiguration();
config.AllowsInlineMediaPlayback = true;
config.AllowsAirPlayForMediaPlayback = true;
config.AllowsPictureInPictureMediaPlayback = true;
config.MediaPlaybackAllowsAirPlay = true;
config.MediaPlaybackRequiresUserAction = false;
config.RequiresUserActionForMediaPlayback = false;
config.MediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypes.None;
wkWebView = new WKWebView(Frame, config);
wkWebView.NavigationDelegate = new WkWebviewPolicy();
SetNativeControl(wkWebView);
}
}
}
public class WkWebviewPolicy : WKNavigationDelegate
{
public override void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, WKWebpagePreferences preferences, [BlockProxy(typeof(NIDActionArity2V120))] Action<WKNavigationActionPolicy, WKWebpagePreferences> decisionHandler)
{
decisionHandler.Invoke(WKNavigationActionPolicy.Allow, preferences);
//base.DecidePolicy(webView, navigationAction, preferences, decisionHandler);
}
public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
base.DidFinishNavigation(webView, navigation);
var JSstr = #"var videos = document.querySelectorAll('video'); for (var i = videos.length - 1; i >= 0; i--) { var ivideo = videos[i]; ivideo.setAttribute('webkit-playsinline','\'); ivideo.play(); };";
webView.EvaluateJavaScript(JSstr,null);
}
}
}

Display SplashScreen during webview loading

I'm building a Xamarin app that display a webview; currenlty I have my splash screen displayed when the application starts using the code on MainActivity.cs:
[Activity(Label = "App.Xamarin",
Icon = "#mipmap/icon",
Theme = "#style/Theme.Splash",
MainLauncher = true,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
Now I need to display the same splash in my webviewrenderer when the webvieb starts/stop to load its content, so I have my own WebViewClient:
internal class CusViewClient : WebViewClient
{
string _javascript;
public SistemiWebViewClient(string javascript)
{
_javascript = javascript;
}
public override void OnPageStarted(Android.Webkit.WebView view, string url, Android.Graphics.Bitmap favicon)
{
base.OnPageStarted(view, url, favicon);
view.Visibility = ViewStates.Invisible;
}
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
base.OnPageFinished(view, url);
view.EvaluateJavascript(_javascript, null);
view.Visibility = ViewStates.Visible;
}
}
but I can't find the correct way to display the splash.
I ended up using a progress-bar instead of splash screen image to display the progress loading of the page in the chrome client, the code is the following:
public class CusWebChromeClient : WebChromeClient
{
Android.Widget.ProgressBar progressBar;
public SistemiWebChromeClient(Android.Widget.ProgressBar progressBar)
{
this.progressBar = progressBar;
}
public override void OnProgressChanged(Android.Webkit.WebView view, int newProgress)
{
if (newProgress < 100 && progressBar.Visibility == ViewStates.Gone)
{
progressBar.Visibility = ViewStates.Visible;
}
progressBar.SetProgress(newProgress, true);
if (newProgress == 100)
{
progressBar.Visibility = ViewStates.Gone;
}
}
}

Scanner is null and not accessible

I am attempting to read a QRCode in Xamarin.Forms. I have a shared project in XF. I have added the nuget packages for ZXing.Net. Everything works in the iOS project. I am getting an error in the Android project. The errors that I get via Android SDK Monitor, it indicates that there is a problem with the scanner being null and not being accessible. I am guessing that there is something that I have not set up correct on the Android side. Does anyone see anything improper in my code? Thanks for your time.
ScanPage class:
public class ScanPage : ContentPage
{
ZXing.Net.Mobile.Forms.ZXingScannerView zxing;
ZXingDefaultOverlay overlay;
bool isConnected = false;
string basicUrl = "golfeventscores.azurewebsites.net";
public ScanPage ()
{
zxing = new ZXing.Net.Mobile.Forms.ZXingScannerView
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
AutomationId = "zxingScannerView",
};
zxing.OnScanResult += async (ZXing.Result result) => {
zxing.IsAnalyzing = false;
zxing.IsScanning = false;
var teamToken = result.Text;
//MessagingCenter.Send<string>(teamToken, "SelectTeamMembers");
isConnected = await Plugin.Connectivity.CrossConnectivity.Current.IsRemoteReachable(basicUrl);
if (isConnected)
{
await GetTeamData(teamToken);
}
else
{
await DisplayAlert("Connectivity", "There is a problem with internet connectivity. Please try and reload this screen.", "Ok");
}
};
overlay = new ZXingDefaultOverlay
{
TopText = "Hold your phone up to the barcode",
BottomText = "Scanning will happen automatically",
ShowFlashButton = zxing.HasTorch,
AutomationId = "zxingDefaultOverlay",
};
overlay.FlashButtonClicked += (sender, e) => {
zxing.IsTorchOn = !zxing.IsTorchOn;
};
var grid = new Grid
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
};
grid.Children.Add(zxing);
grid.Children.Add(overlay);
// The root page of your application
Content = grid;
}
protected override void OnAppearing()
{
base.OnAppearing();
zxing.IsScanning = true;
}
protected override void OnDisappearing()
{
zxing.IsScanning = false;
base.OnDisappearing();
}
async System.Threading.Tasks.Task GetTeamData(string Token)
{
try
{
var scanResult = await WebServices.ws.TokenLookup(Token);
if (scanResult.Result == true)
{
if (scanResult.IsScoreBoard == true)
{
var uri = new System.Uri(scanResult.ScoreboardUrl);
Device.BeginInvokeOnMainThread(() =>
{
Device.OpenUri(uri);
Navigation.PopToRootAsync();
});
}
if (scanResult.IsCharity == true)
{
if (scanResult.TeamPlayers.Count > 0)
{
var player = scanResult.TeamPlayers.First();
var playerId = player.PlayerTeamId;
var urlResult = await WebServices.ws.ServerUrl(Token, playerId);
if (urlResult.ValidRequest && (!String.IsNullOrEmpty(urlResult.Url)))
{
var uri = new System.Uri(urlResult.Url);
Device.OpenUri(uri);
await Navigation.PopToRootAsync();
}
}
else{
await DisplayAlert("Scanning", "There was a problem downloading the Charity Team Info.", "OK");
}
}
else
{
if (scanResult.IsLargeGame != true)
{
var select = new Pages.SelectTeamMembers(Token);
await Navigation.PushAsync(select);
}
else
{
await DisplayAlert("Large Game", "Don't have the large team game setup with scanning.", "Ok");
}
}
}
else
{
await DisplayAlert("Server Problem", "There was some type of server error. Please try again or call Wally.", "Ok");
}
}
catch(System.Exception sysExc)
{
//nothing seems to be caught
}
}
}
MainActivity.cs contents:
[Activity (Label = "TD Scan", Icon = "#drawable/icon", Theme="#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate (Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
ZXing.Net.Mobile.Forms.Android.Platform.Init();
LoadApplication (new GolfGameScanApp.App ());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Have you defined all in Android Project?
Xamarin Forms
For Xamarin Forms there is a bit more setup needed. You will need to initialize the library on each platform in your platform specific app project.
Android
On Android, in your main Activity's OnCreate (..) implementation, call:
ZXing.Net.Mobile.Forms.Android.Platform.Init();
ZXing.Net.Mobile for Xamarin.Forms also handles the new Android permission request model for you, but you will need to add the following override implementation to your main Activity as well:
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
global::ZXing.Net.Mobile.Forms.Android.PermissionsHandler.OnRequestPermissionsResult (requestCode, permissions, grantResults);
}
The Camera permission should be automatically included for you in the AndroidManifest.xml however if you would like to use the Torch API's you will still need to add the Flashlight permission yourself. You can do this by using the following assembly level attribute:
[assembly: UsesPermission (Android.Manifest.Permission.Flashlight)]

System.NullReferenceException at start Xamarin Droid App

I am developing an application with MVVM Cross, Mvvm Cross Forms, Xamarin Forms and Grail KIT. In IOS it works perfectly. But when I start it on Android I get an error without trace and I do not know how to solve it.
After the OnStart method is executed. This exception occurs:
The step-by-step execution of the debugger does not allow me to go beyond this method.
This is the code of the MvxFormsApplication.
public partial class App : MvxFormsApplication
{
private void ConfigLocale()
{
if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android )
{
Debug.WriteLine("Get Culture Info ...");
var ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo();
Debug.WriteLine(ci.ToString());
AppResources.Culture = ci; // set the RESX for resource localization
DependencyService.Get<ILocalize>().SetLocale(ci); // set the Thread for locale-aware methods
}
}
public App()
{
ConfigLocale();
InitializeComponent();
}
void OnAuthenticatedUserMessage(AuthenticatedUserMessage authenticatedUserMessage)
{
Debug.WriteLine("OnAuthenticatedUserMessage ...");
var deviceGroupsService = Mvx.Resolve<IDeviceGroupsService>();
// save token
deviceGroupsService.saveDevice(CrossDeviceInfo.Current.Id, Settings.FcmToken).Subscribe(device => {
Debug.WriteLine(String.Format("Device Saved: {0}", device.ToString()));
});
}
void OnExceptionOcurredMessage(ExceptionOcurredMessage exceptionOcurredMessage)
{
Debug.WriteLine("OnExceptionOcurredMessage ...");
var userDialogs = Mvx.Resolve<IUserDialogs>();
userDialogs.ShowError(AppResources.Global_ErrorOcurred);
if (exceptionOcurredMessage.Ex != null)
exceptionOcurredMessage.Ex.Track();
}
protected override void OnStart()
{
Debug.WriteLine("Forms App OnStart ...");
var messenger = Mvx.Resolve<IMvxMessenger>();
// subscribe to Authenticated User Message
messenger.Subscribe<AuthenticatedUserMessage>(OnAuthenticatedUserMessage);
// subscribe to Exception Ocurred Message
messenger.Subscribe<ExceptionOcurredMessage>(OnExceptionOcurredMessage);
//Handling FCM Token
CrossFirebasePushNotification.Current.OnTokenRefresh += (s, p) =>
{
Debug.WriteLine($"TOKEN REC: {p.Token}");
Settings.FcmToken = p.Token;
};
Debug.WriteLine($"TOKEN: {CrossFirebasePushNotification.Current.Token}");
Settings.FcmToken = CrossFirebasePushNotification.Current.Token;
}
}
}
The application starts with a SplashScreen that I expose below:
using System;
using Android.App;
using Android.Content.PM;
using MvvmCross.Droid.Views;
using MvvmCross.Forms.Droid;
using Xamarin.Forms;
namespace Bullytect.Droid
{
[Activity(
Name = "com.usal.bisite.bulltect.SplashScreen",
Label = "Bulltect"
, MainLauncher = true
, Icon = "#mipmap/ic_launcher"
, Theme = "#style/Theme.Splash"
, NoHistory = true
, ScreenOrientation = ScreenOrientation.Portrait)]
public class SplashScreen : MvxSplashScreenActivity
{
public override void InitializationComplete()
{
StartActivity(typeof(MvxFormsApplicationActivity));
}
protected override void OnCreate(Android.OS.Bundle bundle)
{
Forms.Init(this, bundle);
// Leverage controls' StyleId attrib. to Xamarin.UITest
Forms.ViewInitialized += (object sender, ViewInitializedEventArgs e) => {
if (!string.IsNullOrWhiteSpace(e.View.StyleId))
{
e.NativeView.ContentDescription = e.View.StyleId;
}
};
base.OnCreate(bundle);
}
}
}
The Activity MvxFormsApplicationActivity is then executed by the Application Application
namespace Bullytect.Droid
{
[Activity(
Name = "com.usal.bisite.bulltect.MvxFormsApplicationActivity",
Label = "bulltect",
Icon = "#mipmap/ic_launcher",
Theme = "#style/AppTheme",
MainLauncher = false,
LaunchMode = LaunchMode.SingleTask,
ScreenOrientation = ScreenOrientation.Portrait
)]
public class MvxFormsApplicationActivity : FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
try
{
ToolbarResource = Resource.Layout.Toolbar;
TabLayoutResource = Resource.Layout.Tabs;
base.OnCreate(bundle);
Forms.Init(this, bundle);
PullToRefreshLayoutRenderer.Init();
XFGloss.Droid.Library.Init(this, bundle);
//Initializing FFImageLoading
CachedImageRenderer.Init();
UserDialogs.Init(this);
GrialKit.Init(this, "Bullytect.Droid.GrialLicense");
FormsHelper.ForceLoadingAssemblyContainingType(typeof(UXDivers.Effects.Effects));
var formsPresenter = (MvxFormsPagePresenter)Mvx.Resolve<IMvxAndroidViewPresenter>();
LoadApplication(formsPresenter.FormsApplication);
//FirebasePushNotificationManager.ProcessIntent(Intent);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("**BullTect LAUNCH EXCEPTION**\n\n" + e);
}
}
public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig)
{
base.OnConfigurationChanged(newConfig);
DeviceOrientationLocator.NotifyOrientationChanged();
}
}
}
These are all the packages I have installed:
Hope someone can help me.

Xamarin Android: When I open my application by notification splash-screen doesn't work

If I open the application by clicking on the notification (got from Google Cloud Messaging), I doesn't get splash-screen
GcmListenerService.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Gms.Gcm;
using Android.Util;
using System;
using Android.Database.Sqlite;
namespace Dharma.Droid
{
[Service (Exported = false), IntentFilter (new [] { "com.google.android.c2dm.intent.RECEIVE" })]
public class MyGcmListenerService : GcmListenerService
{
public override void OnMessageReceived (string from, Bundle data)
{
var message = data.GetString ("message");
Log.Debug ("MyGcmListenerService", "From: " + from);
Log.Debug ("MyGcmListenerService", "Message: " + message);
DataAccess.InsertDowload (message);
SendNotification (message);
}
void SendNotification (string message)
{
var intent = new Intent (this, typeof(MainActivity));
intent.AddFlags (ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Notification.Builder (this)
.SetSmallIcon (Resource.Drawable.mhu2)
.SetContentTitle ("Mobile Health Unit")
.SetContentText ("U heeft een nieuwe vragenlijst.")
.SetAutoCancel (true)
.SetContentIntent (pendingIntent);
var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
notificationManager.Notify (0, notificationBuilder.Build());
}
}
}
InstanceIdListenerService.cs
using Android.App;
using Android.Content;
using Android.Gms.Gcm.Iid;
namespace Dharma.Droid
{
[Service(Exported = false), IntentFilter(new[] { "com.google.android.gms.iid.InstanceID" })]
class MyInstanceIDListenerService : InstanceIDListenerService
{
public override void OnTokenRefresh()
{
var intent = new Intent (this, typeof (RegistrationIntentService));
StartService (intent);
}
}
}
RegistrationIntentService.cs
using System;
using Android.App;
using Android.Content;
using Android.Util;
using Android.Gms.Gcm;
using Android.Gms.Gcm.Iid;
namespace Dharma.Droid
{
[Service(Exported = false)]
class RegistrationIntentService : IntentService
{
static object locker = new object();
public RegistrationIntentService() : base("RegistrationIntentService") { }
protected override void OnHandleIntent (Intent intent)
{
try
{
Log.Info ("RegistrationIntentService", "Calling InstanceID.GetToken");
lock (locker)
{
var instanceID = InstanceID.GetInstance (this);
var token = instanceID.GetToken (
"***************", GoogleCloudMessaging.InstanceIdScope, null);
Log.Info ("RegistrationIntentService", "GCM Registration Token: " + token);
SendRegistrationToAppServer (token);
Subscribe (token);
}
}
catch (Exception e)
{
Log.Debug("RegistrationIntentService", "Failed to get a registration token");
return;
}
}
void SendRegistrationToAppServer (string token)
{
}
void Subscribe (string token)
{
var pubSub = GcmPubSub.GetInstance(this);
pubSub.Subscribe(token, "/topics/global", null);
}
}
}
SplashActivity.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V7.App;
using Android.Util;
using System.Threading.Tasks;
using Android.Gms.Common;
namespace Dharma.Droid
{
[Activity(Theme = "#style/MyTheme.Splash", MainLauncher = true, NoHistory = true)]
public class SplashActivity : AppCompatActivity
{
static readonly string TAG = "X:" + typeof (SplashActivity).Name;
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
}
protected override void OnResume()
{
base.OnResume();
Task startupWork = new Task(() =>
{
Task.Delay(5000); // Simulate a bit of startup work.
});
startupWork.ContinueWith(t =>
{
NetworkDiscovery network = new NetworkDiscovery();
CredentialsService cs = new CredentialsService();
if (GetToken() && network.IsOnline())
{
StartActivity(typeof (MainActivity));
}
else
{
StartActivity(typeof (NoInternetActivity));
}
}, TaskScheduler.FromCurrentSynchronizationContext());
startupWork.Start();
}
public bool GetToken()
{
if (IsPlayServicesAvailable ())
{
var intent = new Intent (this, typeof (RegistrationIntentService));
StartService (intent);
return true;
}
else
{
return false;
}
}
public bool IsPlayServicesAvailable ()
{
int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable (this);
if (resultCode != ConnectionResult.Success)
{
return false;
}
else
{
return true;
}
}
}
}
The issue is with these lines:
var intent = new Intent (this, typeof(MainActivity));
intent.AddFlags (ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.OneShot);
Specifically var intent = new Intent (this, typeof(MainActivity)); where you are telling the notification to open your MainActivity when it is clicked. If you want to show the splash screen, you should tell it to open the splash screen instead by replacing that line with:
var intent = new Intent (this, typeof(SplashActivity));
The only issue with this is if the application is already open, you might not want to show the splash screen again. To fix this, I would recommend doing something like this where they have a boolean on IsRunning that gets set in the MainActivity lifecycle events. You could check that boolean like this possibly:
Activity intent;
if(MainActivity.IsRunning) {
intent = new Intent (this, typeof(MainActivity));
intent.AddFlags (ActivityFlags.ClearTop);
} else {
intent = new Intent (this, typeof(SplashActivity));
intent.AddFlags (ActivityFlags.ClearTop);
}
var pendingIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.OneShot);
Warning, I did not test the code above.

Resources