如何在 Android 上获得连接可用或不可用?
我尝试了很多代码,但没有得到正确的结果。
放入此函数并在 Activity 开始时调用它:
void checkInternetConnectionStatus()
{
ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
/*
* Toast.makeText(this, "Wi-Fi connection enabled",
* Toast.LENGTH_LONG) .show();
*/
} else if (mobile.isAvailable()) {
/*
* Toast.makeText(this, "Mobile Internet enabled",
* Toast.LENGTH_LONG) .show();
*/
} else {
Toast.makeText(this, "No Internet Connection", Toast.LENGTH_LONG)
.show();
new AlertDialog.Builder(this)
.setTitle("No internet connection active")
.setMessage("Please start internet connection and run this application.")
.setNegativeButton(
"Exit",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog", "Negative");
finish();
}
}).show();
}
}
如果您尝试检查 Internet 连接,请使用以下命令:
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// If no network is available networkInfo will be null,
// otherwise check if we are connected.
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
也许这会有所帮助:
ConnectivityManager conn = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifi = conn.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifi.isConnected()) {
// Do your code
}
您还需要添加 AndroidManifest.xml:
android.permission.ACCESS_NETWORK_STATE
此链接也将有所帮助: