我知道发生错误是因为我试图在主线程上进行网络调用,所以我需要使用处理程序或异步任务
但是我似乎无法做到这一点
这是我试图开始工作的代码
try {
// Create a URL for the desired page
URL url = new URL("http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
eventText.setText(str);
eventText.setText(in.readLine());
}
in.close();
} catch (MalformedURLException e) {
Toast.makeText(getBaseContext(), "MalformedURLException", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getBaseContext(), "IOException", Toast.LENGTH_LONG).show();
}
我想在单击此按钮时调用它
public void onClick(View v) {
if (v.getId() == R.id.update) {
}
}
有谁能够告诉我应该将第一个部分包含在内以及如何从 onClick 中调用它
最佳答案
类似
public class TalkToServer extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... params) {
//do your work here
return something;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// do something with data here-display it or send to mainactivity
}
在 doInBackground()
中完成所有繁重的工作,您可以在其他 3 种方法中更新 UI。
<强> Here 是AsyncTask的文档
关于java - 使用处理程序/AsyncTask 或类似的程序来运行网络任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13882095/