这是我的代码。为什么这个应用程序在更新期间挂起异步实现是错误的吗? 在这个应用程序中,我有一个列表。此列表的内容是来自我的服务器的响应正文。我使用OkHttpClient库
public class MainActivity extends AppCompatActivity {
private MyContinousAsyncTask myContinouslyRunningAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
myContinouslyRunningAsyncTask = new MyContinousAsyncTask();
myContinouslyRunningAsyncTask.execute("execute");
}
String run(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
private void refresh() throws IOException {
final ListView listview = (ListView) findViewById(R.id.lvChat);
String url = "???"; //hidden
String code = run(url);
String[] values = code.split("<break>");
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
// list.add(code);
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
}
适配器类:
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
@Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
@Override
public boolean hasStableIds() {
return true;
}
}
AsyncTask类:
public class MyContinousAsyncTask extends AsyncTask<String, Void, String> {
Timer timer;
TimerTask timerTask;
@Override
protected String doInBackground(String... params) {
timer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
refresh();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 100, 5000);
return "execute";
}
}
}
请帮忙