2

Я работаю над приложением Xamarin.Forms с Azure Notification Hub и Androud GCM. Теперь, когда я пользователь зарегистрирован зарегистрировать его на уведомление:Как отменить регистрацию клиента из Push-уведомлений?

У меня есть интерфейс:

public interface IPushNotificationService 
    { 
     void Register(); 
     void UnRegister(); 
    } 

А в проекте Android я реализовал интерфейс, как:

public class PushNotificationService : IPushNotificationService 
    { 

     public PushNotificationService() { } 

     public void Register() 
     { 
      RegisterWithGCM(); 
     } 

     public void UnRegister() 
     { 
      try 
      { 
       GcmClient.UnRegister(MainActivity.instance); 
      } 
      catch (Exception e) 
      { 
       Log.Verbose(PushHandlerBroadcastReceiver.TAG, "ERROR while UnRegistering - " + e.Message); 
      } 

     } 

     private void RegisterWithGCM() 
     { 
      try 
      { 
       // Check to ensure everything's setup right 
       GcmClient.CheckDevice(MainActivity.instance); 
       GcmClient.CheckManifest(MainActivity.instance); 

       // Register for push notifications 
       UnRegister(); 
       Log.Verbose(PushHandlerBroadcastReceiver.TAG, "Registering..."); 
       GcmClient.Register(MainActivity.instance, Constants.SenderID); 
      } 
      catch (Java.Net.MalformedURLException) 
      { 
       Log.Verbose(PushHandlerBroadcastReceiver.TAG, "ERROR - There was an error creating the client. Verify the URL."); 
      } 
      catch (Exception e) 
      { 
       Log.Verbose(PushHandlerBroadcastReceiver.TAG, "ERROR - " + e.Message); 
       CreateAndShowDialog("Cannot register to push notification. Please try to run the app again.", "Error"); 
      } 
     } 

     private void CreateAndShowDialog(String message, String title) 
     { 
      AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.instance); 

      builder.SetMessage(message); 
      builder.SetTitle(title); 
      builder.Create().Show(); 
     } 
    } 

Я также имею GcmService как слушать на сайтах MSDN Azure:

[assembly: Permission(Name = "@[email protected]_MESSAGE")] 
[assembly: UsesPermission(Name = "@[email protected]_MESSAGE")] 
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")] 
[assembly: UsesPermission(Name = "android.permission.INTERNET")] 
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")] 
namespace MyApp.Droid 
{ 
    [BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)] 
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "@[email protected]" })] 
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "@[email protected]" })] 
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "@[email protected]" })] 
    public class PushHandlerBroadcastReceiver : GcmBroadcastReceiverBase<GcmService> 
    { 
     public static string[] SENDER_IDS = new string[] { "XXXXX" }; 
     public static string TAG = "PUSH_NOTIFICATIONS"; 
    } 

    [Service] 
    public class GcmService : GcmServiceBase 
    { 
     public static string RegistrationID { get; private set; } 
     private NotificationHub Hub { get; set; } 

     public GcmService() 
      : base(PushHandlerBroadcastReceiver.SENDER_IDS) { } 

     protected override void OnRegistered(Context context, string registrationId) 
     { 
      Log.Verbose(PushHandlerBroadcastReceiver.TAG, "GCM Registered: " + registrationId); 
      RegistrationID = registrationId; 

      Hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, 
           context); 
      try 
      { 
       Hub.UnregisterAll(registrationId); 
       Hub.Unregister(); 
      } 
      catch (Exception ex) 
      { 
       Log.Error(PushHandlerBroadcastReceiver.TAG, ex.Message); 
      } 

      var userId = Settings.UserId; 
      if (! String.IsNullOrWhiteSpace(userId)) 
      { 
       Log.Verbose(PushHandlerBroadcastReceiver.TAG, "Registering user_id: " + userId); 

       var tags = new List<string>() { userId }; 

       try 
       { 
        Hub.Register(registrationId, tags.ToArray()); 
       } 
       catch (Exception ex) 
       { 
        Log.Error(PushHandlerBroadcastReceiver.TAG, ex.Message); 
       } 
      } 
     } 

     protected override void OnMessage(Context context, Intent intent) 
     { 
      Log.Info(PushHandlerBroadcastReceiver.TAG, "GCM Message Received!"); 

      var msg = new StringBuilder(); 

      if (intent != null && intent.Extras != null) 
      { 
       foreach (var key in intent.Extras.KeySet()) 
        msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString()); 
      } 

      string message = intent.Extras.GetString("message"); 
      if (!string.IsNullOrEmpty(message)) 
      { 
       createNotification("New Message", message); 
       return; 
      } 

      Log.Error(PushHandlerBroadcastReceiver.TAG, "Unknown message details: " + msg); 
     } 

     void createNotification(string title, string desc) 
     { 
      //Create notification 
      var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; 

      //Create an intent to show ui 
      var uiIntent = new Intent(this, typeof(MainActivity)); 

      //Use Notification Builder 
      NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 

      //Create the notification 
      //we use the pending intent, passing our ui intent over which will get called 
      //when the notification is tapped. 


      var notification = builder.SetContentIntent(PendingIntent.GetActivity(this, 0, uiIntent, 0)) 
        .SetSmallIcon(Resource.Drawable.ic_stat_ic_notification) 
        .SetTicker(title) 
        .SetContentTitle(title) 
        .SetContentText(desc) 
        //.AddAction(new NotificationCompat.Action()) 


        //Set the notification sound 
        .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification)) 

        //Auto cancel will remove the notification once the user touches it 
        .SetAutoCancel(true).Build(); 

      //Show the notification 
      notificationManager.Notify(1, notification); 
     } 

     protected override void OnUnRegistered(Context context, string registrationId) 
     { 
      Log.Info(PushHandlerBroadcastReceiver.TAG, "Unregistered RegisterationId : " + registrationId); 

      try 
      { 
       Hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, 
           context); 

       Hub.Unregister(); 

       if (!String.IsNullOrWhiteSpace(registrationId)) 
        Hub.UnregisterAll(registrationId); 
      } 
      catch (Exception e) 
      { 
       Log.Error(PushHandlerBroadcastReceiver.TAG, "Error while unregistering: " + e.Message); 
      } 
     } 

     protected override void OnError(Context context, string errorId) 
     { 
      Log.Error(PushHandlerBroadcastReceiver.TAG, "GCM Error: " + errorId); 
     } 
    } 
} 

Теперь, когда пользователь вошел в систему приложение, которое я называю:

DependencyService.Get<IPushNotificationService>().Register(); 

И когда он вошел, что я называю:

Теперь, когда пользователь вошел в приложение я называю:

DependencyService.Get<IPushNotificationService>().UnRegister(); 

Что я делаю неправильно здесь? Когда пользователь вышел из системы, я вижу в отладке, что все методы Unregister вызываются, но пользователь все еще получает новые сообщения.

Thanks, Seif.

ответ

2

Может быть, проблема в линии:

Hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, 
          context); 

Вы создаете новый объект NotificationHub, который не может быть ссылающегося первоначальное соединение.

Вы можете создать собственное поле NotificationHub _hub; установить его значение на этапе регистрации; и используйте это поле на незарегистрированном этапе:

  _hub.Unregister(); 

      if (!string.IsNullOrWhiteSpace(registrationId)) 
       _hub.UnregisterAll(registrationId); 

отказ от ответственности: не пробовал это решение. Надеюсь, поможет.

+0

Это именно то, как я его исправил. Большое спасибо. – iseif

 Смежные вопросы

  • Нет связанных вопросов^_^