我正在开发一个用于检查互联网连接的android广播接收器。

问题是我的广播接收器被调用了两次。我希望它只在网络可用时被调用。如果它不可用,我不想被通知。

这是广播接收机

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable()) {
            // Do something

            Log.d("Network Available ", "Flag No 1");
        }
    }
}

这是manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastreceiverforinternetconnection"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

当前回答

到2022年,上述BroadcastReceiver方法都将失效。由于Android 7.0的限制,BroadcastReceiver方法将不再工作。检查互联网是否可用的最新和最简单的方法是使用以下代码。(Android 12测试)

val networkRequest = NetworkRequest.Builder()
        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
        .build()

private val networkCallback = object : ConnectivityManager.NetworkCallback() {
    // network is available for use
    override fun onAvailable(network: Network) {
        super.onAvailable(network)
    }

    // Network capabilities have changed for the network
    override fun onCapabilitiesChanged(
            network: Network,
            networkCapabilities: NetworkCapabilities
    ) {
        super.onCapabilitiesChanged(network, networkCapabilities)
        val unmetered = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
    }

    // lost network connection
    override fun onLost(network: Network) {
        super.onLost(network)
    }
}

val connectivityManager = getSystemService(ConnectivityManager::class.java) as ConnectivityManager
connectivityManager.requestNetwork(networkRequest, networkCallback

将这段代码放在一个函数中,并在activity/fragment的onCreate()中调用它。在onAvailable()和onLost()函数中,每当互联网连接或断开连接时,您都会收到通知。与此同时,您可以使用liveData或任何您喜欢的方式在其他活动/片段中广播这些更新。 官方文档链接:https://developer.android.com/training/monitoring-device-state/connectivity-status-type

其他回答

public class AsyncCheckInternet extends AsyncTask<String, Void, Boolean> {

public static final int TIME_OUT = 10 * 1000;

private OnCallBack listener;

public interface OnCallBack {

    public void onBack(Boolean value);
}

public AsyncCheckInternet(OnCallBack listener) {
    this.listener = listener;
}

@Override
protected void onPreExecute() {
}

@Override
protected Boolean doInBackground(String... params) {

    ConnectivityManager connectivityManager = (ConnectivityManager) General.context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

    if ((networkInfo != null && networkInfo.isConnected())
            && ((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) || (networkInfo
                    .getType() == ConnectivityManager.TYPE_MOBILE))) {
        HttpURLConnection urlc;
        try {
            urlc = (HttpURLConnection) (new URL("http://www.google.com")
                    .openConnection());
            urlc.setConnectTimeout(TIME_OUT);
            urlc.connect();
            if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return true;
            } else {
                return false;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;

        } catch (IOException e) {
            e.printStackTrace();
            return false;

        }
    } else {
        return false;
    }
}

@Override
protected void onPostExecute(Boolean result) {
    if (listener != null) {
        listener.onBack(result);
    }
}

}

public static boolean isNetworkAvailable(Context context) {
        boolean isMobile = false, isWifi = false;

        NetworkInfo[] infoAvailableNetworks = getConnectivityManagerInstance(
                context).getAllNetworkInfo();

        if (infoAvailableNetworks != null) {
            for (NetworkInfo network : infoAvailableNetworks) {

                if (network.getType() == ConnectivityManager.TYPE_WIFI) {
                    if (network.isConnected() && network.isAvailable())
                        isWifi = true;
                }
                if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
                    if (network.isConnected() && network.isAvailable())
                        isMobile = true;
                }
            }
        }

        return isMobile || isWifi;
    }

/* You can write such method somewhere in utility class and call it NetworkChangeReceiver like below */
public class NetworkChangedReceiver extends BroadcastReceiver 
{
@Override
    public void onReceive(Context context, Intent intent) {

        if (isNetworkAvailable(context)) 
                {
             Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); 


    }
    }
}

只有当网络状态变为已连接而不是已断开时,才会调用上述广播接收器。

到2022年,上述BroadcastReceiver方法都将失效。由于Android 7.0的限制,BroadcastReceiver方法将不再工作。检查互联网是否可用的最新和最简单的方法是使用以下代码。(Android 12测试)

val networkRequest = NetworkRequest.Builder()
        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
        .build()

private val networkCallback = object : ConnectivityManager.NetworkCallback() {
    // network is available for use
    override fun onAvailable(network: Network) {
        super.onAvailable(network)
    }

    // Network capabilities have changed for the network
    override fun onCapabilitiesChanged(
            network: Network,
            networkCapabilities: NetworkCapabilities
    ) {
        super.onCapabilitiesChanged(network, networkCapabilities)
        val unmetered = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
    }

    // lost network connection
    override fun onLost(network: Network) {
        super.onLost(network)
    }
}

val connectivityManager = getSystemService(ConnectivityManager::class.java) as ConnectivityManager
connectivityManager.requestNetwork(networkRequest, networkCallback

将这段代码放在一个函数中,并在activity/fragment的onCreate()中调用它。在onAvailable()和onLost()函数中,每当互联网连接或断开连接时,您都会收到通知。与此同时,您可以使用liveData或任何您喜欢的方式在其他活动/片段中广播这些更新。 官方文档链接:https://developer.android.com/training/monitoring-device-state/connectivity-status-type

回答第一个问题:您的广播接收器被调用了两次,因为

您已经添加了两个<intent-filter>

网络连接的改变: <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> WiFi状态变化: <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />

就用一个: <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />。

它将只响应一个操作而不是两个。更多信息请参见这里。

回答你的第二个问题(如果可以上网,你想让对方只打一次电话):

你的代码是完美的;只有在互联网可用时才通知。

更新

如果你只是想检查手机是否与互联网相连,你可以使用这种方法来检查你的连接。

public boolean isOnline(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    //should check null because in airplane mode it will be null
    return (netInfo != null && netInfo.isConnected());
}

广播接收机代码检查互联网连接变化:

public class BroadCastDetecter extends BroadcastReceiver {
    public static boolean internet_status = false;
    public static void checkInternetConenction(Context context) {
        internet_status = false;
        ConnectivityManager check = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (check != null) {
            NetworkInfo[] info = check.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        internet_status = true;
                    }
                }
            if(internet_status)
            {
               //do what you want to if internet connection is available
            }
        }
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        try {
            checkInternetConenction(context);
        }catch(Exception e){

        }
    }
}

在manifest文件中添加:

 <receiver android:name=".BroadCastDetecter">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>