我知道发生错误是因为IM试图在主线程上放置网络调用,所以我需要使用处理程序或异步任务
但是我似乎无法正确处理
这是我试图开始工作的代码
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。
这是关于 AsyncTask 的文档
在 onClick 方法中创建并实例化 AsyncTask。将 url 调用的调用(和等待)放在 doOnBackground 方法中,并在 onPostExecute 中对响应执行任何您想要的操作(这再次发生在主线程中)。