在android中的Wifi网络切换

时间:2014-08-29 14:52:56

标签: android

目前我正在研究音乐播放器的应用程序,其中dj正在播放歌曲和听众听音乐但是它涉及网络如果客户端和DJ在同一网络上然后他们听那些表演活动,否则我们没有超过两个wifi网络问题是这个,如果网络1关闭移动切换它默认网络所以我的应用程序将崩溃我想从os获取通知,如果它将网络从一个热点更改为另一个任何帮助我们提前感谢Thankx

1 个答案:

答案 0 :(得分:1)

如果我提出请求,我通常会这样做:

private static final int NETWORK_TYPE_MOBILE = 0;
private static final int NETWORK_TYPE_WIFI = 1;
private static final int NETWORK_TYPE_ETHERNET = 9; //yep, cable

public static boolean checkForActiveNetworkOnDevice(Context applicationContext) {
    boolean deviceHasConnectedWifi = false;
    boolean deviceHasConnectedMobile = false;
    boolean deviceHasConnectedEthernet = false;

    ConnectivityManager connectivityManager = (ConnectivityManager) applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
    if (networkInfos != null) {
        for (NetworkInfo networkInfo : networkInfos) {
            if (NETWORK_TYPE_WIFI == networkInfo.getType()) {
                if (networkInfo.isConnected()) { deviceHasConnectedWifi = true;}
            }
            if (NETWORK_TYPE_MOBILE == networkInfo.getType()) {
                if (networkInfo.isConnected()) { deviceHasConnectedMobile = true;}
            }
            if (NETWORK_TYPE_ETHERNET == networkInfo.getType()) {
                if (networkInfo.isConnected()) { deviceHasConnectedEthernet = true; }
            }
        }
    }
    return deviceHasConnectedWifi || deviceHasConnectedMobile || deviceHasConnectedEthernet;
}

public static boolean checkForWifi(Context applicationContext) {
    boolean deviceHasConnectedWifi = false;

    ConnectivityManager connectivityManager = (ConnectivityManager) applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
    if (networkInfos != null) {
        for (NetworkInfo networkInfo : networkInfos) {
            if (NETWORK_TYPE_WIFI == networkInfo.getType()) {
                if (networkInfo.isConnected()) { deviceHasConnectedWifi = true;}
            }
        }
    }
    return deviceHasConnectedWifi;
}

public static boolean checkForEthernet(Context applicationContext) {
    boolean deviceHasConnectedEthernet = false;

    ConnectivityManager connectivityManager = (ConnectivityManager) applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
    if (networkInfos != null) {
        for (NetworkInfo networkInfo : networkInfos) {
            if (NETWORK_TYPE_ETHERNET == networkInfo.getType()) {
                if (networkInfo.isConnected()) { deviceHasConnectedEthernet = true;}
            }
        }
    }
    return deviceHasConnectedEthernet;
}

但如果设备断开连接,您应该让您的MediaPlayer呼叫OnErrorListener。如果发生这种情况,您可以再次检查连接,如果您有网络连接,则可以恢复播放。

修改 哦,似乎我误解了你的问题,但我留下了答案,因为你还可以检查连接。