0

我试图使用以下代码测试我的模拟器的网络状态并允许它android.permission.ACCESS_NETWORK_STATE

public class Main extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean wified = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
        TextView textView = (TextView) findViewById(R.id.textView1);
        if (wified) {
            textView.setText("Wified");
        } else {
            textView.setText("Not connected to wifi");
        }       
    }
    //..
}

当我将它作为 Android 应用程序运行时,我得到Not connected to wifi TextView 消息显示在模拟器上,但是当我使用模拟器连接到 google.com 或 yahoo.com 时,它工作得很好。

有人可以帮我理解为什么我没有连接到 wifi消息吗?

谢谢。

4

3 回答 3

2

尝试添加<uses-permission android:name="android.permission.INTERNET" />

在您的 Android 清单文件中的权限部分。

编辑:- 试试这个..

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo Info = cm.getActiveNetworkInfo();
        if (Info == null || !Info.isConnectedOrConnecting()) {
            Log.i(TAG, "No connection");
        } else {
            int netType = Info.getType();
            int netSubtype = Info.getSubtype();

            if (netType == ConnectivityManager.TYPE_WIFI) {
                Log.i(TAG, "Wifi connection");
             wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
                 int linkSpeed = wifiManager.getConnectionInfo().getLinkSpeed();
            //Need to get wifi strength
        } else if (netType == ConnectivityManager.TYPE_MOBILE) {
          Log.i(TAG, "GPRS/3G connection"); 
           //Need to get differentiate between 3G/GPRS
        } 
    }

当然,在真实设备上检查这个:)

希望这可以帮助。

于 2013-05-08T09:26:46.260 回答
1

因为模拟器无法模拟wifi,请看这个答案和文档。我认为如果您在模拟器中执行此方法,它将始终返回“未连接到 wifi”。

如何在安卓模拟器设备上打开 Wi-Fi?

http://developer.android.com/tools/devices/emulator.html

于 2013-05-08T09:44:09.277 回答
0
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
    StringBuffer networkInfo = new StringBuffer();
    for (NetworkInfo nextNetworkInfo : networkInfos) {
        networkInfo.append(nextNetworkInfo.getTypeName() + ", ");
    }
    TextView textView = (TextView) findViewById(R.id.textView1);
    textView.setText(networkInfo.toString());

}

上面的代码得到了mobile、WIFI、mobile_mms、mobile_supl、mobile_hipri,在AVD上显示为TextView消息。

于 2013-05-08T11:05:19.657 回答