OneSignal postNotification Android

时间:2016-04-26 09:58:52

标签: android push onesignal

我的原生app android中需要postNotification

我有这段代码,但它不起作用:

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

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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();
                    }
                }
            }
        });