只是對加布裏埃爾的答案擴大,因爲它可能是值得檢查用戶的任何數據連接,即; WiFi或數據。這也會顯示一個對話框詢問用戶他們是否想用Intent打開WiFi。希望這可以幫助你!
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
if (haveConnectedWifi == false && haveConnectedMobile == false) {
Log.d("Network State", "false");
AlertDialog.Builder alert = new AlertDialog.Builder(YourActivity.this);
alert.setTitle("No Data Connection!");
alert.setMessage("You have no data connection.");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// TODO Auto-generated method stub
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.wifi.WifiSettings");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alert.show();
}else{
//do something else
}
return haveConnectedWifi || haveConnectedMobile;
}
...因爲它返回啓用。我用4.2.2試過,發現它再次返回CURRENT。不知道爲什麼...看[這裏](http://stackoverflow.com/questions/22795829/differences-between-wificonfiguration-status)。 – 2014-04-01 20:13:35