如果使用凌空响应有新数据,如何更新ui?

时间:2016-02-15 12:39:20

标签: android android-volley

我有一个代码从Web服务获取数据并在textview中显示响应。但是,如果Web服务中的数据发生更改,我希望能够使用新数据更新我的textview,并可能播放指示存在新数据的通知声音。我已经尝试进行轮询,我将每隔x秒向Web服务发送一次数据请求。但问题是,几分钟后,我的应用程序崩溃是因为内存不足。另外,关于通知声音,我的想法是,如果textview值改变,那么只有声音播放或警报对话框才会出现。在我的情况下发生的事情是,因为我每隔x秒轮询一次,然后textview每隔x秒刷新一次,导致每隔x秒出现一次警告对话框。我用它来达到我想要的最佳方法是什么?

ParseJson

public class ParseJson {
public static String[] playing;

public static final String JSON_ARRAY = "result";
public static final String RESULT_ID = "playing";

private JSONArray users = null;

private String json;

public ParseJson(String json){
    this.json = json;
}

public void parseJSON(){
    JSONObject jsonObject=null;
    try {
        jsonObject = new JSONObject(json);
        users = jsonObject.getJSONArray(JSON_ARRAY);

        playing = new String[users.length()];

        for(int i=0;i<users.length();i++){
            JSONObject jo = users.getJSONObject(i);
            playing[i] = jo.getString(RESULT_ID);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    }
} 

MainActivity

public class MainActivity extends AppCompatActivity {

public TextView text;

MediaPlayer mp;

public static final String JSON_URL = "http://172.16.51.118/androidphp/data.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    text = (TextView) findViewById(R.id.text);
    text.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("Response")
                    .setMessage("text has changed")
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // continue with delete
                        }
                    })
                    .setIcon(android.R.drawable.btn_star)
                    .show();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    handleMe();
}

public void handleMe() {
    Timer timer = new Timer();
    final Handler handler = new Handler(){


        @Override
        public void handleMessage(Message msg) {
            // do something on UI

        }

    };
    TimerTask task = new TimerTask () {
        @Override
        public void run () {
            //send volley request here
            //RequestData requestData = new RequestData(MainActivity.this);
            //requestData.sendRequest(text);
            //text.setText(ParseJson.playing[0]);
            /*(RequestData requestData = new RequestData(MainActivity.this);
            requestData.sendRequest();*/
            sendRequest();
        }
    };
    timer.schedule(task, 0, 10000); // 60000 is time in ms
}

public void sendRequest(){

    //While the app fetched data we are displaying a progress dialog
    //final ProgressDialog loading = ProgressDialog.show(this,"Fetching Data","Please wait...",false,false);

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

                    //text.setText(response);

                    //loading.dismiss();
                    showJSON(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
    requestQueue.add(stringRequest);
}

private void showJSON(String json){
    ParseJson pj = new ParseJson(json);
    pj.parseJSON();
    text.setText(ParseJson.playing[0]);
    }
}

1 个答案:

答案 0 :(得分:1)

您不应每X秒请求一次服务器。您可以使用Google的GCM Api直接在设备上发送数据包。看看the doc

否则,您可以执行单个操作,例如here,以避免每个请求重新分配队列。