聆听更改网络并检测互联网只能工作一次

时间:2017-08-04 04:24:57

标签: android

我写了简单的BroadcastReceiver来检测互联网连接并检查互联网可用于向服务器发送数据,只在第一次打开应用程序时返回true,这意味着,在打开应用程序后,BroadcastReceiver可以正确检测连接到互联网,在每次打开/关闭wifi后,我只得到假,它不正确,必须是真或假

public class ConnectionListener extends BroadcastReceiver {
    private boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    @Override
    public void onReceive(Context mContext, Intent intent) {
        Log.e("check ", isNetworkAvailable(mContext) + "");
        if (isNetworkAvailable(mContext)) {
            EventBus.getDefault().post(new EventNetworkConnectionStateEvent(EventNetworkConnectionStateEvent.ConnectionState.connected));
        } else
            EventBus.getDefault().post(new EventNetworkConnectionStateEvent(EventNetworkConnectionStateEvent.ConnectionState.disconnected));
    }
}

清单:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

接收器:

<receiver android:name="..Broadcasts.ConnectionListener">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
        <action android:name="android.net.wifi.STATE_CHANGE"/>
    </intent-filter>
</receiver>

0 个答案:

没有答案