简体   繁体   中英

xamarin android push notification only works once

i'm developing an android app and i followed this link to use google push notification
my problem is that the first time that app starts, push notification work's fine but as I restart my app, push notification stops working and I cant receive notifications.

here is my code:

[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(
                    "my_id", 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)
    {
     // some code
    }

    void Subscribe(string token)
    {
        var pubSub = GcmPubSub.GetInstance(this);
        pubSub.Subscribe(token, "/topics/global", null);
    }
}


[Service(Exported = false), IntentFilter(new[] { "com.google.android.c2dm.intent.RECEIVE" })]
public class MyGcmListenerService : GcmListenerService
{
    public override void OnMessageReceived(string from, Bundle data)
    {
        Log.Debug("MyGcmListenerService", "From:    " + from);
        Log.Debug("MyGcmListenerService", "Message: " + message);
    }
}


[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);
    }
}

and i send notification with this method

public static void SendNotification(string MESSAGE, string token)
    {
        var jGcmData = new JObject();
        var jData = new JObject();
        jData.Add("message", MESSAGE);

        jGcmData.Add("to", token);
        jGcmData.Add("data", jData);

        var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.TryAddWithoutValidation(
                    "Authorization", "key=" + API_KEY);

                System.Threading.Tasks.Task.WaitAll(client.PostAsync(url,
                    new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                        .ContinueWith(response =>
                        {
                            Console.WriteLine(response);
                            Console.WriteLine("Message sent: check the client device notification tray.");
                        }));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Unable to send GCM message:");
            Console.Error.WriteLine(e.StackTrace);
        }

    }


do you have any idea?

Is this in the emulator? I had this issue with the emulator and fixed it by turning off the option to preserve application data/cache between deploys. In Visualstudio it's Tools->Options-Xamarin->Android Options. Now I get a new token on each deploy and it always works.

Why this happens I haven't figured out. Maybe it's a security feature that a different build of the app cannot use the same taken?

From the official documentation of Xamarin:

"If you force-close the app, FCM will stop delivering notifications. Android prevents background service broadcasts from inadvertently or unnecessarily launching components of stopped applications. (For more information about this behavior, see Launch controls on stopped applications.) For this reason, it is necessary to manually uninstall the app each time you run it and stop it from a debug session – this forces FCM to generate a new token so that messages will continue to be received."

https://docs.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=windows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM