2016-04-26 36 views
3

我需要postNotification在我的本機應用程序的Android。OneSignal postNotification的Android

我有這樣的代碼,但它不工作:

try { 
    OneSignal.postNotification(new JSONObject("{'contents': {'en':'Test Message'}, 'include_player_ids': ['" + userId + "']}"), null); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

回答

3

你可以確保在userId值是在您的帳戶有效OneSignal ID,它是訂閱?

您也可以使用下面的代碼,而不是添加的logcat日誌調試問題。

try { 
    OneSignal.postNotification(new JSONObject("{'contents': {'en':'Test Message'}, 'include_player_ids': ['" + "userId" + "']}"), 
    new OneSignal.PostNotificationResponseHandler() { 
     @Override 
     public void onSuccess(JSONObject response) { 
     Log.i("OneSignalExample", "postNotification Success: " + response.toString()); 
     } 
     @Override 
     public void onFailure(JSONObject response) { 
     Log.e("OneSignalExample", "postNotification Failure: " + response.toString()); 
     } 
    }); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
0

這爲我工作, 檢查是否創建ID然後張貼通知

OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() { 
      @Override 
      public void idsAvailable(String userId, String registrationId) { 
       Log.d("debug", "UserId:" + userId); 
       if (registrationId != null) { 
        String msg_welcome = getResources().getString(R.string.msg_welcome); 
        Log.d("debug", "registrationId:" + registrationId); 
        try { 
         OneSignal.postNotification(new JSONObject("{'contents': {'en': '"+ msg_welcome +"'}, 'include_player_ids': ['" + userId + "']}"), 
           new OneSignal.PostNotificationResponseHandler() { 
            @Override 
            public void onSuccess(JSONObject response) { 
             Log.i("OneSignalExample", "postNotification Success: " + response.toString()); 

            } 

            @Override 
            public void onFailure(JSONObject response) { 
             Log.e("OneSignalExample", "postNotification Failure: " + response.toString()); 
            } 
           }); 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     });