处理应用内 WiFi 状态的定期检查

Handling periodic checking of WiFi state within app

Android 应用程序编程的新手,我有一个场景,我正在努力在 Android Studio 中编写代码。

我的应用要求用户连接到特定的 Wifi。所以我想定期检查 Wifi 状态,如果它没有连接/连接到错误的 Wifi,我想抛出一个 AlertDialog 直到用户连接到正确的 Wifi。

但是,我正在为实施而苦苦挣扎。到目前为止,我的方法是使用一种方法 checkWifi() 来测试我们是否使用正确的 Wifi,并相应地设置一个全局布尔值 onCorrectWifi。此 checkWifi() 通过 TimerTask 每 30 秒定期运行。

在与 checkWifi() 方法相同的 TimerTask 中,是另一个名为 handleWifiStatus() 的方法。 handleWifiStatus() 方法查看 onCorrectWifi,如果为 True,则什么都不做。如果 onCorrectWifi 为 False,handleWifiStatus() 生成一个 AlertDialog,然后进入一个 while 循环。 while 循环重复调用 checkWifi() 直到 onCorrectWifi 再次为 True,此时 while 循环退出并且 AlertDialog 被关闭并且正常的应用程序活动恢复。

我正在努力解决这个问题。

我是不是把这件事弄得太复杂了?是否有更好/更简单的实现来实现整个 "check Wifi state, if wrong, show AlertDialog till Wifi is good again" 概念?

  • 我会使用 BroadcaseReceiver 来捕获 Wifi 连接更改事件。这样,您就不需要运行定期检查了。 (参见:How to detect when WIFI Connection has been established in Android?

  • 不确定您使用的是哪种对话框,但是如果您使用的是 AlertDialog.Builder 构建的通用对话框,则不需要 运行 while 循环继续显示对话框。只需调用 dialog.create().show() 即可显示它,仅当建立正确的 Wifi 连接时才关闭它。鉴于这种情况,我会选择 ProgressDialogProgressBar 而不是 AlertDialog

乍一看,您的方法似乎很合理,所以我不太确定哪里出了问题。也就是说,Android 实际上具有在网络状态发生变化时收到通知的功能,以简化这种情况。

// Retrieve the ConnectivityManager via the current Context
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

// Create the method to be called when the WiFi network changes
ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        // Check that this Network is the correct one and take
        // action as appropriate
    }
};

// Set the callback to be fired when WiFi status changes
cm.registerNetworkCallback(
     new NetworkRequest.Builder()
     .addTransportType(TRANSPORT_WIFI)
     .build(),
     callback
);