1

我想學習使用azure移動應用程序,但我在使用NotificationHub時遇到嚴重問題。我有一個Imagine訂閱Azure。我使用天藍色後端創建了一個移動應用程序Android。我創建了一個與Azure門戶上的Azure移動應用關聯的通知中心。 要註冊在我使用的代碼本教程中的通知集線器應用程式:使用天藍色的通知集線器無法接收特定的用戶推送通知

https://docs.microsoft.com/en-gb/azure/notification-hubs/notification-hubs-android-push-notification-google-fcm-get-started

用戶previuosly通過使用他們的谷歌帳戶,Microsoft帳戶或Facebook帳戶認證對天青後端。通過爲表腳本Users.js編寫的以下節點js代碼將新用戶插入到表Users中。我想要一個推送通知來歡迎新用戶

var azureMobileApps = require('azure-mobile-apps'); 
var logger = require('azure-mobile-apps/src/logger'); 
var table = azureMobileApps.table(); 

table.access = 'authenticated'; 

/** 
* Adds the email address from the claims to the context item - used for 
* insert operations 
* @param {Context} context the operation context 
* @returns {Promise} context execution Promise 
*/ 
function addEmailToContext(context) { 
    /* 
    * Getting claim fields 
    */ 
    return context.user.getIdentity().then((data) => { 
     if(data.microsoftaccount != undefined){ 
      context.item.email = data.microsoftaccount.claims.emailaddress; 
      context.item.name = data.microsoftaccount.claims.givenname; 
      context.item.surname = data.microsoftaccount.claims.surname;   
     } 
     if(data.google != undefined){ 
      context.item.email = data.google.claims.emailaddress; 
      context.item.name = data.google.claims.givenname; 
      context.item.surname = data.google.claims.surname; 
      context.item.picture_url = data.google.claims.picture; 
     } 
     if(data.facebook != undefined){ 
      context.item.email = data.facebook.claims.emailaddress; 
      context.item.name = data.facebook.claims.givenname; 
      context.item.surname = data.facebook.claims.surname; 
     } 

     logger.info('[tables/Users.js] --> NEW USER REGISTERED:' 
       +'\n\t Name:'+context.item.name 
       +'\n\t Surname:'+context.item.surname 
       +'\n\t Email:'+context.item.email); 


    // Execute the insert. The insert returns the results as a Promise, 
    // Do the push as a post-execute action within the promise flow. 
    return context.execute() 
     .then(function (results) { 
      // Only do the push if configured 
      if (context.push) { 
       // Mobile Apps adds a user tag when registering for push notifications 

       // Define the GCM payload. 
       var payload = { 
        "data": { 
         "message": 'Welcome '+context.item.username 
        } 
       };  

       context.push.gcm.send(context.user.id, payload, function (error) { 
        if (error) { 
         logger.error('Error while sending push notification: ', error); 
        } else { 
         logger.info('Push notification sent successfully!'); 
        } 
       }); 
      } 
      // Don't forget to return the results from the context.execute() 
      return results; 
     }) 
     .catch(function (error) { 
      logger.error('Error while running context.execute: ', error); 
     }); 
    }); 
} 

// CREATE - add or overwrite the authenticated user 
table.insert(addEmailToContext); 

module.exports = table; 

據「如何:發送推送通知到使用標籤的認證用戶」的教程How to use the Azure Mobile Apps Node.js SDK

「當身份驗證的用戶推送通知寄存器,用戶ID標籤自動將添加到註冊中。「 因此,在Users.js中,按照本教程中的建議,我編寫了以下代碼以將推送通知發送給用戶。

context.push.gcm.send(context.user.id, payload, function (error) { 
        if (error) { 
         logger.error('Error while sending push notification: ', error); 
        } else { 
         logger.info('Push notification sent successfully!'); 
        } 
       }); 

使用此代碼,推送通知結果將成功發送,但設備不會收到任何通知。如果我使用空,而不是context.user.id的那麼所有設備上正確收到推送通知:

context.push.gcm.send(null, payload, function (error) { 
        if (error) { 
         logger.error('Error while sending push notification: ', error); 
        } else { 
         logger.info('Push notification sent successfully!'); 
        } 
       }); 

我也試圖調用以下自定義API,當用戶註冊到中心來創建標籤。被調用的API如下:

var logger = require('azure-mobile-apps/src/logger'); 

exports.post = function(req, res) { 
    logger.info('[api/registerTag.js] --> Invoked'); 

     // Get the notification hub used by the mobile app. 
     var push = req.azureMobile.push, 
      installationId = req.get('X-ZUMO-INSTALLATION-ID'), 
      tags = req.body.tag.toString(); 



     // Define an update tags operation. 
     var updateOperation = [{ 
      "op": "add", 
      "path": "/tags", 
      "value": tags 
     }]; 

     // Update the installation to add the new tags. 
     push.patchInstallation(installationId, updateOperation, function(error) { 
      if(error){ 
       logger.error('[api/registerTag.js] --> An error occurred while adding' 
          +'the following tags: \n\t'+tags, error); 
       res.status(error.statusCode).send(error.detail); 
      } else { 
       logger.info('[api/registerTag.js] --> The following tags have been added' 
          +'to the Notification Hub: \n\t'+tags, error); 
       res.status(200).send(tags); 
      } 
     }); 
}; 

