我正在编写一个从 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/