简体   繁体   English

xamarin android 推送通知只能工作一次

[英]xamarin android push notification only works once

i'm developing an android app and i followed this link to use google push notification我正在开发一个 android 应用程序,我按照这个链接使用谷歌推送通知
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.在 Visualstudio 中,它是工具->选项-Xamarin->Android 选项。 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:来自 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." “如果您强制关闭应用程序,FCM 将停止发送通知。Android 防止后台服务广播无意或不必要地启动已停止应用程序的组件。(有关此行为的更多信息,请参阅已停止应用程序的启动控件。)因此,每次运行应用程序时都必须手动卸载应用程序并从调试会话中停止它——这会迫使 FCM 生成一个新令牌,以便继续接收消息。”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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