Push Notification to specific devices on xamarin forms android/ios - xamarin

I have successfully set up push notification using firebase and linked it up Azure notification hub using this guide from the Microsoft docs:
https://learn.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm
However I am now trying to push notification to specific devices using tags. There isn't currently a xamarin c# document. I have done some research around the area and found people solving what seems to be the same problem using dependency injection (which feels a little complex?). I have also found these two questions/answers:
How to push notification to specific users in Xamarin.Forms Android?
https://forums.xamarin.com/discussion/85935/how-to-push-notification-to-specific-users-in-xamarin-forms-android
Both of which point to the method "OnRegistered" which i don't seem to have? i've had another look through the documentation I followed to set up notifications in the first place and I seem to have followed it correctly?
I have the following code for android:
private void SendRegistrationToServer(string token)
{
// Register with Notification Hubs
hub = new NotificationHub(ApplicationConstants.NotificationHubName,
ApplicationConstants.ListenConnectionString, this);
var tags = new List<string>() { };
var regID = hub.Register(token, tags.ToArray()).RegistrationId;
}
I can obviously set the tags manually there, however how do i 'call' this Method again if the tags need to be changed?
So bottom line, my question is how do i set up push notification to specific devices on xamarin.forms android/ios?
Thanks.

Related

How to import Activity of NfcFCardEmulation.EnableService from Xamarin common project, not Android project?

I'm developing an app using Xamarin's HCE feature.
The project structure is as follows.
hceSample
hceSample.Android
hceSample.iOS
I am implementing hce simulation code called hceService in hceSample, not hceSample.Android.
A function called Enable_Card exists in the hce service, and you want to use the NfcFCardEmulation.EnableService function in that function.
Activity and ComponentName are requested as parameters of the function.
The ComponentName area was handled easily, but I don't know how to get the Activity. Please advise.
This is the contents of enable_Card function of hceService.
private Activity activity = null;
private bool enable_Card(cardModel card)
{
try
{
sid = card.cardSN;
tag = "Felica";
emulation.EnableService(, componentName); //<- How to get Activity??
emulation.SetNfcid2ForService(componentName, sid);
return true;
}
catch
{
return false;
}
}
This is my first time asking a question on Stackoverflow.
I would appreciate it if you could point out any missing or incorrect parts.
I trying this
activity = Xamarin.Essentials.Platform.CurrentActivity; //<- this function is not found!
Added missing information!
The namespace of the Enable_Card function is located in hceSample.Service.
Are you using the NfcFCardEmulation.EnableService(Activity, ComponentName) Method, right?
The method is an android api from android sdk,you cannot use it directly in xamarin.form(yours is hceSample) project.
If you want to call the function in xamarin form project(hceSample) from native platform(hceSample.Android, or hceSample.iOS),you can use Xamarin.Forms DependencyService to achieve this.
The DependencyService class is a service locator that enables Xamarin.Forms applications to invoke native platform functionality from shared code.
For more information about DependencyService, you can check document Xamarin.Forms DependencyService. And there is a sample included in above document,which is helpful for you to understand DependencyService.
Note:
We recognize that hardware service is the right and ideal way to
implement in each OS project. However, I'm curious if there is a way
to code Android and iOS at the same time
Since the api you used is from android sdk, you can call it in native android or use DependencyService to call it on xamarin.form(yours is hceSample) project.
If you call it on xamarin.form(yours is hceSample) project, you also need to find the the corresponding function or interface in iOS.

Visual Studio App Center Analytics Not working for Xamarin Forms Android Project

