Question

I understand this problem has been asked multiple times, but the other solutions don't seem to help me as my code is quite specific. I am trying to monitor my network bandwidth and quality, and I have looked at example code regarding how to do that on StackOverflow.

The following is what I have (a lot of it is owned by members on SO), in my MainActivity.java class:

public class MainActivity extends Activity {

@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final String TAG = "test";
    long startTime;
    long endTime;
    BufferedHttpEntity bufHttpEntity;
    float bandwidth;
    try {
        startTime = System.currentTimeMillis();
        String urlString = "http://www.google.com";
        HttpGet httpRequest = new HttpGet(new URL(urlString).toURI());
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpClient.execute(httpRequest);
        endTime = System.currentTimeMillis();

        HttpEntity entity = response.getEntity();
        bufHttpEntity = new BufferedHttpEntity(entity);
        //You can re-check the size of your file
        final long contentLength = bufHttpEntity.getContentLength();

        // Log
        Log.d(TAG, "[BENCHMARK] Dowload time :"+(endTime-startTime)+" ms");

        // Bandwidth : size(KB)/time(s)
        System.out.println("here");
        bandwidth = contentLength / ((endTime-startTime) *1000);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        bandwidth = -1;
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        bandwidth = -1;
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        bandwidth = -1;
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        bandwidth = -1;
        e.printStackTrace();
    }    

    int linkSpeed;
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (wifiInfo != null) {
        linkSpeed = wifiInfo.getLinkSpeed(); //measured using WifiInfo.LINK_SPEED_UNITS
    }
    else {
        linkSpeed = -1;
    }

    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(25);
    textView.setText("Linkspeed = " + linkSpeed + "\nbandwidth = " + bandwidth);

    // Set the text view as the activity layout
    setContentView(textView);
}


//Set up the {@link android.app.ActionBar}, if the API is available.
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }
}

I have done error checking, and I found 2 problems.

  1. The call "WifiInfo wifiInfo = wifiManager.getConnectionInfo()" causes the "unfortunately, xxx has stopped" error, resulting in my emulator crashing. I can't seem to get around what the issue with this is; I don't think I need to throw a try-catch block...?

  2. A similar "unfortunately, xxx has stopped" error occurs when I input a website in urlString. When I leave the field blank, the bandwidth becomes -1, as no website gets specified, and an Exception gets thrown.


06-26 19:10:15.164: D/AndroidRuntime(2402): Shutting down VM
06-26 19:10:15.203: W/dalvikvm(2402): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-26 19:10:15.244: E/AndroidRuntime(2402): FATAL EXCEPTION: main
06-26 19:10:15.244: E/AndroidRuntime(2402): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.networkinfo/com.example.networkinfo.MainActivity}: android.os.NetworkOnMainThreadException
06-26 19:10:15.244: E/AndroidRuntime(2402):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at android.os.Looper.loop(Looper.java:137)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at android.app.ActivityThread.main(ActivityThread.java:5041)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at java.lang.reflect.Method.invokeNative(Native Method)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at java.lang.reflect.Method.invoke(Method.java:511)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at dalvik.system.NativeStart.main(Native Method)
06-26 19:10:15.244: E/AndroidRuntime(2402): Caused by: android.os.NetworkOnMainThreadException
06-26 19:10:15.244: E/AndroidRuntime(2402):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at com.example.networkinfo.MainActivity.onCreate(MainActivity.java:46)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at android.app.Activity.performCreate(Activity.java:5104)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-26 19:10:15.244: E/AndroidRuntime(2402):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-26 19:10:15.244: E/AndroidRuntime(2402):     ... 11 more
Was it helpful?

Solution

The call "WifiInfo wifiInfo = wifiManager.getConnectionInfo()" causes the "unfortunately, xxx has stopped" error, resulting in my emulator crashing. I can't seem to get around what the issue with this is; I don't think I need to throw a try-catch block...?

Where's the logcat for this? Possibly: does your app have ACCESS_NETWORK_STATE permission?

A similar "unfortunately, xxx has stopped" error occurs when I input a website in urlString. When I leave the field blank, the bandwidth becomes -1, as no website gets specified, and an Exception gets thrown.

Don't do network operations on the UI thread. Easy solution is to use an AsyncTask to do them on a background thread. For more info: How to fix android.os.NetworkOnMainThreadException?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top