我正在尝试将某些网站的代码下载到我的应用中:
public void wypned(final View pwn) throws IllegalStateException, IOException{
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://example.com");
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent() ) );
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
}
我所得到的只是致命的错误。 LogCat说:
Caused by: android.os.NetworkOnMainThreadException
on Android 3.x and up, you can't do network I/O on the main thread
有人能告诉我如何解决它吗?我试图用线程做一些事情,但它没有成功。
答案 0 :(得分:2)
实现asyncTask:
public class MyAsyncTask extends AsyncTask<Void, Void, Result>{
private Activity activity;
private ProgressDialog progressDialog;
public MyAsyncTask(Activity activity) {
super();
this.activity = activity;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(activity, "Loading", "Loading", true);
}
@Override
protected Result doInBackground(Void... v) {
//do your stuff here
return null;
}
@Override
protected void onPostExecute(Result result) {
progressDialog.dismiss();
Toast.makeText(activity.getApplicationContext(), "Finished.",
Toast.LENGTH_LONG).show();
}
}
从活动中调用它:
MyAsyncTask task = new AsyncTask(myActivity.this);
task.execute();
答案 1 :(得分:0)