android检测wifi是否打开或连接及设置自动打开

    private boolean isWifiOpened() {
        WifiManager wifiManager = (WifiManager) cxt.getSystemService(Context.WIFI_SERVICE);
        return wifiManager.isWifiEnabled();
    }
    private boolean isWifiConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager)cxt.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return wifiNetworkInfo.isConnected();
    }
    private void showWifiDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(cxt);
        builder.setTitle("Tip");
        builder.setMessage("未打开Wifi,是否进行设置?");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                toggleWiFi(cxt, true);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }
    private void toggleWiFi(Context context, boolean enabled) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(enabled);
    }

你可能感兴趣的:(Android)