如何处理wifi和移动数据之间的网络变化?

时间:2018-01-03 15:25:51

标签: android networking android-wifi mobile-data android-connectivitymanager

我正在构建一个VoIP应用程序。当用户在WiFi与移动数据之间切换时,在VoIP呼叫期间,我在处理该方案时遇到问题。

在我的通话屏幕活动中,我已经注册了接收器,这有助于我获得有关网络更改方案的通知。

这是我用于检测onRecieve方法中网络变化的代码。 conn_name是包含先前连接名称的私有类级别变量。

ConnectivityManager connectivity_mgr = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    NetworkInfo net_info = connectivity_mgr.getActiveNetworkInfo();

    if (net_info != null && net_info.isConnectedOrConnecting() && !conn_name.equalsIgnoreCase("")) {
        new_con = net_info.getExtraInfo();        
        if (new_con != null && !new_con.equalsIgnoreCase(conn_name))
            network_changed = true;
        conn_name = (new_con == null) ? "" : new_con;
        connectionStatus ="connected";        
    } else {
        if (net_info != null && conn_name.equalsIgnoreCase("")){
            conn_name = net_info.getExtraInfo();
            connectionStatus ="connected";
            network_changed = true;
        }else if(!new_con.equals(conn_name)) {    
            conn_name = "";
            connectionStatus ="disconnected";
            network_changed = true;          
        }        
    }

因此,使用上述方法,我可以检测网络变化。但是当我与WiFi连接时,会发生一件奇怪的事情。当我的应用程序最初启动时,它与移动数据连接。当用户进入他已知的WiFi区域时,他连接到他已知的WiFi。由于WiFi始终被选为默认路由,因此android会切换到WiFi,并且我会收到WiFi已打开的网络通知。

所以我将我的应用IP地址更新为WiFi IP地址,所以这里没有问题。但仍然是移动数据仍在同一时间连接,但 getActiveNetworkInfo()告诉我,即使我早期连接到移动数据,我也能清楚地连接WiFi。

所以问题是当用户关闭WiFi按钮,移动数据仍然连接但我仍然收到关闭WiFi的通知。 它表明即使我的手机仍然连接到移动数据,网络仍然断开连接。

但是一秒钟后我收到移动数据已连接的通知。 但是一旦我收到网络断开连接,我就关闭了我的VoIP电话。 因此,当我收到关闭WiFi的通知时,如何确定移动数据是否仍然连接。

我尝试了getActiveNetworkInfo()但是当我收到关闭WiFi的通知时,它恰好是null。

我已关注此链接:

Android API call to determine user setting "Data Enabled"
How to tell if 'Mobile Network Data' is enabled or disabled (even when connected by WiFi)?

使用上面的链接,当用户与mobiledata连接时,我能够检测到移动数据按钮已启用。 但是当这种特殊情况发生时就会出现问题。

现在,当禁用wifi时,我会收到通知,但它显示即使我的移动数据已启用,移动数据也会被禁用。我无法处理这种情况,因为当我收到断开连接的通知时,我断开了通话。

4 个答案:

答案 0 :(得分:16)

您可以使用ConnectivityManager的API:特别是在您感兴趣的registerDefaultNetworkCallback()用例中:


    public class TestActivity extends AppCompatActivity {

        private ConnectivityManager manager;
        private final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                super.onAvailable(network);
                // this ternary operation is not quite true, because non-metered doesn't yet mean, that it's wifi
                // nevertheless, for simplicity let's assume that's true
                Log.i("vvv", "connected to " + (manager.isActiveNetworkMetered() ? "LTE" : "WIFI"));
            }

            @Override
            public void onLost(Network network) {
                super.onLost(network);
                Log.i("vvv", "losing active connection");
            }
        };

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            manager.registerDefaultNetworkCallback(networkCallback);
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            manager.unregisterNetworkCallback(networkCallback);
        }
    }

我的设备在大约半秒钟内连接到LTE。

enter image description here

