You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

安卓开发:如何通过代码显示已连接WiFi的分享二维码?

编程实现显示当前连接WiFi的分享二维码

你希望通过Kotlin或Java代码,实现类似系统网络详情界面(含WiFi名称、信号信息及底部“分享”按钮,点击后弹出WiFi二维码)的功能,目前仅能通过startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))打开WiFi设置主页面,以下是具体解决方案:

一、是否存在直接跳转分享界面的Intent ACTION?

Android系统没有公开的官方Intent ACTION可以直接跳转到WiFi分享弹窗。这个界面属于系统设置的内部页面,不同厂商(如小米、华为、三星)的实现逻辑和页面路径存在差异,没有统一的标准Intent可供调用。

二、可靠实现方案:自行生成WiFi二维码

更稳定的方式是获取当前WiFi的连接信息,自行生成符合标准的WiFi二维码,无需依赖系统界面。

1. 所需权限

在AndroidManifest.xml中添加权限:

<!-- 获取WiFi状态信息 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- Android 12+ 需要此权限获取WiFi详细信息 -->
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" />
<!-- Android 11及以下需要位置权限 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

注意:需动态申请对应权限,确保权限获取成功后再执行后续逻辑。

2. 获取当前连接的WiFi信息

Kotlin示例:

val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val currentNetwork = wifiManager.connectionInfo
val ssid = currentNetwork.ssid.replace("\"", "") // 去除SSID两端的引号
val encryptionType = getEncryptionType(wifiManager, ssid)
val password = getWifiPassword(applicationContext, ssid)

// 辅助方法:获取加密类型
fun getEncryptionType(wifiManager: WifiManager, ssid: String): String {
    val configuredNetworks = wifiManager.configuredNetworks
    configuredNetworks?.forEach { network ->
        if (network.SSID.replace("\"", "") == ssid) {
            return when (network.allowedKeyManagement.get(0)) {
                WifiConfiguration.KeyMgmt.WPA_PSK, WifiConfiguration.KeyMgmt.WPA_EAP, WifiConfiguration.KeyMgmt.IEEE8021X -> "WPA"
                WifiConfiguration.KeyMgmt.WEP -> "WEP"
                else -> ""
            }
        }
    }
    return ""
}

// 辅助方法:获取已保存的WiFi密码(Android 10+)
fun getWifiPassword(context: Context, ssid: String): String? {
    val contentResolver = context.contentResolver
    val projection = arrayOf(WifiNetworkSuggestion.COLUMN_PASSWORD)
    val selection = "${WifiNetworkSuggestion.COLUMN_SSID} = ?"
    val selectionArgs = arrayOf(ssid)
    contentResolver.query(
        WifiNetworkSuggestion.CONTENT_URI,
        projection,
        selection,
        selectionArgs,
        null
    )?.use { cursor ->
        if (cursor.moveToFirst()) {
            return cursor.getString(cursor.getColumnIndexOrThrow(WifiNetworkSuggestion.COLUMN_PASSWORD))
        }
    }
    return null
}

Java示例:

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo currentNetwork = wifiManager.getConnectionInfo();
String ssid = currentNetwork.getSsid().replace("\"", "");
String encryptionType = getEncryptionType(wifiManager, ssid);
String password = getWifiPassword(getApplicationContext(), ssid);

// 辅助方法:获取加密类型
private String getEncryptionType(WifiManager wifiManager, String ssid) {
    List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
    if (configuredNetworks != null) {
        for (WifiConfiguration network : configuredNetworks) {
            if (network.SSID.replace("\"", "").equals(ssid)) {
                if (network.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK) ||
                    network.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP) ||
                    network.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
                    return "WPA";
                } else if (network.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WEP)) {
                    return "WEP";
                } else {
                    return "";
                }
            }
        }
    }
    return "";
}

// 辅助方法:获取已保存的WiFi密码(Android 10+)
private String getWifiPassword(Context context, String ssid) {
    ContentResolver contentResolver = context.getContentResolver();
    String[] projection = {WifiNetworkSuggestion.COLUMN_PASSWORD};
    String selection = WifiNetworkSuggestion.COLUMN_SSID + " = ?";
    String[] selectionArgs = {ssid};
    Cursor cursor = contentResolver.query(
        WifiNetworkSuggestion.CONTENT_URI,
        projection,
        selection,
        selectionArgs,
        null
    );
    if (cursor != null && cursor.moveToFirst()) {
        String password = cursor.getString(cursor.getColumnIndexOrThrow(WifiNetworkSuggestion.COLUMN_PASSWORD));
        cursor.close();
        return password;
    }
    return null;
}

3. 生成WiFi二维码

使用ZXing库生成二维码,先在Module级别的build.gradle添加依赖:

implementation 'com.google.zxing:core:3.5.2'
implementation 'com.journeyapps:zxing-android-embedded:4.3.0'

Kotlin示例:生成二维码Bitmap并显示

fun generateWifiQrCode(ssid: String, password: String, encryptionType: String): Bitmap? {
    val wifiQrString = "WIFI:T:$encryptionType;S:$ssid;P:$password;;"
    val hints = hashMapOf<EncodeHintType, Any>().apply {
        put(EncodeHintType.CHARACTER_SET, "UTF-8")
        put(EncodeHintType.MARGIN, 1) // 二维码边距
    }
    return try {
        val bitMatrix = MultiFormatWriter().encode(
            wifiQrString,
            BarcodeFormat.QR_CODE,
            500, 500, // 二维码尺寸
            hints
        )
        BarcodeEncoder().createBitmap(bitMatrix)
    } catch (e: WriterException) {
        e.printStackTrace()
        null
    }
}

// 显示到ImageView
val qrBitmap = generateWifiQrCode(ssid, password ?: "", encryptionType)
qrImageView.setImageBitmap(qrBitmap)

Java示例:生成二维码Bitmap并显示

private Bitmap generateWifiQrCode(String ssid, String password, String encryptionType) {
    String wifiQrString = "WIFI:T:" + encryptionType + ";S:" + ssid + ";P:" + password + ";;";
    Map<EncodeHintType, Object> hints = new HashMap<>();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    hints.put(EncodeHintType.MARGIN, 1);
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(
            wifiQrString,
            BarcodeFormat.QR_CODE,
            500, 500,
            hints
        );
        return new BarcodeEncoder().createBitmap(bitMatrix);
    } catch (WriterException e) {
        e.printStackTrace();
        return null;
    }
}

// 显示到ImageView
Bitmap qrBitmap = generateWifiQrCode(ssid, password != null ? password : "", encryptionType);
qrImageView.setImageBitmap(qrBitmap);

三、非官方跳转方式(不推荐)

部分厂商有隐藏的系统页面Component,但适配性极差,仅作参考:
例如小米系统的分享界面:

val intent = Intent().apply {
    component = ComponentName(
        "com.android.settings",
        "com.android.settings.wifi.WifiShareActivity"
    )
}
try {
    startActivity(intent)
} catch (e: ActivityNotFoundException) {
    // 适配失败, fallback到自行生成二维码
}

这种方式在不同品牌、不同系统版本下大概率失效,不建议作为主要方案。

内容的提问来源于stack exchange,提问作者algorix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 04:56:02