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

Android Studio中判断Wi-Fi/移动数据并提示用户切换的实现方法

检测移动网络并提示切换Wi-Fi的实现方案

核心思路

利用浏览器原生的Navigator.connection API检测当前网络连接类型,判断是否为移动数据(cellular),如果是则显示提示弹窗引导用户切换到Wi-Fi。

完整实现示例

1. HTML结构

<!-- 提示弹窗,默认隐藏 -->
<div id="wifi-prompt" class="prompt-overlay">
  <div class="prompt-content">
    <h3>当前使用移动数据</h3>
    <p>本应用在移动数据环境下无法正常运行,请切换到Wi-Fi网络后再使用。</p>
    <button id="close-prompt">我知道了</button>
  </div>
</div>

<!-- 你的应用内容 -->
<div id="app-content">
  <!-- 这里是你的应用主体内容 -->
</div>

2. CSS样式

/* 遮罩层 */
.prompt-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: none;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

/* 弹窗内容 */
.prompt-content {
  background-color: white;
  padding: 2rem;
  border-radius: 8px;
  width: 80%;
  max-width: 400px;
  text-align: center;
}

.prompt-content button {
  margin-top: 1.5rem;
  padding: 0.8rem 1.5rem;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.prompt-content button:hover {
  background-color: #0056b3;
}

3. JavaScript逻辑

// 检测网络连接类型并显示提示
function checkNetworkConnection() {
  // 检查浏览器是否支持Navigator.connection API
  if (!navigator.connection) {
    console.warn("当前浏览器不支持网络连接检测API");
    return;
  }

  const connection = navigator.connection;
  // 判断是否为移动数据(cellular)
  const isCellular = connection.type === 'cellular';

  // 额外:也可以通过effectiveType判断,比如'2g'/'3g'/'4g'都属于移动数据
  // const isMobileData = ['2g', '3g', '4g'].includes(connection.effectiveType);

  if (isCellular) {
    document.getElementById('wifi-prompt').style.display = 'flex';
  }

  // 监听网络连接变化
  connection.addEventListener('change', () => {
    const nowIsCellular = connection.type === 'cellular';
    if (nowIsCellular) {
      document.getElementById('wifi-prompt').style.display = 'flex';
    } else {
      document.getElementById('wifi-prompt').style.display = 'none';
    }
  });
}

// 关闭弹窗事件
document.getElementById('close-prompt').addEventListener('click', () => {
  document.getElementById('wifi-prompt').style.display = 'none';
});

// 页面加载完成后执行检测
window.addEventListener('load', checkNetworkConnection);

关键说明

  • API兼容性:Navigator.connection已被大多数现代移动端浏览器支持(Chrome、Firefox、Edge等),但部分旧版浏览器可能不支持,因此需要做兼容性判断。
  • 判断逻辑:除了connection.type === 'cellular',也可以通过effectiveType判断网络类型(比如'2g'、'3g'、'4g'),覆盖更多移动数据场景。
  • 监听网络变化:通过change事件可以实时监听网络切换,用户切换到Wi-Fi后自动隐藏提示。
  • 注意事项:Web应用无法直接跳转到系统Wi-Fi设置页面,只能通过提示引导用户手动操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:40:31