1

晴れのモバイルアプリを使用する方法を学習しようとしていますが、NotificationHubの使用に深刻な問題があります。私はAzureへの購読を想像しています。ぼんやりしたバックエンドを使用してandroidモバイルアプリを作成します。私は紺碧のポータルの紺碧のモバイルアプリに関連付けられた通知ハブを作成しました。 は、私がこのチュートリアルのコードを使用した通知ハブにアプリを登録するには:紺碧の通知ハブを使用して特定のユーザープッシュ通知を受け取ることができません

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

ユーザーがpreviuosly、マイクロソフトアカウントまたはFacebookのアカウントを自分のGoogleアカウントを使用して、紺碧のバックエンドでを認証されます。新しいユーザーは、テーブルスクリプトUsers.js用に作成された次のノードjsコードによって、テーブルUsersに挿入されます。 プッシュ通知で新しいユーザーへようこそ。 How to use the Azure Mobile Apps Node.js SDK

にチュートリアルで「とき認証されたユーザプッシュ通知のためのレジスタ、ユーザーIDタグは次のとおりです。「タグを使用して認証されたユーザーにプッシュ通知を送信する方法を」による

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; 

自動的にを登録に追加しました。 " このチュートリアルで示唆しているように、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 Server Explorerに表示されているタグを確認してください。[link](https://msdn.microsoft.com/en-us/) /library/azure/dn530751.aspx)、**無料のImagine Subscription **を使用していますか?残念ながら、このサブスクリプションではVisual Studioのサーバーエクスプローラで通知ハブを表示できません:( – CatLog02

+0

Visual Studioを起動し、 'view'をクリックして' Server Explorer'を見つけ、Azureにログインして通知ハブを見つけてください。 –

関連する問題