问题
I was trying to test the network state of my emulator using following code and allowing it 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");
}
}
//..
}
When I run it as Android Application I get Not connected to wifi TextView message displayed on the emulator but when I use emulator to connect to google.com or yahoo.com, it works just fine.
Could someone help me understand why am I getting Not connected to wifi message?
Thanks.
回答1:
Try adding <uses-permission android:name="android.permission.INTERNET" />
In permission section in your Android manifest file.
Edit:- Try this..
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
}
}
Ofcourse, check this on real device :)
Hope this helps.
回答2:
Because the simulator can't simulate wifi, see this answer and the documentation. I think it will always return "Not connected to wifi" if you execute this method in an emulator.
How to turn on the Wi-Fi on android emulator device?
http://developer.android.com/tools/devices/emulator.html
回答3:
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());
}
Above code got mobile, WIFI, mobile_mms, mobile_supl, mobile_hipri, displayed as TextView
message on the AVD.
来源:https://stackoverflow.com/questions/16436900/android-emulator-network-state-and-internet-access