FirebaseMessagingService使用齐射的字符串请求不起作用

时间:2017-05-08 19:11:04

标签: android firebase android-volley firebase-cloud-messaging

当我使用volley向服务器发送请求时,它不起作用并引发运行时错误。

public class MyFCMService extends FirebaseMessagingService {
    String url, title, message;
    String category_id;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    title = remoteMessage.getData().get("title");
    message = remoteMessage.getData().get("message");

    String id = remoteMessage.getData().get("ID");

    if (check(id).equals("6")) {
        sendNotification(title, message);
    } else {
        sendNotification("khalid", "khalid");
    }
}

public String check(String id) {
    url = "http://www.tobeacademy.com/api/get_post/?post_id=" + id;
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray array = jsonObject.getJSONArray("post");
                        category_id = array.getJSONObject(0).getString("id");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });
    Volley.newRequestQueue(this).add(stringRequest);

    return category_id;
}

1 个答案:

答案 0 :(得分:0)

Volley请求异步完成。在从onResponse()服务器收到重新获取的数据之前,侦听器的tobeacademy方法不会执行。

这意味着在check()方法中,category_id返回的值无效,因为它是在侦听器onResponse()执行并定义之前返回的。

您需要将代码重构为以下内容:

public void check(String id, final String title, final String message) {
    url = "http://www.tobeacademy.com/api/get_post/?post_id=" + id;

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray array = jsonObject.getJSONArray("post");

                        String category_id = array.getJSONObject(0).getString("id");

                        if (category_id.equals("6")) {
                            sendNotification(title, message);
                        } else {
                            sendNotification("khalid", "khalid");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });
    Volley.newRequestQueue(this).add(stringRequest);
}