现在我正在解决
android.os.NetworkOnMainThreadException
我将connect方法放入分离的线程中,但是当线程启动时,start()
方法不会调用Run()
,
- 并且还使用AsyncTask
,任务不会调用doInBackground()
方法!
public class ConnectTask extends AsyncTask<URL, Integer, HttpEntity> {
HttpEntity entity;
String statue;
LogInJSONActivity mainActivity;
@Override
protected HttpEntity doInBackground(URL... arg0) {
// TODO Auto-generated method stub
mainActivity.setString("Inside Do in background");
entity = connect(arg0[0]);
mainActivity.setHttp(entity);
return entity;
}
public HttpEntity connect(String url) {
statue= "Inside Connect";
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
HttpEntity entity = null;
try {
response = httpclient.execute(httpget);
entity = response.getEntity();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return entity;
}
public void setActivity(LogInJSONActivity act){
mainActivity = act;
}
}
URL url = null;
try {
url = new URL("http://www.flickr.com/photos/51469488@N03/");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ConnectTask backgroundTask = (ConnectTask) new ConnectTask();
backgroundTask.setActivity(this);
backgroundTask.execute(url);
public class ConnectThread extends Thread {
HttpEntity entity;
String statue;
LogInJSONActivity mainActivity;
@Override
public void run() {
// TODO Auto-generated method stub
mainActivity.setString("Inside Run");
entity = connect("http://www.flickr.com/photos/51469488@N03/");
mainActivity.setHttp(entity);
super.run();
}
public HttpEntity connect(String url) {
statue= "Inside Connect";
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
HttpEntity entity = null;
try {
response = httpclient.execute(httpget);
entity = response.getEntity();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(entity !=null)
System.out.print("Valid Entity");
else
System.out.print("Null Entity");
return entity;
}
public void setActivity(LogInJSONActivity act){
mainActivity = act;
}
}
ConnectThread t = new ConnectThread();
t.setActivity(this);
t.start();
答案 0 :(得分:0)
您的error
可能是因为您在Network
UI
上进行了thread
次操作,API 11
不允许这样做。我会说不是要创建单独的Thread
,只需使用AsyncTask
课程来执行Network
operation
。只需在doInBackground()
中进行网络操作,然后从UI线程调用AsyncTask类,
new YourAsyncTask().execute(url);
通过创建一个单独的Thread
类并使其更复杂,所有这些都不需要付出太多努力。