监控网络带宽的问题

时间:2013-06-26 19:05:50

标签: java android network-programming bandwidth wifimanager

我理解这个问题已被多次询问,但其他解决方案似乎对我没有帮助,因为我的代码非常具体。我正在尝试监控我的网络带宽和质量,我已经查看了有关如何在StackOverflow上执行此操作的示例代码。

我的MainActivity.java类中包含以下内容(很多内容由SO成员拥有):

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);
    }
}

我做了错误检查,发现了2个问题。

  1. 电话" WifiInfo wifiInfo = wifiManager.getConnectionInfo()"导致"不幸的是,xxx已停止"错误,导致我的模拟器崩溃。我似乎无法解决这个问题;我不认为我需要抛出一个试试块......?

  2. 类似的"不幸的是,xxx已经停止了#34;我在urlString中输入网站时出错。当我将该字段留空时,带宽变为-1,因为没有指定网站,并且抛出异常。


  3. 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
    

1 个答案:

答案 0 :(得分:1)

  

调用“WifiInfo wifiInfo = wifiManager.getConnectionInfo()”导致“不幸的是,xxx已停止”错误,导致我的模拟器崩溃。我似乎无法解决这个问题;我认为我不需要抛出try-catch块......?

这是什么logcat?可能:您的应用是否有ACCESS_NETWORK_STATE权限?

  

当我在urlString中输入网站时,出现类似的“不幸的是,xxx已停止”错误。当我将该字段留空时,带宽变为-1,因为没有指定网站,并且抛出异常。

不要在UI线程上进行网络操作。简单的解决方案是使用AsyncTask在后​​台线程上执行它们。有关详细信息:How to fix android.os.NetworkOnMainThreadException?