本文翻译自:Detect whether there is an Internet connection available on Android [duplicate]
I need to detect whether the Android device is connected to the Internet. 我需要检测Android设备是否已连接到Internet。
The NetworkInfo
class provides a non-static method isAvailable()
that sounds perfect. NetworkInfo
类提供了一个听起来很完美的非静态方法isAvailable()
。
Problem is that: 问题是:
NetworkInfo ni = new NetworkInfo();
if (!ni.isAvailable()) {
// do something
}
throws this error: 抛出此错误:
The constructor NetworkInfo is not visible.
Safe bet is there is another class that returns a NetworkInfo
object. 可以肯定的是,还有另一个类返回NetworkInfo
对象。 But I don't know which. 但我不知道。
- How to get the above snippet of code to work? 如何使上面的代码片段起作用?
- How could I have found myself the information I needed in the online documentation? 如何找到自己在在线文档中所需的信息?
- Can you suggest a better way for this type of detection? 您能为这种类型的检测提出更好的方法吗?
#1楼
参考:https://stackoom.com/question/Hmjh/检测Android上是否存在Internet连接-重复
#2楼
The getActiveNetworkInfo()
method of ConnectivityManager
returns a NetworkInfo
instance representing the first connected network interface it can find or null
if none of the interfaces are connected. ConnectivityManager
的getActiveNetworkInfo()
方法返回一个NetworkInfo
实例,该实例表示它可以找到的第一个连接的网络接口;如果没有接口ConnectivityManager
返回null
。 Checking if this method returns null
should be enough to tell if an internet connection is available or not. 检查此方法是否返回null
应该足以判断互联网连接是否可用。
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
You will also need: 您还需要:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in your android manifest. 在您的Android清单中。
Edit: 编辑:
Note that having an active network interface doesn't guarantee that a particular networked service is available. 请注意,拥有活动的网络接口并不能保证特定的网络服务可用。 Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. 网络问题,服务器停机,信号不足,门户网站被俘,内容过滤器等都可能阻止您的应用程序到达服务器。 For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service. 例如,在您收到来自Twitter服务的有效回复之前,您无法确定您的应用程序是否可以访问Twitter。
#3楼
Probably I have found myself: 可能我发现自己:
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
#4楼
Also another important note. 也是另一个重要说明。 You have to set android.permission.ACCESS_NETWORK_STATE
in your AndroidManifest.xml for this to work. 为此,您必须在AndroidManifest.xml中设置android.permission.ACCESS_NETWORK_STATE
。
_ how could I have found myself the information I needed in the online documentation? _我如何找到自己在在线文档中需要的信息?
You just have to read the documentation the the classes properly enough and you'll find all answers you are looking for. 您只需要足够适当地阅读有关类的文档,即可找到所需的所有答案。 Check out the documentation on ConnectivityManager . 请查看ConnectivityManager上的文档。 The description tells you what to do. 描述告诉您该怎么做。
#5楼
I check for both Wi-fi and Mobile internet as follows... 我按以下方式检查Wi-fi和移动互联网...
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Obviously, It could easily be modified to check for individual specific connection types, eg, if your app needs the potentially higher speeds of Wi-fi to work correctly etc. 显然,可以很容易地对其进行修改以检查单个特定的连接类型,例如,如果您的应用需要可能更高的Wi-fi速度才能正常工作等。
#6楼
Step 1: Create a class AppStatus in your project(you can give any other name also). 步骤1:在您的项目中创建一个AppStatus类(您也可以指定其他名称)。 Then please paste the given below lines into your code: 然后,将下面给出的行粘贴到您的代码中:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class AppStatus {
private static AppStatus instance = new AppStatus();
static Context context;
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
boolean connected = false;
public static AppStatus getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
try {
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isAvailable() &&
networkInfo.isConnected();
return connected;
} catch (Exception e) {
System.out.println("CheckConnectivity Exception: " + e.getMessage());
Log.v("connectivity", e.toString());
}
return connected;
}
}
Step 2: Now to check if the your device has network connectivity then just add this code snippet where ever you want to check ... 步骤2:现在检查您的设备是否具有网络连接,然后只需将此代码段添加到要检查的位置即可...
if (AppStatus.getInstance(this).isOnline()) {
Toast.makeText(this,"You are online!!!!",8000).show();
} else {
Toast.makeText(this,"You are not online!!!!",8000).show();
Log.v("Home", "############################You are not online!!!!");
}