如何使用片段中的AsyncTask每n秒从URL解析JSON?

时间:2013-11-27 10:28:33

标签: android json android-asynctask

我想每隔几秒解析一次JSON。我的想法是不断解析它以查看它是否有一些变化,是否有获取它们并更新我的观点(主要是TextView s)。我有一个名为MyFragment的Fragment。在onCreateView我正在执行以下操作:new MyTask().execute(myJSONUrl);。一些代码:

        class MyTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {

            //getJSONString(String url) - my method for getting the JSON from URL
            return getJSONString(params[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

        if (result == null || result.length() == 0) {
                Log.w(TAG," JSON IS **null** ");
                Toast.makeText(getActivity().getApplicationContext(), "JSON IS NULL", Toast.LENGTH_SHORT).show();
            } else {
                     try{
                           JSONObject root = new JSONObject(result);

                            // Here i get what i need from the JSONObject and everything works fine.

                         } catch (Exception e) {
                    e.printStackTrace();
                         }
        }

现在如何每隔n秒从URL解析JSON?我尝试过使用ScheduledExecutorService,Timer和Thread,但似乎没有任何效果。在此先感谢: - )

1 个答案:

答案 0 :(得分:1)

当你真的把电池问题扔出窗外时:

class MyTask extends AsyncTask<String, Void, String>更改为class MyTask extends AsyncTask<String, String, Void>

执行以下操作:

protected String doInBackground(String... params) {

  //getJSONString(String url) - my method for getting the JSON from URL
  while(isCancelled() == false) {
    try {
      Thread.sleep(1000* 5); // only do this every 5 seconds.
    } catch (InterruptException ex) {}
    publishResult(getJSONString(params[0]));
  }
}
public void onResultPublished(String result) {
  // stuff that happened in onResult before...
}

你发出字符串作为结果并在onResultPublished中处理它(这个方法在UI线程上执行,所以在这里修改ui是安全的。)

不要忘记取消asynctask。