0

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!

Joe C
  • 2,757
  • 2
  • 26
  • 46
  • This is a common question. See: http://stackoverflow.com/questions/6976317/android-http-connection-exception – Scott Jul 02 '13 at 00:28

1 Answers1

0

Did you add <uses-permission android:name="android.permission.INTERNET" /> on your manifest ?

IronBlossom
  • 3,898
  • 3
  • 35
  • 42
  • I did. I solved my problem in terms of the link http://stackoverflow.com/questions/6976317/android-http-connection-exception – Joe C Jul 09 '13 at 01:25