php服务器和android java之间的实时json通信

时间:2017-11-07 01:10:55

标签: java php android json

我有一个java代码,通过向服务器发送数据,从php服务器接受jsonObject到我的android应用程序:

requestQueue = Volley.newRequestQueue(this);

    request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);

                user_id = jsonObject.getJSONObject("user").getInt("user_id");;
                textView.setText(jsonObject.getString("msg"));

                saveInfo();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //Toast.makeText(context, "Please check your internet connection.", Toast.LENGTH_LONG).show();
            AlertDialog.Builder a_builder = new AlertDialog.Builder(getApplicationContext());
            a_builder.setMessage("Please check your internet connection.").setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            AlertDialog alertDialog = a_builder.create();
            alertDialog.setTitle("Network failure!");
            alertDialog.show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> hashMap = new HashMap<String, String>();

            hashMap.put("username", "testing");
            hashMap.put("password", "testing");

            return hashMap;
        }
    };
    requestQueue.add(request);

现在,如何在没有任何用户操作的情况下实时从服务器接收jsonObject? 当来自服务器的数据发生变化时,自动更新我的Android应用程序中的数据。

0 个答案:

没有答案