这意味着,当WIFI断开连接时,您无法事先知道设备最终是否会连接到LTE或者没有连接到LTE。因此,您可以采用以下方法:在一秒钟内对处理程序发布操作,并在此操作中取消调用。如果很快就会出现连接 - 取消预先安排以前发布的操作。如果您最终使用Runnable代码,则表示连接未快速建立,这意味着您应该结束通话。


    public class TestActivity extends AppCompatActivity {

        private ConnectivityManager manager;

        private final Handler handler = new Handler();
        private final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                super.onAvailable(network);
                Log.i("vvv", "connected to " + (manager.isActiveNetworkMetered() ? "LTE" : "WIFI"));

                // we've got a connection, remove callbacks (if we have posted any)
                handler.removeCallbacks(endCall);
            }

            @Override
            public void onLost(Network network) {
                super.onLost(network);
                Log.i("vvv", "losing active connection");

                // Schedule an event to take place in a second
                handler.postDelayed(endCall, 1000);
            }
        };

        private final Runnable endCall = new Runnable() {
            @Override
            public void run() {
                // if execution has reached here - feel free to cancel the call
                // because no connection was established in a second
            }
        };

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            manager.registerDefaultNetworkCallback(networkCallback);
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            manager.unregisterNetworkCallback(networkCallback);
            handler.removeCallbacks(endCall);
        }
    }

该方法的缺点是,registerDefaultNetworkCallback()从API 24开始可用。ConnectivityManagerCompat中也没有替代方法。相反,您可以使用API​​ 21中提供的registerNetworkCallback()

答案 1 :(得分:3)

您可以使用BroadcastReceiver并注册NETWORK_STATE_CHANGED_ACTION& WIFI_STATE_CHANGED_ACTION

private boolean isConnected;

final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || intent.getAction() == null)
            return;
        switch (intent.getAction()){
            case WifiManager.NETWORK_STATE_CHANGED_ACTION :
            case WifiManager.WIFI_STATE_CHANGED_ACTION :
                if (!isConnected && isOnline(BaseActivity.this)) {
                    isConnected = true;
                    // do stuff when connected
                    Log.i("Network status: ","Connected");
                }else{
                    isConnected = isOnline(BaseActivity.this);
                    Log.i("Network status: ","Disconnected");
                }
                break;
        }
    }
};



@Override
protected void onCreate(Bundle savedInstanceState) {
    isConnected = isOnline(this);
    final IntentFilter filters = new IntentFilter();
    filters.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    filters.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    registerReceiver(broadcastReceiver, filters);
}


public static boolean isOnline(Context ctx) {
    ConnectivityManager cm = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm != null
            ? cm.getActiveNetworkInfo()
            : null;
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

更新不要忘记取消注册收件人BroadcastReceiver onDestroy

@Override
protected void onDestroy() {
    unregisterReceiver(broadcastReceiver);
    super.onDestroy();
} 

答案 2 :(得分:0)

您正在寻找的答案是#Define your function as calcualtion <- function(x){ x*x - 1 } #Suppose you want to call it on column A. Use sapply function as df$A <- sapply(df$A, calcualtion) result: ID A 1 0 63 2 1 255 3 2 15 。请查看以下链接。

BroadcastReceiver when wifi or 3g network state changed

希望它可以帮助您解决问题,如果是,请考虑结束您的问题。

答案 3 :(得分:0)

我用RxJava实现

class ConnectivityMonitor : ConnectivityManager.NetworkCallback() {
    var networkTimeout: Disposable? = null

    override fun onAvailable(network: Network?) {
        super.onAvailable(network)
        Timber.d("Network available")
        networkTimeout?.dispose()
    }

    override fun onLosing(network: Network?, maxMsToLive: Int) {
        super.onLosing(network, maxMsToLive)
        Timber.d("onLosing")
    }

    override fun onLost(network: Network?) {
        super.onLost(network)
        Timber.d("onLost")

        networkTimeout = Single.timer(5, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { _ -> Timber.d("Network lost") }
    }

    override fun onUnavailable() {
        super.onUnavailable()
        Timber.d("Network unavailable")
    }
}

监听器设置:

    private fun setupListeners() {
        // connection listener
        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            connectivityManager.registerDefaultNetworkCallback(connectivityMonitor)
        } else {
            val builder = NetworkRequest.Builder()
            connectivityManager.registerNetworkCallback(builder.build(), connectivityMonitor)
        }
    }

使用计时器/一次性使用可在切换连接类型之间延迟。