I use this code to receive push notifications on iOS. The code works but I get a warning in this line:
new UIAlertView("Error registering push notifications", error.LocalizedDescription, null, "OK", null).Show();
Warning CS0618: 'UIAlertView.UIAlertView(string, string, UIAlertViewDelegate, string, params string[])' is obsolete: 'Use overload with a IUIAlertViewDelegate parameter'
Is it still possible to use FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)? What should I change in my code?
using System;
using Foundation;
using UIKit;
using Xamarin.Forms;
namespace InapppurchaseTest.iOS
{
[Register("AppDelegate")]
class Program : UIApplicationDelegate
{
private static Game1 game;
internal static void RunGame()
{
game = new Game1();
game.Run();
}
static void Main(string[] args)
{
UIApplication.Main(args, null, "AppDelegate");
}
public override void FinishedLaunching(UIApplication app)
{
global::Xamarin.Forms.Forms.Init();
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
var authOptions = UserNotifications.UNAuthorizationOptions.Alert | UserNotifications.UNAuthorizationOptions.Badge | UserNotifications.UNAuthorizationOptions.Sound;
UserNotifications.UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) =>
{
Console.WriteLine(granted);
});
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
else
{
var notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
}
RunGame();
}
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
// Get current device token
var DeviceToken = deviceToken.Description;
if (!string.IsNullOrWhiteSpace(DeviceToken))
{
DeviceToken = DeviceToken.Trim('<').Trim('>');
}
// Get previous device token
var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");
// Has the token changed?
if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(DeviceToken))
{
//TODO: Put your own logic here to notify your server that the device token has changed/been created!
}
// Save new device token
NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");
}
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
new UIAlertView("Error registering push notifications", error.LocalizedDescription, null, "OK", null).Show();
}
public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{
ProcessNotification(userInfo, false);
}
void ProcessNotification(NSDictionary options, bool fromFinishedLaunching)
{
// Check to see if the dictionary has the aps key. This is the notification payload you would have sent
if (null != options && options.ContainsKey(new NSString("aps")))
{
//Get the aps dictionary
NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;
string alert = string.Empty;
if (aps.ContainsKey(new NSString("alert")))
alert = (aps[new NSString("alert")] as NSString).ToString();
if (!fromFinishedLaunching)
{
//Manually show an alert
if (!string.IsNullOrEmpty(alert))
{
NSString alertKey = new NSString("alert");
UILocalNotification notification = new UILocalNotification();
notification.FireDate = NSDate.Now;
notification.AlertBody = aps.ObjectForKey(alertKey) as NSString;
notification.TimeZone = NSTimeZone.DefaultTimeZone;
notification.SoundName = UILocalNotification.DefaultSoundName;
UIApplication.SharedApplication.ScheduleLocalNotification(notification);
}
}
}
}
}
}
If want to remove this warnning , adding [Obsolete] berfore Method as follow:
[Obsolete]
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
new UIAlertView("Error registering push notifications", error.LocalizedDescription, null, "OK", null).Show();
}
By the way , from document Displaying Alerts in Xamarin.iOS
Starting with iOS 8, UIAlertController has completed replaced UIActionSheet and UIAlertView both of which are now deprecated.
Then you can use UIAlertController to realize this:
//Create Alert
var okAlertController = UIAlertController.Create("Title", "The message", UIAlertControllerStyle.Alert);
//Add Action
okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
// Present Alert
PresentViewController(okAlertController, true, null);
Related
var acceptAction = UNNotificationAction.FromIdentifier("AcceptAction", "Accept", UNNotificationActionOptions.None);
var declineAction = UNNotificationAction.FromIdentifier("DeclineAction", "Decline", UNNotificationActionOptions.None);
// Create category
var meetingInviteCategory = UNNotificationCategory.FromIdentifier("MeetingInvitation",
new UNNotificationAction[] { acceptAction, declineAction }, new string[] { }, UNNotificationCategoryOptions.CustomDismissAction);
// Register category
var categories = new UNNotificationCategory[] { meetingInviteCategory };
UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet<UNNotificationCategory>(categories));
how can you receive a custom actionable push notification and where need to put the above code in which file?
Before an iOS app can send notifications to the user the app must be registered with the system and, because a notification is an interruption to the user, an app must explicitly request permission before sending them.
Notification permission should be requested as soon as the app launches by adding the following code to the FinishedLaunching method of the AppDelegate and setting the desired notification type (UNAuthorizationOptions):
...
using UserNotifications;
...
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
....
//after iOS 10
if(UIDevice.CurrentDevice.CheckSystemVersion(10,0))
{
UNUserNotificationCenter center = UNUserNotificationCenter.Current;
center.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.UNAuthorizationOptions.Badge, (bool arg1, NSError arg2) =>
{
});
center.Delegate = new NotificationDelegate();
}
else if(UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert| UIUserNotificationType.Badge| UIUserNotificationType.Sound,new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
return true;
}
New to iOS 10, an app can handle Notifications differently when it is in the foreground and a Notification is triggered. By providing aUNUserNotificationCenterDelegate and implementing theUserNotificationCentermethod, the app can take over responsibility for displaying the Notification. For example:
using System;
using ObjCRuntime;
using UserNotifications;
namespace xxx
{
public class NotificationDelegate:UNUserNotificationCenterDelegate
{
public NotificationDelegate()
{
}
public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
// Do something with the notification
Console.WriteLine("Active Notification: {0}", notification);
// Tell system to display the notification anyway or use
// `None` to say we have handled the display locally.
completionHandler(UNNotificationPresentationOptions.Alert|UNNotificationPresentationOptions.Sound);
}
public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
// Take action based on Action ID
switch (response.ActionIdentifier)
{
case "reply":
// Do something
break;
default:
// Take action based on identifier
if (response.IsDefaultAction)
{
// Handle default action...
}
else if (response.IsDismissAction)
{
// Handle dismiss action
}
break;
}
// Inform caller it has been handled
completionHandler();
}
}
}
I created the application with Xamarin.forms.iOS and use Plugin.FirebasePushNotification to send the notification through firebase.
once I registered the device there no problem with getting Token, but, after I delete app and test again the app doesn't get the Token.
I cannot receive the notification anymore.
AppDelegate.cs
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
NSDictionary _launchOptions;
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
ImageCircleRenderer.Init();
LoadApplication(new App());
AnimationViewRenderer.Init();
_launchOptions = options;
Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
SQLitePCL.Batteries.Init();
ZXing.Net.Mobile.Forms.iOS.Platform.Init();
FirebasePushNotificationManager.Initialize(options, true);
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Sound,
(granted, error) =>
{
if (granted)
InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
});
}
else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
else
{
UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
}
CrossFirebasePushNotification.Current.OnTokenRefresh += (s, p) =>
{
System.Diagnostics.Debug.WriteLine($"TOKEN : {p.Token}");
UIPasteboard clipboard = UIPasteboard.General;
clipboard.String = p.Token;
Helper.Settings.Token = p.Token;
};
CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
{
Dictionary<string, object> dic = p.Data as Dictionary<string, object>;
if (dic["targetUserId"].ToString() != null && Helper.Settings.UserId == dic["targetUserId"].ToString())
{
System.Diagnostics.Debug.WriteLine("Received");
Helper.Settings.userWhoSentNotiId = dic["userWhoSentNotiId"].ToString();
Helper.Settings.callingStatus = true; FirebasePushNotificationManager.CurrentNotificationPresentationOption = UNNotificationPresentationOptions.Alert;
MessagingCenter.Send<object, string>(this, "CallingNotifications", dic["callingName"].ToString());
}
};
CrossFirebasePushNotification.Current.OnNotificationOpened += (s, p) =>
{
Dictionary<string, object> dic = p.Data as Dictionary<string, object>;
Helper.Settings.userWhoSentNotiId = dic["userWhoSentNotiId"].ToString();
Helper.Settings.callingStatus = true;
MessagingCenter.Send<object, string>(this, "CallingNotifications", dic["callingName"].ToString());
};
return base.FinishedLaunching(app, options);
}
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
FirebasePushNotificationManager.DidRegisterRemoteNotifications(deviceToken);
}
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
FirebasePushNotificationManager.RemoteNotificationRegistrationFailed(error);
}
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
FirebasePushNotificationManager.DidReceiveMessage(userInfo);
completionHandler(UIBackgroundFetchResult.NewData);
}
}
I notice the app don't launch
CrossFirebasePushNotification.Current.OnTokenRefresh
How can the app refresh the token?
I want to display local notification when the app is closed and also app is not in the recent history of the device.How can I do this.
Please help me..
Here is my code MainPage.cs
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);
Device.StartTimer(TimeSpan.FromSeconds(5), () =>
{
GetData();
return true;
});
}
public void GetData()
{
IAlarmReceiver _local = DependencyService.Get<IAlarmReceiver>();
_local.LocalNotifications("Xamarin", "Hello world");
}
private void btn_Click_Clicked(object sender, EventArgs e)
{
GetData();
}
}
Here I call the notification method in every 5 seconds.
Here is my AlarmReciever.CS
public void GetNotification(string Title, string Text)
{
Intent _intent = new Intent(Application.Context, typeof(MainActivity));
const int _pendingIntentId = 0;
PendingIntent _pintent = PendingIntent.GetActivity(Application.Context, _pendingIntentId, _intent, PendingIntentFlags.CancelCurrent);
Notification.Builder builder = new Notification.Builder(Application.Context)
.SetContentIntent(_pintent)
.SetContentTitle(Title)
.SetContentText(Text)
.SetDefaults(NotificationDefaults.Sound)
.SetAutoCancel(true)
.SetSmallIcon(Resource.Drawable.icon);
Notification _notification = builder.Build();
NotificationManager _notificationmanager = Android.App.Application.Context.GetSystemService(Context.NotificationService)
as NotificationManager;
_notificationmanager.Notify(0, _notification);
you can use ACR Notifications Plugin for Xamarin this will display the local notification when app is closed.
Example await CrossNotifications.Current.Send("Happy Birthday", "I sent this a long time ago", when = TimeSpan.FromDays(50));
If you tested your program using the debugger the notification will be terminated with the rest of your application as soon as you close it.
I tested your code (assuming _local.LocalNotifications should be _local.GetNotification) and it worked, when the app is started on the device without the debugger.
EDIT
To display the notification all x minutes, use a ScheduledJob
Add a StartJob Method to your IAlarmReceiver inteface and its implementation
public void StartJob()
{
var builder = new JobInfo.Builder(1234, new ComponentName(Android.App.Application.Context, Java.Lang.Class.FromType(typeof(ScheduledJob))));
builder.SetPeriodic(15L * 60L * 1000L); // <- change the intervall
var jobInfo = builder.Build();
var jobScheduler = (JobScheduler)Android.App.Application.Context.GetSystemService(Context.JobSchedulerService);
jobScheduler.Schedule(jobInfo);
}
This method starts the ScheduledJob (defined in the android project)
[Service(Exported = true, Permission = "android.permission.BIND_JOB_SERVICE")]
public class ScheduledJob : JobService
{
public override bool OnStartJob(JobParameters #params)
{
new AlarmReceiver().GetNotification("Hello World!", "Xamarin");
return false;
}
public override bool OnStopJob(JobParameters #params)
{
return false;
}
}
Replace
Device.StartTimer(TimeSpan.FromSeconds(5), () =>
{
GetData();
return true;
});
with
DependencyService.Get<IAlarmReceiver>().StartJob();
I am setting up push notifications in my Xamarin Forms app for my Android project. I have been following the online documentation (https://developer.xamarin.com/guides/xamarin-forms/cloud-services/push-notifications/azure/) to get it working but I am having some problems
1 - The notifications don't arrive when I send a test from my Azure Notification Hub.
2 - The app crashes during debug after a certain amount of time during the Register method.
I believe that the problem is being caused by its registration, I don't think the registration is working and hence the app times out which causes it to crash and also the Azure Notification Hub sends the message successfully but no device picks it up (possibly because it's not registred)
To start off, here is what I have done so far.
I have setup a project in console.firebase.google.com and taken note of the sender ID and the Server Key as instructed. I have given the Project ID a name of myapp-android-app.
I have added all the code from the documtation to my Android project.
I have added a GCM notification service to my Notification Hub in Azure and supplied it with the Server Key documented from my Firebase app registration.
I have added my google account to my Andoird Emulator
Here is the source code from my Android project.
MainActivity.cs
using System;
using Android.App;
using Android.Content.PM;
using Android.OS;
using Gcm.Client;
namespace MyApp.Droid
{
[Activity(Label = "#string/app_name", Theme = "#style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
//public static MainActivity CurrentActivity { get; private set; }
// Create a new instance field for this activity.
static MainActivity instance = null;
// Return the current activity instance.
public static MainActivity CurrentActivity
{
get
{
return instance;
}
}
protected override void OnCreate(Bundle bundle)
{
instance = this;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
LoadApplication(new App());
try
{
// Check to ensure everything's setup right
GcmClient.CheckDevice(this);
GcmClient.CheckManifest(this);
// Register for push notifications
System.Diagnostics.Debug.WriteLine("Registering...");
GcmClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS);
}
catch (Java.Net.MalformedURLException)
{
CreateAndShowDialog("There was an error creating the client. Verify the URL.", "Error");
}
catch (Exception e)
{
CreateAndShowDialog(e.Message, "Error");
}
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
}
void CreateAndShowDialog(String message, String title)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetMessage(message);
builder.SetTitle(title);
builder.Create().Show();
}
}
}
GcmService.cs
using Android.App;
using Android.Content;
using Android.Media;
using Android.Support.V4.App;
using Android.Util;
using Gcm.Client;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
[assembly: Permission(Name = "#PACKAGE_NAME#.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "#PACKAGE_NAME#.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
[assembly: UsesPermission(Name = "android.permission.INTERNET")]
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
//GET_ACCOUNTS is only needed for android versions 4.0.3 and below
[assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")]
namespace MyApp.Droid
{
[BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "#PACKAGE_NAME#" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "#PACKAGE_NAME#" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "#PACKAGE_NAME#" })]
public class PushHandlerBroadcastReceiver : GcmBroadcastReceiverBase<GcmService>
{
public static string[] SENDER_IDS = new string[] { "xxxxxxxxxx" };
}
[Service]
public class GcmService : GcmServiceBase
{
public static string RegistrationToken { get; private set; }
public GcmService()
: base(PushHandlerBroadcastReceiver.SENDER_IDS) { }
protected override void OnRegistered(Context context, string registrationToken)
{
Log.Verbose("PushHandlerBroadcastReceiver", "GCM Registered: " + registrationToken);
RegistrationToken = registrationToken;
var push = AzureService.DefaultManager.CurrentClient.GetPush();
MainActivity.CurrentActivity.RunOnUiThread(() => Register(push, null));
}
protected override void OnUnRegistered(Context context, string registrationToken)
{
Log.Error("PushHandlerBroadcastReceiver", "Unregistered RegisterationToken: " + registrationToken);
}
protected override void OnError(Context context, string errorId)
{
Log.Error("PushHandlerBroadcastReceiver", "GCM Error: " + errorId);
}
public async void Register(Microsoft.WindowsAzure.MobileServices.Push push, IEnumerable<string> tags)
{
try
{
const string templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}";
JObject templates = new JObject();
templates["genericMessage"] = new JObject
{
{"body", templateBodyGCM}
};
await push.RegisterAsync(RegistrationToken, templates);
Log.Info("Push Installation Id", push.InstallationId.ToString());
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message + ex.StackTrace);
Debugger.Break();
}
}
protected override void OnMessage(Context context, Intent intent)
{
Log.Info("PushHandlerBroadcastReceiver", "GCM Message Received!");
var msg = new StringBuilder();
if (intent != null && intent.Extras != null)
{
foreach (var key in intent.Extras.KeySet())
msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());
}
// Retrieve the message
var prefs = GetSharedPreferences(context.PackageName, FileCreationMode.Private);
var edit = prefs.Edit();
edit.PutString("last_msg", msg.ToString());
edit.Commit();
string message = intent.Extras.GetString("message");
if (!string.IsNullOrEmpty(message))
{
CreateNotification("New todo item!", "Todo item: " + message);
}
string msg2 = intent.Extras.GetString("msg");
if (!string.IsNullOrEmpty(msg2))
{
CreateNotification("New hub message!", msg2);
return;
}
CreateNotification("Unknown message details", msg.ToString());
}
void CreateNotification(string title, string desc)
{
// Create notification
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
// Create an intent to show the UI
var uiIntent = new Intent(this, typeof(MainActivity));
// Create the notification
// we use the pending intent, passing our ui intent over which will get called
// when the notification is tapped.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
var notification = builder.SetContentIntent(PendingIntent.GetActivity(this, 0, uiIntent, 0))
.SetSmallIcon(Android.Resource.Drawable.SymActionEmail)
.SetTicker(title)
.SetContentTitle(title)
.SetContentText(desc)
.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification)) // set the sound
.SetAutoCancel(true).Build(); // remove the notification once the user touches it
// Show the notification
notificationManager.Notify(1, notification);
}
}
}
I replaced the string in: public static string[] SENDER_IDS = new string[] { "xxxxxxxx" }; with the Sender id I recorded from my Firebase console app.
When I run the app through my Android Emulator I get the following error after about 3 minutes.
Error in GcmService.cs:
Exception: System.Threading.Tasks.TaskCanceledException: A task was canceled.
seen at Line 71:
await push.RegisterAsync(RegisteToken, templates);
Does anyone know what I have done wrong? Am I correct in thinking that it's not registering correctly?
I was able to integrate Firebase Cloud Messaging in Xamarin.Forms (both Android and iOS) following this official Xamarin guide that is well explained:
https://developer.xamarin.com/guides/android/application_fundamentals/notifications/remote-notifications-with-fcm/
Looking at your code, it seems to me that you use the old Gcm service (that is deprecated) and not the new Fcm.
You should have a google-services.json file and a FirebaseMessagingService class
Then...
Note
As of now, Xamarin Forms does not handle very well the deployment of the app while developing, making a dirty reinstallation that seems to invalidate the previously obtained Notification Token and sometimes raising IllegalStateException when calling Fcm library's methods.
That's a known bug that can be resolved by cleaning the solution and
relaunching
I am using Rivets with Android to open my app and get data from a webpage.
I have the following in my onCreate method.
if (Intent.HasExtra("al_applink_data"))
{
var data = Intent.Data.ToString();
var appLinkData = Intent.GetStringExtra("al_applink_data");
var alUrl = new Rivets.AppLinkUrl(data, appLinkData);
// InputQueryParameters will contain our token
if (alUrl != null && alUrl.InputQueryParameters.ContainsKey("an"))
{
_token = alUrl.InputQueryParameters["an"];
}
else
{
// No token found
}
}
My activity has this filter at the top.
[IntentFilter(new[] { Intent.ActionView },
DataScheme = "test",
DataHost = "test",
Categories = new[]
{
Intent.CategoryDefault, Intent.CategoryBrowsable
})]
My test content is test://test?an=1234, which successfully opens my activity. However, Intent.HasExtra("al_applink_data") is always false and Intent.GetStringExtra("al_applink_data") is always null. Intent.Data.ToString(); shows my content with the parameter. I am new to Rivets and Android programming in C#. Why might this always be false and null?
Try like this:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(....);
if (Intent != null)
{
OnNewIntent(Intent);
}
}
protected override void OnNewIntent(Android.Content.Intent intent)
{
base.OnNewIntent(intent);
var appLinkData = intent.GetStringExtra("al_applink_data");
AppLinkUrl alUrl = null;
if (appLinkData != null)
{
alUrl = new Rivets.AppLinkUrl(intent.Data.ToString(), appLinkData);
}
if (alUrl != null) {
// LAUNCH URI
}
}
Remember to use the (lowercase) "intent" parameter passed in the OnNewIntent method:
intent.GetStringExtra("al_applink_data") ----> contains data
Intent.GetStringExtra("al_applink_data") ----> return null.