gpt4 book ai didi

java - 如何在 android 设备上检查 wifi 或 3g 网络是否可用

转载 作者:IT老高 更新时间:2023-10-28 21:02:55 26 4
gpt4 key购买 nike

在这里,我的安卓设备同时支持 wifi 和 3g。在特定时间此设备上可用的网络。因为我的要求是当 3g 可用时,我必须上传少量数据。当 wifi 可用时,必须上传整个数据。所以,我必须检查连接是 wifi 还是 3g。请帮我。提前致谢。

最佳答案

我用这个:

/**
* Checks if we have a valid Internet Connection on the device.
* @param ctx
* @return True if device has internet
*
* Code from: http://www.androidsnippets.org/snippets/131/
*/
public static boolean haveInternet(Context ctx) {

NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return false;
}
return true;
}

你还需要

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

在 AndroidMainfest.xml 中

要获取网络类型,您可以使用以下代码段:

ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

//mobile
State mobile = conMan.getNetworkInfo(0).getState();

//wifi
State wifi = conMan.getNetworkInfo(1).getState();

然后像这样使用它:

if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//wifi
}

要获得移动网络的类型,我会尝试 TelephonyManager#getNetworkTypeNetworkInfo#getSubtypeName

关于java - 如何在 android 设备上检查 wifi 或 3g 网络是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3262781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com