我试图使用以下代码测试我的模拟器的网络状态并允许它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应用程序运行时,我得到未连接到wifi 模拟器上显示的TextView消息但是当我使用模拟器连接到google.com或yahoo.com时,它工作得很好。
有人可以帮我理解为什么我没有连接到wifi 消息?
感谢。
答案 0 :(得分: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
}
}
当然,请在真实设备上查看:)
希望这会有所帮助。
答案 1 :(得分:1)
因为模拟器无法模拟wifi,请参阅此答案和文档。我认为如果你在模拟器中执行此方法,它将始终返回“未连接到wifi”。
答案 2 :(得分: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());
}
以上代码移动,WIFI,mobile_mms,mobile_supl,mobile_hipri,在AVD上显示为TextView
消息。