0

I follow the tutorial in https://learn.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=vswin and manage to make server to client notification.

I find a few tutorials and example in java but i need to make it in Xamarin android platform.

I need to make application that send notification from one phone to one phone which is client to client and still using FCM, anyone have idea or example code that i can dig in?

yus ala
  • 3
  • 4
  • You can only send messages from the server, https://firebase.google.com/docs/cloud-messaging/admin/send-messages. What you are looking for is most likely client -> server -> FCM -> client. You can also use Cloud Functions for a serverless environment with an HTTPS endpoint to point the clients to. – Charles Crete Mar 15 '18 at 04:35
  • @CharlesCrete You can think of the phone as a server, because whether your server or your phone just send a request using HTTP to FCM, and then FCM will send the notification to the other phone. So FCM just need a HTTP request. – Robbit Mar 16 '18 at 02:51
  • For HTTP request do you have example for that @joe-lv-msft – yus ala Mar 16 '18 at 04:14
  • I read Document about it at [link](https://firebase.google.com/docs/cloud-messaging/server#choose) but quiet dont understand as I new to this. – yus ala Mar 16 '18 at 04:34
  • You will need to have admin credentials on your app, which is extremely not recommended for production apps. For testing apps that would be fine yes, but you will also need a way to manage FCM tokens, which the server also comes in handy – Charles Crete Mar 16 '18 at 05:56
  • @JoeLv-MSFT so i need to make two app right?one to receive with your code in it and one who send it – yus ala Mar 21 '18 at 04:27

1 Answers1

0

First, please follow this step by step to complete it, then you will get the base application.

Second, add a button to send Http to the FCM server:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <TextView
      android:text=" "
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/msgText"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:padding="10dp" />
  <Button
    android:id="@+id/bt"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
</LinearLayout>

initialize the button in OnCreate:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.Main);
    msgText = FindViewById<TextView>(Resource.Id.msgText);
    IsPlayServicesAvailable();
    Button bt = FindViewById<Button>(Resource.Id.bt);
    bt.Click += Bt_Click;

}

Here I used two class to generate the json string, and I am using json.net:

class Mes
{
    public string to;
    public Noti notification;
    public Mes(string to,Noti notification){
        this.to = to;
        this.notification = notification;
    }
}
class Noti {
    public string title;
    public string text;
    public Noti(string body,string text) {
        this.title = body;
        this.text = body;
    }
}

Click event(I am using okhttp3):

 private void Bt_Click(object sender, System.EventArgs e)
{

    Mes mes = new Mes("your token",
        new Noti("great","yes"));
    string json = JsonConvert.SerializeObject(mes);
    Log.Error("json",json);
    OkHttpClient client = new OkHttpClient();
    RequestBody body = RequestBody.Create(
    MediaType.Parse("application/json; charset=utf-8"),json);
    Request request = new Request.Builder()
        .Url("https://fcm.googleapis.com/fcm/send")// this is the base url which you can find it from  https://firebase.google.com/docs/cloud-messaging/http-server-ref?#params
        .Post(body)
        .AddHeader("Authorization", "your app key")// find it from this case https://stackoverflow.com/questions/37337512/where-can-i-find-the-api-key-for-firebase-cloud-messaging
        .Build();

    // Synchronous blocking call

    client.NewCall(request).Enqueue(
        (call, response) => {
        // Response came back
        string body1 = response.Body().String();
        Log.Error("lv",body1);
        }, (call, exception) => {
            // There was an error
            Log.Error("lv", exception.Message);
        });
}

After clicking the button, you will get a notification(if you have done with the first link), also, you don't need send a notification, you can use the data to do other things.

Update 1:

Change your MyFirebaseIIDService to this:

public class MyFirebaseIIDService : FirebaseInstanceIdService
{
    const string TAG = "MyFirebaseIIDService";
   public static string token;
    public override void OnTokenRefresh()
    {
         token = FirebaseInstanceId.Instance.Token;
        Log.Debug(TAG, "Refreshed token: " + token);
        SendRegistrationToServer(token);
    }
    void SendRegistrationToServer(string token)
    {
        // Add custom implementation, as needed.
    }
}

And then use this:

Mes mes = new Mes(MyFirebaseIIDService.token,new Noti("great","yes"));

Update 2:

    Request request = new Request.Builder()
        .Url("https://fcm.googleapis.com/fcm/send")
        .Post(body)
        .AddHeader("Authorization", "key=AAAAjPn9-TY:APA91bE-g4774KmFI72V1gWATmK8uta7N7NgcufoEgGgdidU9wyWBQ5YagCjP0WPBKrgILHZSVeb1I9vegYC-YfFHE2umWWcTzjo-t7W8ynDkwbB6qHY7JZExaxxvlI3VIg3d66sFZ40")
        .Build();

This is my http request, note that AddHeader method, you need use key=....

Robbit
  • 4,300
  • 1
  • 13
  • 29
  • Hi @JoeLv-MSFT, The error The request was missing an Authentication Key (FCM Token) appear, although i already insert my token at : ` Mes mes = new Mes("my token", new Noti("great","yes"));` – yus ala Mar 22 '18 at 04:30
  • The token will be refresh if you reinstall the app. Every time you install your app the token will be different. – Robbit Mar 22 '18 at 04:44
  • Or you can install the app on phone B, and get the phone B's token, and then install the App with the phone B's token on phone A. – Robbit Mar 22 '18 at 04:47
  • still missing the authentication key as I using the server or server legacy key @JoeLv-MSFT – yus ala Mar 26 '18 at 04:16
  • Hi,@yusala, I am can't understand it. It works well on my side. – Robbit Mar 26 '18 at 05:31
  • Hi @JoeLv-MSFT do you post your project in GitHub or google drive for reference? I also don't understand it still not work. – yus ala Mar 26 '18 at 06:48
  • Hi, @yusala, My answer is my project, I guess something may be you have missed, check my update 2. – Robbit Mar 26 '18 at 07:14