检测WiFi或移动网络

5
我需要注意android系统中的网络变化,并根据情况执行特定活动。
1)当WiFi启用时,执行功能A。 2)当移动网络启用时,执行功能B。 3)当WiFi被禁用并且移动网络启用时,停止功能A并启动功能B。 4)当移动网络被禁用并且WiFi启用时,停止功能B并启动功能A。 5)没有可用网络时,不执行任何功能。
我尝试使用CONNECTIVITY_CHANGE。使用此方法,我会多次接收到Intent通知,我也知道原因。还有另一个问题。假设移动网络已打开。现在,当我启用WiFi时,我会收到2-3次WiFi已启用的通知,并且无法确认移动网络是否已被禁用。
我还尝试注册PhoneStateListener.LISTEN_DATA_CONNECTION_STATE。这方法几乎有效,但是当WiFi和移动网络都开启时,我知道WiFi将处于活动状态,当我关闭WiFi时,有时会收到移动网络已启用的消息,有时则没有。
我需要解决这个问题。请您给予指导。
4个回答

1
    Please find the below code. I suppose it is what you want. In case I misunderstood you, then please let me know:


    public void checkWifiMobileNetwork(Context context){

            ConnectivityManager conMgr =  (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();

            if (activeNetwork != null && activeNetwork.isConnected()) {
                android.net.NetworkInfo connWifiType = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                android.net.NetworkInfo connMobileType = conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                if(connWifiType.isConnectedOrConnecting()){
                    Log.d("NETWORK_STATUS","WIFI_IS_THERE");
                }else{
                    Log.d("NETWORK_STATUS","WIFI_IS_NOT_THERE");
                }

                if(connMobileType.isConnectedOrConnecting()){
                    Log.d("NETWORK_STATUS","MOBILE_NETWORK_IS_THERE");
                }else{
                    Log.d("NETWORK_STATUS","MOBILE_NETWORK_IS_NOT_THERE");
                }

            }else {
                //notify user you are not online
                Log.d("NETWORK_STATUS","WIFI_MOBILE_IS_NOT_THERE");

            }
        }

Set permission at Manifest:
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

1
实际上,当网络可用时,您有四种状态(如果有互联网,则为第五种)。
当网络可用时,您需要通过监视Wifi和移动网络的状态来检查互联网提供商,您的四种状态是:
Wifi更改状态并且
1. 移动网络已启用 2. 移动网络已禁用
移动网络更改状态并且
1. Wifi已启用 2. Wifi已禁用
首先,您必须监视互联网是否可用。然后,您将不得不添加类似的两个侦听器(广播接收器)以监听Wifi状态更改和移动状态更改,并检查所需的状态。我在下面添加了状态检查方法。
接收器实现
检查接收器中的更改,然后检查状态。
public class Internet_State extends BroadcastReceiver {
//checked with new state changed when event occurs
public boolean oldInternetState;

@Override
public void onReceive(Context context, Intent intent) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    Bundle b = intent.getExtras();
    // if Internet available
    boolean isConnected = !b
            .getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);
            // ignore if no state change
    if (oldInternetState == isConnected)
        return;
    // set new oldInternetState
    oldInternetState = isConnected;
    boolean isMobile = activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;
    boolean isWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            .isAvailable();
 //you can save these states to be monitored in wifi and mobile change change listners

    //No internet is 0 state
    int state = isConnected?1:0;
            if(state)
            state = checkState(context)
    intent.putExtra("state", state);
             // and then send this intent to your required method which will
             // check the state and perform function
}

@Override
public void initialize(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            //save the current internet state at start of the receiver registration
    oldInternetState = false;
    if (activeNetwork != null)
        oldInternetState = activeNetwork.isConnectedOrConnecting();
}

}

实现两个广播接收器,分别用于监听手机和Wi-Fi状态的改变,并添加一个如下所示的状态检查方法

检查状态

监测四种状态之一

public int checkState(Context context){
            ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isMobile = activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;
    boolean isWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            .isAvailable();
    //No internet is 0 state
    int state = isConnected?1:0;
    if(isWifi && isMobile)
        state = 1;
    else if(isWifi && !isMobile)
        state = 2;
    if(isMobile && isWifi)
        state = 3;
    else if(isMobile && !isWifi)
        state = 4;
       return state;
}

请将此方法从3个Wifi、Internet和移动数据更改接收器中调用,不要忘记检查旧状态并将其与更改后的状态进行匹配。
移动设备旧状态:
 NetworkInfo allNetInfo = cm
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    oldDataState = allNetInfo.getState();

用于Wi-Fi状态

int state = intent.getExtras().getInt(WifiManager.EXTRA_WIFI_STATE);
    if (state == WifiManager.WIFI_STATE_ENABLED)
        state = 1;
    else if (state == WifiManager.WIFI_STATE_DISABLED)
        state = 0;
    else
        return;
    if (state == oldWifiState)
        return;
    oldWifiState = state;

问题:我只能开启2到3次WiFi

由于操作系统触发了WiFi状态的变化,如打开和关闭WiFi,会导致多个WiFi更改调用。您需要取消它们,就像我上面所做的那样。

if (state == WifiManager.WIFI_STATE_ENABLED)
        state = 1;
    else if (state == WifiManager.WIFI_STATE_DISABLED)
        state = 0;
    else
        return;

现在只监视启用和禁用状态。


0

在你的应用程序的第一个活动中尝试这段代码。

public class YourActivity extends Activity {

    Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        this.registerReceiver(this.mNetworkConReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); // Here you register your receiver
    }

    private BroadcastReceiver mNetworkConReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            ConnectivityManager conMngr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifi = conMngr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            NetworkInfo mobile = conMngr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if(wifi.isConnected()){
                // Wifi is connected
            }else if(mobile.isConnected() && wifi.isConnected()){
                // Mobile Network and Wifi is connected
            }// Others conditions here...

        }
    };

}

请记住:每当网络状态发生变化时,您的广播接收器都会被 Android 触发。


0

这就是我的问题。如何只用一个触发器注意到变化?此外,当我们同时启用移动网络和WiFi时,该技术会将两者都启用。实际上,WiFi 将处于活动状态。我们必须动态决定当 WiFi 打开时移动网络关闭。 - madhu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接