java - Android 中的 AsyncTask 循环

标签 java android

我正在编写一个从 Internet 获取货币价格的程序,并将此代码放在一个异步任务中。我需要能够不断更新,但我不太确定在不搞乱程序的情况下循环异步任务。任何帮助表示赞赏!

我需要这段代码持续运行:

public void parseJSON(){
        new AsyncTask<Void, Void, String>() {
            protected String doInBackground(Void... params) {

                try {
                    return downloadJSON(ticker);
                } catch (Exception e) {
                    Log.d("JWP", e.toString());
                }

                return "Can't reach server. Is Internet access enabled?";
            }

            @Override
            protected void onProgressUpdate(Void... values) {
                TextView textView = (TextView) findViewById(R.id.ltcdata);

                textView.setText("Retrieving Data...");
            }

            @Override
            protected void onPostExecute(String result) {
                TextView textView = (TextView) findViewById(R.id.ltcdata);

                try {
                    JSONObject items = (JSONObject) new JSONTokener(result)
                            .nextValue();

                    String price = items.getJSONObject("ticker").getString(
                            "last");
                    String high = items.getJSONObject("ticker").getString(
                            "high");
                    String low = items.getJSONObject("ticker").getString("low");

                    textView.append("Last Price: $" + price + "\n");
                    textView.append("High: $" + high + "\n");
                    textView.append("Low: $" + low + "\n");

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        }.execute();
    }

最佳答案

为计时器使用一个处理程序。在下面的示例中,它将每 5 秒连续检查一次。

private Handler handler = new Handler();


private Runnable runnable = new Runnable() {

 public void run() {

  parseJSON();

  /*
   * Now register it for running next time
   */

  handler.postDelayed(this, 5000); // the request will be made again 5 sec later
 }


};

使用 runnable.run(); 启动计时器,使用 runnable.removeCallbacks(handler ); 停止计时器。

关于java - Android 中的 AsyncTask 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20233749/

相关文章:

java - 如何在一 block 玻璃板上绘制多个矩形?

java - 在 mysql 查询中传递 java 字符串变量

android - BadParcelableException ClassNotFoundException CoordinatorLayout$SavedState

java - 使用 2 个字符串集(组合它们)

android - 使文本填满编辑文本中的屏幕

java - 从输入创建集合

java - 如何使用 GridBagLayout 设置最小尺寸?

java - 如何在 Jython 中扩展一个 java 类?

android - 动画在 api 响应成功回调中不起作用

java - NoClassDefFoundError 异常 android joda 时间