0

我想在 wifi 未连接一段时间后关闭我的 wifi。我遇到的问题是当我删除 wifi 连接时 onreceive接到电话但说网络仍然连接。我不明白为什么它的连接状态没有改变?是不是状态变化太快以至于来不及捕捉??任何帮助将不胜感激。

这是我的接收器

class WifiDataReceiver extends BroadcastReceiver {
    public void onReceive(Context c, Intent intent) {
        Log.v("msg", "onReceive WifiDataReceiver");
        Log.v("msg", "mWifi : " + mWifi);
        cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        mWifi = cm.getNetworkInfo(1).getState();
        if (mWifi != NetworkInfo.State.CONNECTED){
            try {
                Thread.sleep(disconnectionTimeout);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            wifiManager.setWifiEnabled(false);
            Log.v("msg", "Disconnect  WifiDataReceiver");

        } else {
            Log.v("msg", "connected");
        }
    }
4

1 回答 1

1

我已经在 2 台设备(GS3 和 Samsung Charge)上测试了您的代码。它工作得很好。切换 wifi 设置后,状态发生了变化。我的代码在 github 上,这里。以下是日志:

06-17 15:50:46.151: V/msg(12488): onReceive WifiDataReceiver
06-17 15:50:46.151: V/msg(12488): mWifi : DISCONNECTED
06-17 15:50:56.151: V/msg(12488): Disconnect  WifiDataReceiver
06-17 15:50:56.221: V/msg(12488): onReceive WifiDataReceiver
06-17 15:50:56.221: V/msg(12488): mWifi : DISCONNECTED
06-17 15:51:06.232: V/msg(12488): Disconnect  WifiDataReceiver
06-17 15:51:06.292: V/msg(12488): onReceive WifiDataReceiver
06-17 15:51:06.302: V/msg(12488): mWifi : DISCONNECTED
06-17 15:51:16.293: V/msg(12488): Disconnect  WifiDataReceiver
06-17 15:51:39.678: V/msg(12488): onReceive WifiDataReceiver
06-17 15:51:39.678: V/msg(12488): mWifi : CONNECTED
06-17 15:51:39.678: V/msg(12488): connected
06-17 15:51:39.708: V/msg(12488): onReceive WifiDataReceiver
06-17 15:51:39.708: V/msg(12488): mWifi : CONNECTED
06-17 15:51:39.708: V/msg(12488): connected
06-17 15:51:39.908: V/msg(12488): onReceive WifiDataReceiver
06-17 15:51:39.918: V/msg(12488): mWifi : CONNECTED
06-17 15:51:39.918: V/msg(12488): connected
06-17 15:51:39.918: V/msg(12488): onReceive WifiDataReceiver
06-17 15:51:39.918: V/msg(12488): mWifi : CONNECTED
06-17 15:51:39.918: V/msg(12488): connected

我认为这可能与您的手机或ROM有关。

于 2013-06-17T19:55:15.310 回答