I am learning Android development, and confronted a problem.
I am using Eclipse ADT in both 64bit windows 7 and ubuntu 12.04. In Android Virtual Device (AVD), I can access internet via pre-installed browsers. However, my own application cannot use http in AVD, although it works in my real android phone.
The following is my code (almost from the android guide---http://developer.android.com/shareables/training/NetworkUsage.zip).
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String x = networkInfo.getTypeName();
try{
URL url = new URL("http://www.sina.com.cn");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
}
I debugged the code in AVD, networkInfo.isConnected() returns true. Future debugging shows the connection type is mobil, not wifi (by using notworkInfo.getType()). But, conn.connect() raises android.os.NetworkOnMainTHreadException. I also tried HttpClient, it also fails with the same exception.
Can anyone help? Thank you!