如何在Android上检查我的设备是否已连接到Wi-Fi?

时间:2013-08-14 12:13:35

标签: android

如何才能在Android上获得连接?

我尝试了很多代码,但是没有得到正确的结果。

3 个答案:

答案 0 :(得分:3)

输入此功能并在您的活动开始时调用它:

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();
    }
}

答案 1 :(得分:2)

如果您要检查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;
}

答案 2 :(得分:1)

也许这会有所帮助:

 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

此链接也有帮助:

NetworkInfo