Android : 检查 3G 或 Wifi 网络是否在 android 设备上打开或可用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11343249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android : Check 3G or Wifi network is ON or Available or not on android Device
提问by Rahul Baradia
How to check that network is available or not on android device programmatically, which throws a message or toast message when we are trying to connect with a network such as Wifi & 3G.
如何以编程方式检查 android 设备上的网络是否可用,当我们尝试连接 Wifi 和 3G 等网络时会抛出消息或吐司消息。
回答by Rahul Baradia
TO check whether network i.e 3G or WiFi is available or not we can use below methods to verify before starting our activities.
要检查网络(即 3G 或 WiFi)是否可用,我们可以在开始活动之前使用以下方法进行验证。
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
//For 3G check
boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.isConnectedOrConnecting();
//For WiFi Check
boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting();
System.out.println(is3g + " net " + isWifi);
if (!is3g && !isWifi)
{
Toast.makeText(getApplicationContext(),"Please make sure your Network Connection is ON ",Toast.LENGTH_LONG).show();
}
else
{
" Your method what you want to do "
}
Hope this will help someone.
希望这会帮助某人。
回答by Agustin Gandara
final ConnectivityManager connMgr = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if( wifi.isAvailable() && wifi.getDetailedState() == DetailedState.CONNECTED){
Toast.makeText(this, "Wifi" , Toast.LENGTH_LONG).show();
}
else if( mobile.isAvailable() && mobile.getDetailedState() == DetailedState.CONNECTED ){
Toast.makeText(this, "Mobile 3G " , Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "No Network " , Toast.LENGTH_LONG).show();
}
this code check if you are with wifi or 3g or nothing , in the case of wifi on but not connected to a net or 3g have signal problem it detect this details, with DetailedStates
此代码检查您是否使用 wifi 或 3g 或什么都没有,如果 wifi 打开但未连接到网络或 3g 有信号问题,它会检测此详细信息,详细信息
回答by zeeali
You can use this method to check whether your internet connection is 2G, 3G or 4G:
您可以使用此方法来检查您的互联网连接是2G、3G 还是 4G:
public String getNetworkClass(Context context) {
TelephonyManager mTelephonyManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
int networkType = mTelephonyManager.getNetworkType();
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return "2G";
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return "3G";
case TelephonyManager.NETWORK_TYPE_LTE:
return "4G";
default:
return "Unknown";
}
}
And using following method you can check if internet is available or not, and get whether you are accessing the internet via a mobile network or WiFi:
并使用以下方法检查互联网是否可用,并了解您是否通过移动网络或WiFi访问互联网:
public String getNetworkType(Context context){
String networkType = null;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
networkType = "WiFi";
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
networkType = "Mobile";
}
} else {
// not connected to the internet
}
return networkType;
}
回答by Krzysztof Huminski
Rahul Baradia's answer includes manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
and it's deprecated.
Rahul Baradia 的回答包括manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
但已弃用。
Below is an improved solution for the latest Android SDK.
以下是针对最新 Android SDK 的改进解决方案。
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
boolean is3gEnabled = false;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connManager.getAllNetworks();
for(Network network: networks)
{
NetworkInfo info = connManager.getNetworkInfo(network);
if(info!=null) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
is3gEnabled = true;
break;
}
}
}
}
else
{
NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(mMobile!=null)
is3gEnabled = true;
}
回答by benoffi7
This work for me
这对我有用
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
String name networkInfo.getTypeName();
回答by Soumyadip Das
Use the following code as NetworkChecker.java& reuse it in your code:
使用下面的代码作为NetworkChecker.java和在你的代码重用它:
package das.soumyadip.util;
import android.net.ConnectivityManager;
import android.util.Log;
public class NetworkChecker {
private final static String TAG = "NwtworkChecker";
public static boolean isNetworkConnected(
final ConnectivityManager connectivityManager) {
boolean val = false;
Log.d(TAG, "Checking for Mobile Internet Network");
final android.net.NetworkInfo mobile = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobile.isAvailable() && mobile.isConnected()) {
Log.i(TAG, "Found Mobile Internet Network");
val = true;
} else {
Log.e(TAG, "Mobile Internet Network not Found");
}
Log.d(TAG, "Checking for WI-FI Network");
final android.net.NetworkInfo wifi = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifi.isAvailable() && wifi.isConnected()) {
Log.i(TAG, "Found WI-FI Network");
val = true;
} else {
Log.e(TAG, "WI-FI Network not Found");
}
return val;
}
}
回答by Maidul
// TODO Auto-generated method stub
ConnectivityManager connMgr =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
final android.net.NetworkInfo mobile = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobile.isAvailable() && mobile.isConnected()) {
Log.i(TAG, "Found Mobile Internet Network");
val = true;
}
// Checks the user prefs and the network connection. Based on the result, decides
// whether
// to refresh the display or keep the current display.
// If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
if (WIFI.equals(sPref) && networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// If device has its Wi-Fi connection, sets refreshDisplay
// to true. This causes the display to be refreshed when the user
// returns to the app.
refreshDisplay = true;
Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
// If the setting is ANY network and there is a network connection
// (which by process of elimination would be mobile), sets refreshDisplay to true.
}
}
else if (ANY.equals(sPref) && networkInfo != null) {
refreshDisplay = true;
// Otherwise, the app can't download content--either because there is no network
// connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there
// is no Wi-Fi connection.
// Sets refreshDisplay to false.
} else {
refreshDisplay = false;
Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
}
回答by A-Droid Tech
We can use ConnectivityManager Classfor any information related to network.
我们可以将ConnectivityManager 类用于任何与网络相关的信息。
It also notifies applications when network connectivity changes. Get an instance of this class by calling
它还会在网络连接发生变化时通知应用程序。通过调用获取此类的实例
The primary responsibilities of this class are to:
这个类的主要职责是:
- Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)
- Send broadcast intents when network connectivity changes
- Attempt to "fail over" to another network when connectivity to a network is lost
- Provide an API that allows applications to query the coarse-grained or fine-grained state of the available networks
- Provide an API that allows applications to request and select networks for their data traffic
- 监控网络连接(Wi-Fi、GPRS、UMTS 等)
- 当网络连接发生变化时发送广播意图
- 当与网络的连接丢失时,尝试“故障转移”到另一个网络
- 提供允许应用程序查询可用网络的粗粒度或细粒度状态的 API
- 提供允许应用程序为其数据流量请求和选择网络的 API
GetNetworkInfo functionreturn status information about a particular network type.
GetNetworkInfo 函数返回有关特定网络类型的状态信息。
This method requires the caller to hold the permission
此方法需要调用者持有权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
/**
* Checks the type of data connection that is currently available on the device.
*
* @return <code>ConnectivityManager.TYPE_*</code> as a type of internet connection on the
*This method does not support multiple connected networks
* of the same type.
* device. Returns -1 in case of error or none of
* <code>ConnectivityManager.TYPE_*</code> is found.
**/
--
——
public static int getDataConnectionType(Context ctx) {
ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null && connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null) {
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()) {
return ConnectivityManager.TYPE_MOBILE;
} else if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
return ConnectivityManager.TYPE_WIFI;
} else
return -1;
} else
return -1;
}
回答by Bilawal sharif
public boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
return true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
return true;
}
} else {
// not connected to the internet
return false;
}
return false;
}
回答by Macs
in none of the code above i see a check for whether getNetworkInfo() returned null, which happens according to the docs when the requested network type is not supported. this suggests that on devices without 3g the app will crash with null pointer exception.
在上面的代码中,我都没有看到检查 getNetworkInfo() 是否返回 null,根据文档,当请求的网络类型不受支持时会发生这种情况。这表明在没有 3g 的设备上,应用程序将因空指针异常而崩溃。