3

我创建了一个需要始终连接到远程套接字服务器的应用程序。

我为了这样做,我已经注册了一个BroadcastReceiver连接更改。每次 Receiver 触发时 - 应用程序都会与服务器断开连接并创建新连接。它这样做是为了保持一个活动的和连接的套接字连接。

在我的手机和我检查过的其他几部手机中效果很好。但是我发现其他一些手机在连接到移动提供商数据连接时 - 经常调用接收器,而连接性没有任何实际变化。

有没有办法让我知道连接是否真的发生了变化?此外,为什么接收器如此频繁地开火?

4

1 回答 1

1

好的,我找到了解决我的问题的方法,希望我能在某个时候帮助别人:

在我的广播接收器中进行连接更改:

@Override
public void onReceive(Context context, Intent intent) {
        //my Application class where i store the last known state of connectivity
    app = (AppVariables) context.getApplicationContext();
        //new network state
    networkState = ((NetworkInfo)intent.getExtras().get("networkInfo")).getState();
    if (app.getLastNetworkState().equals(State.CONNECTED) && networkState.equals(State.DISCONNECTED))
    {
        Log.i("InternetConnectivity", "Internet Status Changed: disconnected");
        if (app.getServerConnectionManager() != null)
            app.getServerConnectionManager().stopServer(false, false);
        if (app.getMainActivity() != null)
            app.getMainActivity().showReconnectDialog();
        app.setLastNetworkState(networkState);
    }
    else if (networkState.equals(State.CONNECTED))
        app.setLastNetworkState(networkState);
}
于 2012-12-23T14:20:52.053 回答