1

我知道这个问题已被多次询问,但其他解决方案似乎对我没有帮助,因为我的代码非常具体。我正在尝试监控我的网络带宽和质量,并且我查看了有关如何在 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 已停止”错误,导致我的模拟器崩溃。我似乎无法解决这个问题。我认为我不需要抛出 try-catch 块......?

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


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
4

1 回答 1

1

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

这个的logcat在哪里?可能:你的应用有ACCESS_NETWORK_STATE权限吗?

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

不要在 UI 线程上进行网络操作。简单的解决方案是使用一个AsyncTask在后台线程上执行它们。有关更多信息:如何修复 android.os.NetworkOnMainThreadException?

于 2013-06-27T09:17:19.027 回答