我也想离线执行我的应用程序,所以我需要检查当前是否有可用的互联网连接。任何人都可以告诉我如何在Android中检查互联网是否可用?提供示例代码。我尝试使用下面的代码并使用模拟器进行检查,但它无法正常工作
public boolean isInternetConnection()
{
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
}
由于
答案 0 :(得分:59)
这将告诉您是否已连接到网络:
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
}
else
connected = false;
警告:如果您连接的WiFi网络不包含互联网访问权限或需要基于浏览器的身份验证,则connected
仍然是真的。
您的清单中需要此权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 1 :(得分:14)
另外,请注意,有时用户将连接到Wi-Fi网络,但该网络可能需要基于浏览器的身份验证。大多数机场和酒店热点都是这样,所以你的应用程序可能会被认为你有连接,然后任何URL提取实际上将检索热点的登录页面而不是你正在寻找的页面。
根据执行此检查的重要性,除了检查与ConnectivityManager的连接之外,我还建议包含代码以检查它是否是一个有效的Internet连接而不仅仅是一种错觉。您可以尝试从您的站点获取已知地址/资源,例如1x1 PNG图像或1字节文本文件。
答案 2 :(得分:9)
使用以下代码:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
如果 isNetworkAvailable()返回true
,则互联网连接可用,否则互联网连接不可用
此处需要在您的应用清单文件
中添加 uses-Permission<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 3 :(得分:5)
您可以使用两种方法:
1-用于检查连接:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
2-用于支票上网:
public boolean internetIsConnected() {
try {
String command = "ping -c 1 google.com";
return (Runtime.getRuntime().exec(command).waitFor() == 0);
} catch (Exception e) {
return false;
}
}
添加清单权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
答案 4 :(得分:2)
您可以尝试与远程主机建立TCP连接:
public boolean hostAvailable(String host, int port) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), 2000);
return true;
} catch (IOException e) {
// Either we have a timeout or unreachable host or failed DNS lookup
System.out.println(e);
return false;
}
}
然后:
boolean online = hostAvailable("www.google.com", 80);
答案 5 :(得分:2)
使用下一个代码:
public static boolean isNetworkAvaliable(Context ctx) {
ConnectivityManager connectivityManager = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
if ((connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
|| (connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState() == NetworkInfo.State.CONNECTED)) {
return true;
} else {
return false;
}
}
请记住,您需要将清单放入下一行:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 6 :(得分:2)
getActiveNetworkInfo
仅在 API 29 中弃用。所以我们可以在下面的29中使用它。
Kotlin中所有API的新代码
fun isNetworkAvailable(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
// For 29 api or above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) ?: return false
return when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
else -> false
}
}
// For below 29 api
else {
if (connectivityManager.activeNetworkInfo != null && connectivityManager.activeNetworkInfo!!.isConnectedOrConnecting) {
return true
}
}
return false
}
答案 7 :(得分:1)
使用方法checkConnectivity:
if (checkConnectivity()){
//do something
}
检查连接的方法:
private boolean checkConnectivity() {
boolean enabled = true;
ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if ((info == null || !info.isConnected() || !info.isAvailable())) {
Toast.makeText(getApplicationContext(), "Sin conexión a Internet...", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
return false;
}
答案 8 :(得分:1)
代码:
fun isInternetConnection(): Boolean {
var returnVal = false
thread {
returnVal = try {
khttp.get("https://www.google.com/")
true
}catch (e:Exception){
false
}
}.join()
return returnVal
}
摇篮:
implementation 'io.karn:khttp-android:0.1.0'
我使用 khttp 是因为它非常易于使用。
因此在上面的代码中,如果它成功连接到 google.com,则返回 true 否则返回 false。
答案 9 :(得分:1)
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
Google建议使用此代码块。用这个。因为即使将设备连接到wifi也无法将其连接到Internet。 Wifi无法连接到互联网
答案 10 :(得分:1)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
答案 11 :(得分:1)
你可以试试这个:
private boolean isConnectedToWifi(){
ConnectivityManager cm = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm != null){
NetworkCapabilities nc = cm.getNetworkCapabilities(cm.getActiveNetwork());
return nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
}
return false;
}
答案 12 :(得分:0)
尝试使用ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
还添加AndroidManifest.xml的权限
<input>
答案 13 :(得分:0)
这是您可以使用的方法。这适用于所有 API。
public boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager) AnkiDroidApp.getInstance().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
return false;
}
/* NetworkInfo is deprecated in API 29 so we have to check separately for higher API Levels */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Network network = cm.getActiveNetwork();
if (network == null) {
return false;
}
NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(network);
if (networkCapabilities == null) {
return false;
}
boolean isInternetSuspended = !networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED);
return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
&& networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
&& !isInternetSuspended;
} else {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
答案 14 :(得分:0)
此代码可检查所有版本的Android(包括Android 9.0及更高版本)的网络可用性:
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
// For 29 api or above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
} else return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
别忘了在清单中添加网络状态权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
此外,在方法前添加@SuppressWarnings(“ deprecation”),以避免android studio弃用警告。
答案 15 :(得分:0)
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
答案 16 :(得分:0)
如果没有网络连接,则会显示一个对话框错误对话框
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
} else {
new AlertDialog.Builder(this)
.setTitle("Connection Failure")
.setMessage("Please Connect to the Internet")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
答案 17 :(得分:0)
此功能正常工作...
public void checkConnection()
{
ConnectivityManager connectivityManager=(ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo network=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected())
{
//Internet available
}
else if(network.isConnected())
{
//Internet available
}
else
{
//Internet is not available
}
}
向AndroidManifest.xml添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 18 :(得分:0)
使用 ConnectivityManager 服务
来源Link
...
...
import android.net.ConnectivityManager;
....
....
public class Utils {
static ConnectivityManager connectivityManager;
....
....
public static String isOnline(Context context) {
JSONArray array = new JSONArray();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("connected","false");
} catch (JSONException e) {
e.printStackTrace();
}
try {
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
Log.i("networkInfo", networkInfo.toString());
jsonObject.put("connected",(networkInfo != null && networkInfo.isAvailable() &&
networkInfo.isConnected()));
jsonObject.put("isAvailable",(networkInfo.isAvailable()));
jsonObject.put("isConnected",(networkInfo.isConnected()));
jsonObject.put("typeName",(networkInfo.getTypeName()));
array.put(jsonObject);
return array.toString();
} catch (Exception e) {
System.out.println("CheckConnectivity Exception: " + e.getMessage());
Log.v("connectivity", e.toString());
}
array.put(jsonObject);
return array.toString();
}
}
答案 19 :(得分:0)
public static boolean isInternetConnection(Context mContext)
{
ConnectivityManager connectivityManager = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
return true;
}
else {
return false;
}
}
答案 20 :(得分:0)
package com.base64;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import android.widget.Toast;
import com.androidquery.AQuery;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isConnectingToInternet(MainActivity.this))
{
Toast.makeText(getApplicationContext(),"internet is available",Toast.LENGTH_LONG).show();
}
else {
System.out.print("internet is not available");
}
}
public static boolean isConnectingToInternet(Context context)
{
ConnectivityManager connectivity =
(ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
/* manifest */
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.base64">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
答案 21 :(得分:-1)
如果您要检查互联网连接,并且它会更改wifi断开连接或移动数据,则可以使用此库。