如何知道设备何时在Android中连接到互联网(Wi-fi/移动数据)

如何知道设备何时在Android中连接到互联网(Wi-fi/移动数据),android,android-intent,broadcastreceiver,android-wifi,Android,Android Intent,Broadcastreceiver,Android Wifi,我想在设备连接到wi-fi或移动数据后立即与服务器通信。目前我正在使用广播接收器通知设备何时连接到wifi代码如下: <receiver android:name="com.example.rup35h.WifiReceiver" > <intent-filter android:priority="100" > <action android:name="android.net.wifi.STATE_CHANGE" />

我想在设备连接到wi-fi或移动数据后立即与服务器通信。目前我正在使用广播接收器通知设备何时连接到wifi代码如下:

<receiver android:name="com.example.rup35h.WifiReceiver" >
        <intent-filter android:priority="100" >
            <action android:name="android.net.wifi.STATE_CHANGE" />
        </intent-filter>
    </receiver>

我关心的是,当设备连接到移动数据时,它会工作吗。当用户打开移动数据/3G网络时,也会调用此命令

请让我知道是否有人会有与此相关的东西。 提前谢谢

当用户打开移动数据/3G网络时,也会调用此命令

不,它不会执行,所以当您使用移动数据/3G网络时,要使其工作,您还必须添加此功能

<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
啊,我在你的评论中看到了

我只需要检查设备是否已连接,仅此而已

这是非常简单的,你可以像下面这样做

/**
 * This method check mobile is connected to network.
 * @param context
 * @return true if connected otherwise false.
 */
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if(conMan.getActiveNetworkInfo() != null && conMan.getActiveNetworkInfo().isConnected())
        return true;
    else
        return false;
}

@但我听说这也会在设备失去连接时通知我@rup35h是的,您是对的,您必须检查您是否连接到internet以及通过什么连接medium@TGMCians不,我只需要检查设备是否已连接,仅此而已。谢谢您的大力支持。@rup35h是的,我知道,无论如何,我很高兴帮助您:-)
/**
 * This method check mobile is connected to network.
 * @param context
 * @return true if connected otherwise false.
 */
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if(conMan.getActiveNetworkInfo() != null && conMan.getActiveNetworkInfo().isConnected())
        return true;
    else
        return false;
}