I am using Visual Studio App Center for my Xamarin Forms Android Application for capturing the Analytics(Events and Crashes)
I am configuring crashes and analytics in OnStart of my App.Xaml.cs
AppCenter.Start($"android={Settings.Current.AppCenterAnalyticsAndroid};" +
typeof(Analytics), typeof(Crashes));
And for invoking the Events I am calling the below Method.
public void TrackEvent(string name, Dictionary<string, string> properties = null)
{
Analytics.SetEnabledAsync(true).ConfigureAwait(false);
Analytics.TrackEvent(name, properties);
}
Crashes are logging correctly in App Center But the events are not.
Also I can see the corresponding entries in Log Flow
Your app secret string is invalid because it contains + typeof(Analytics), it should be , typeof(Analytics).
Since you used the android key/value delimiter we could extract the appSecret and make it work with Crashes, but typeof(Analytics) ended up in the wrong appSecret parameter string.
You shouldn't need to add Analytics.SetEnabledAsync(true).ConfigureAwait(false);
Simply Call Analytics.TrackEvent(name, properties); (it doesn't need to be in a task anyways. I track my events in the Construtor of pages, for example.
Also, when you run the application, you get a debug Message confirming that AppCenter has been configured correctly, check if that is the case.
And, it may take a while, for them to appear in the Events.

Xamarin Forms - How to open specific page after clicking on notification when the app is closed?

I'm actually working on a Xamarin Forms application that need push notifications. I use the Plugin.PushNotification plugin.
When the app is running in the foreground or is sleeping (OnSleep), I have no problem to open a specific page when I click on a notification that I receive. But I was wondering how can I do that when the app is closed. Thanks!
I finally found the answer by myself and I want to share it in case someone needs it.
Nota bene: according to the official documentation of the plugin, it's Xam.Plugin.PushNotification that is deprecated. I use the new version of this plugin, Plugin.PushNotification which uses FCM for Android and APS for iOS.
There is no significant differences to open a notif when the app is running, is sleeping or is closed. Just add the next callback method in the OnCreate method (MyProject.Droid > MainApplication > OnCreate) and FinishedLaunching method (MyProject.iOS > AppDelegate > FinishedLaunching):
CrossPushNotification.Current.OnNotificationOpened += (s, p) =>
{
// manage your notification here with p.Data
App.NotifManager.ManageNotif(p.Data);
};
Common part
App.xaml.cs
// Static fields
// *************************************
public static NotifManager NotifManager;
// Constructor
// *************************************
public App()
{
...
NotifManager = new NotifManager();
...
}
NotifManager.cs
public class NotifManager
{
// Methods
// *************************************
public void ManageNotif(IDictionary<string, object> data)
{
// 1) switch between the different data[key] you have in your project and parse the data you need
// 2) pass data to the view with a MessagingCenter or an event
}
}
Unfortunately there is no succinct answer for either platform. Generally speaking, you need to tell the OS what to do when it starts the app as a result of the push notification. On both platforms, you should also consider what API level you are targeting, otherwise it won't work or even crash the app.
On iOS, you will need to implement this method in AppDelegate appropriately: FinishedLaunching(UIApplication application, NSDictionary launchOptions). The launchOptions will have the payload from the push notification for you to determine what to do with it (e.g. what page to open). For more information on iOS, Xamarin's documentation is a good place to start.
Android has a more complicated topology in terms of more drastic differences between API levels, whether you are using GCM/FCM, as well as requiring more code components. However, to answer the question directly, you will need to handle this in OnCreate(Bundle savedInstanceState) of your main Activity. If you are using Firebase, the push notification payload is available in Intent.Extras. Again, Xamarin's documentation has a good walkthrough.
Finally, note that the Plugin.PushNotification library you are using has been deprecated. I suggest you either change your library and/or your implementation soon. Part of the reason that library has been deprecated is because Google has deprecated the underlying Google Cloud Messaging (GCM) service, which will be decommissioned on April 11, 2019.

xamarin android project access PCL function

I created a Cross Platform Xamarin Forms app. In the Portable Class I have a WebView that loads a web page from a URL.
From my Android project, I would like to be able to change the WebView URL.
What is the best way to do this ? I am kind of new to this, so any help to point me in the right direction would be great.
Thank you
I had a similar scenario in which I wanted to read the received SMS in Android project and send the message to PCL project.
For that I used Xamarin's MessagingCenter:
In Android's activity, upon receiving the SMS, I used the following code to send the SMS message body back to PCL:
MessagingCenter.Send<RegisterSecondPage, string>
(new RegisterSecondPage(), "OtpReceived", code);
And in one of my PCL pages I received it back like this:
MessagingCenter.Subscribe<RegisterSecondPage, string>
(new RegisterSecondPage(), "OtpReceived", async (s, code) =>
{
ActivationCode = code;
});
I believe you can use similar scenario as well.

Closing Android Activity opened from Forms.Context.StartActivity

I am working on facebook authentication in a Xamarin forms app and want to use "native" login on each device.
The Facebook SDK (by Xamarin) is not designed for forms since it requires passing in an Android activity that implements some specific interfaces.
However; I was able to get the UI to display using a custom page renderer and then in that renderer calling StartActitivty with an activity that uses the exact implementation described in the Facebook SDK getting started. https://components.xamarin.com/view/facebookandroid
So far everything works perfect. The android app starts, xamarin forms kicks in, the custom page renderer is loaded the login android activity starts and the user logs in with facebook and we get to the console.writeline below.
So, how do I dismiss this intent or otherwise get back to xamarin forms?
Do I:
Dismiss this intent? - if so then what?
Inject something to "reset" the main page?
Other?
public void OnCompleted (Xamarin.Facebook.Model.IGraphUser user, Response response)
{
//TODO: show user details with welcome and button that takes them to main app.
//TODO: switch back to xam forms from here on out.
//TODO: figure out how to change the `main` activity to xam forms.
// 'Me' request callback
if (user != null) {
//How do I get back to Xamarin forms from here?
Console.WriteLine ("GOT USER: " + user.Name);
} else {
Console.WriteLine ("Failed to get 'me'!");
}
}
You should call Finish();
Anyway, if you want to see exactly how I did it, you can check it here:
https://github.com/IdoTene/XamarinFormsNativeFacebook

Resources