在控制檯上顯示標籤已成功添加。但是,如果我然後修改Users.js代碼是這樣的:

... 
// Only do the push if configured 
      if (context.push) { 
       // Mobile Apps adds a user tag when registering for push notifications 
       var userTag = '_UserId:' + context.user.id; 
       logger.info("TAG "+userTag); 

       // Define the GCM payload. 
       var payload = { 
        "data": { 
         "message": 'Welcome '+context.item.username 
        } 
       };  

       context.push.gcm.send(userTag, payload, function (error) { 
        if (error) { 
         logger.error('Error while sending push notification: ', error); 
        } else { 
         logger.info('Push notification sent successfully!'); 
        } 
       }); 
      } 
... 

再次沒有收到任何東西。我也曾嘗試白名單標籤或自動添加他們使用移動應用的推動部分像顯示的圖像:

圖像鏈接:i.stack.imgur.com/KBvQI.png

但問題是還在那兒。希望可以有人幫幫我。謝謝。

回答

0

經過多次測試,我成功地再現了您的問題,並得到同樣的問題。爲了達到您的要求,我在Android客戶端做了一些修改:

1,MainActivity類中的高速緩存驗證用戶。以下是我的代碼片段。欲瞭解更多詳情,你可以參考here

public static final String SHAREDPREFFILE = "temp";  
public static final String USERIDPREF = "uid";  
public static final String TOKENPREF = "tkn"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    try { 
     // Create the Mobile Service Client instance, using the provided Mobile Service URL and key 
     mClient = new MobileServiceClient(
       "https://yourwebsitename.azurewebsites.net", 
       this).withFilter(new ProgressFilter()); 

     // Extend timeout from default of 10s to 20s 
     mClient.setAndroidHttpClientFactory(new OkHttpClientFactory() { 
      @Override 
      public OkHttpClient createOkHttpClient() { 
       OkHttpClient client = new OkHttpClient(); 
       client.setReadTimeout(20, TimeUnit.SECONDS); 
       client.setWriteTimeout(20, TimeUnit.SECONDS); 
       return client; 
      } 
     }); 

     authenticate(); 

    } catch (MalformedURLException e) { 
     createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error"); 
    } catch (Exception e){ 
     createAndShowDialog(e, "Error"); 
    } 
} 

private void authenticate() { 
    // We first try to load a token cache if one exists. 
    if (loadUserTokenCache(mClient)) { 
     createTable(); 
     register(); 
    } 
    // If we failed to load a token cache, login and create a token cache 
    else { 
     // Login using the Google provider. 
     ListenableFuture<MobileServiceUser> mLogin = mClient.login(MobileServiceAuthenticationProvider.Google); 

     Futures.addCallback(mLogin, new FutureCallback<MobileServiceUser>() { 
      @Override 
      public void onFailure(Throwable exc) { 
       createAndShowDialog("You must log in. Login Required", "Error"); 
      } 
      @Override 
      public void onSuccess(MobileServiceUser user) { 
       createAndShowDialog(String.format("You are now logged in - %1$2s", user.getUserId()), "Success"); 
       cacheUserToken(mClient.getCurrentUser()); 
       createTable(); 
       register(); 
      } 
     }); 
    } 
} 

private void cacheUserToken(MobileServiceUser user) { 
    SharedPreferences prefs = getSharedPreferences(SHAREDPREFFILE, Context.MODE_PRIVATE); 
    Editor editor = prefs.edit(); 
    editor.putString(USERIDPREF, user.getUserId()); 
    editor.putString(TOKENPREF, user.getAuthenticationToken()); 
    editor.commit(); 
} 

private void register() { 
    NotificationsManager.handleNotifications(this, NotificationSettings.SenderId, MyHandler.class); 
    registerWithNotificationHubs(); 
} 

2,在RegistrationIntentService類用下面的代碼替換regID = hub.register(FCM_token).getRegistrationId();

regID = hub.register(FCM_token, prefs.getString("uid", "")).getRegistrationId(); 

3,確保下面添加到第一行線onHandleIntent方法內。

SharedPreferences prefs = getSharedPreferences("temp", Context.MODE_PRIVATE); 
+0

非常感謝!推送通知現在可以按照預期的方式使用'context.push.gcm.send(context.user.id,[...])'。我非常感謝你的幫助:D – CatLog02

+0

還有一件事!您是否知道是否存在任何方法**通過視覺方式調試通知中心**並查看Visual Studio服務器資源管理器中顯示的標籤[鏈接](https://msdn.microsoft.com/en-us /library/azure/dn530751.aspx),但免費的**免費的想象訂閱**?不幸的是,此訂閱不允許我在Visual Studio的服務器資源管理器中查看通知中心:( – CatLog02

+0

)啓動Visual Studio,單擊'view'查找'Server Explorer',登錄到Azure並展開以查找您的通知中心。點擊它將爲您帶來一個窗口,其中包含當前註冊。 –

相關問題