2

我正在使用Azure通知中心和Androud GCM處理Xamarin.Forms應用程序。現在,當我的用戶註冊我把他記錄下來的通知:如何從推送通知中註銷客戶端?

我有一個接口:

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視爲在Azure MSDN站點中偵聽:

[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方法都被調用,但用戶仍在收到新消息。

謝謝, Seif。

回答

2

也許問題是在該行:

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

您正在創建的NotificationHub可能不被引用的初始連接一個新的對象。

您可以嘗試創建一個字段NotificationHub _hub;在登記步驟中設定其值;並在取消註冊步驟中使用此字段:

  _hub.Unregister(); 

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

聲明:未嘗試此解決方案。希望能幫助到你。

+0

這正是我如何修復它。非常感謝。 – iseif

相關問題