在Android中的蜂窝网络和WiFi网络之间切换

时间:2018-07-24 10:50:42

标签: android

我对了解负责WiFi可用/不可用时负责在WiFi和蜂窝网络之间自动切换的Android源代码文件/类感兴趣。我尝试在android.googlesource.com上搜索android源代码,但找不到任何信息。是由Android平台还是linux内核完成的事情?

1 个答案:

答案 0 :(得分:0)

您可以使用ConnectivityManager类。

示例

String networkStatus = "disconnected";
            int netType = 0;
            try{
            ConnectivityManager connectivityManager =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            if(connectivityManager != null ){
                    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                    if(networkInfo != null){
                        netType = networkInfo.getType();
                        Log.d("Log", "connetion is available");
                    }else {
                        Log.d("Log", "connetion is  not available");
                        return networkStatus;
                    }

                //  if(networkInfo.isAvailable()){  // Old one
if(networkInfo.isAvailable() && networkInfo.isConnected()){  // New change added here
                        if(netType == ConnectivityManager.TYPE_WIFI)
                            {}
                        else if(netType == ConnectivityManager.TYPE_MOBILE )
                            {}
                            }
                        }
                    }catch(Exception e){
            Log.d("Log", "checkNetworkConnection" + e.toString());
            return networkStatus;
        }