您必须使用自己的线程。这是使用 AsyncTask 的解决方案....
所有代码都放在您的 Activity 类中。
public void toCallAsynchronous() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
MyAsyncTask task = new MyAsyncTask();
task.execute(txtSearchField.getText().toString());
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 2000); // execute in every 2 second
}
// 异步任务类
private class MyAsyncTask extends AsyncTask<String, Object, List<ModelObject>> {
@Override
protected List< ModelObject > doInBackground(String... params) {
// Call web service
return null;
}
@Override
protected void onPostExecute(List< ModelObject > result) {
super.onPostExecute(rezultat);
// Update UI
}
}