在Xamarin.Android中从GooglePlayService GCM转换为FireBaseMessaging无需注册

时间:2017-08-02 16:33:44

标签: firebase xamarin.android google-cloud-messaging firebase-cloud-messaging

我继承了一个使用推送通知的Xamarin Android项目。该项目使用的是Google Client Messaging软件包,我正在转换为Firebase Messaging软件包。但是我注意到FireBaseMessaging没有.register方法。我是否仍需要从firebase控制台注册发件人ID,如果是这样的话?

旧代码:

    private void registerInBackground()
    {

        Task.Run(() =>
            {
                string msg = "";
                try
                {
                    if (gcm == null)
                    {
                        gcm = GoogleCloudMessaging.GetInstance(this);
                    }
                    regid = gcm.Register(Constants.SenderID);
                    msg = "Device registered, registration ID=" + regid;
                    Log.Info(TAG, msg);


                    // can use GCM/HTTP or CCS to send messages to your app.
                    sendRegistrationIdToBackend(regid);


                    // Persist the regID - no need to register again.
                    storeRegistrationId(this, regid);
                }
                catch (System.Exception ex)
                {
                    msg = "Error :" + ex.Message;

                    Log.Error(TAG, msg);
                }
                finally
                {
                    //RunOnUiThread(() => mDisplay.Append(msg + "\n"));
                }
                return msg;
            });
    }

当我改为FireBaseMessaging时,我注意到regid = gcm.Register(Constants.SenderID); Firebase消息传递上没有注册方法。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您无需调用寄存器方法即可自动注册。您只需按照以下步骤操作:

  1. 将google-services.json添加到Android项目中,并确保将该文件的构建操作设置为GoogleServicesJson。

  2. 在AndroidManifest.xml中的application tag:

    下添加以下内容
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" 
          android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
      <action android:name="com.google.android.c2dm.intent.RECEIVE" />
      <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
      <category android:name="${applicationId}" />
    </intent-filter>
    </receiver>
    
  3. 实施FirebaseInstanceIdService

    [Service, IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseInstanceIdService : FirebaseInstanceIdService
    {
       public override void OnTokenRefresh()
       {
    
         var token = FirebaseInstanceId.Instance.Token;
         //send token to server here.
       }
    }