我有一个应用程序,它使用计时器每 0.5 秒发送一个 HTTP 请求。我将它放在 asyncTask 中,并在 onPostExecute 完成后从输出中读取数据。一段时间后,我的应用程序开始滞后,用户界面变慢。你知道它为什么会发生以及如何正确地做到这一点吗?
public class Komunikace extends AsyncTask<String, Void, String> {
public static KomunikaceInterface delegate=null;
//ProgressDialog progress;
String response = "";
String url = "";
DefaultHttpClient client;
HttpGet httpGet;
HttpResponse execute;
InputStream content;
BufferedReader buffer;
String s = "";
protected String doInBackground(String... params)
{
url = params[0];
client = new DefaultHttpClient();
httpGet = new HttpGet(url);
try {
execute = client.execute(httpGet);
content = execute.getEntity().getContent();
buffer = new BufferedReader(new InputStreamReader(content));
while ((s = buffer.readLine()) != null) {
response += s + "\n";
}
} catch (Exception e) {
e.printStackTrace();
}
client.getConnectionManager().shutdown();
return response;
}
protected void onPreExecute()
{
super.onPreExecute();
}
protected void onPostExecute(String result)
{
delegate.processFinish(result); // prijata tabulka
}
}
这是我的 asyncTask 类。然后我这样称呼它:
tajmr = new Timer();
tajmr.schedule(new TimerTask() {
@Override
public void run() {
CallWebService();
}
}, 0, 100);
然后这个电话:
private void CallWebService()
{
this.runOnUiThread(fetchData);
}
private Runnable fetchData = new Runnable() {
public void run() {
try
{
updateURL =url;
Komunikace komunikace= new Komunikace();
komunikace.execute(updateURL);
}
catch (Exception e)
{
}
}
};
看起来它在某个地方循环,一段时间后它变慢了。这例如需要 1 分钟。