检查 android 中的互联网连接(不是网络连接)

Check internet connection in android (not network connection)

我在运行时检查 android 中的互联网连接时遇到问题。 我使用一些不同的方法来检查互联网连接,但我不知道哪种方法更好。因为他们每个人都有一些问题。

方法一 通过 ping Google 检查互联网连接:

Runtime runtime = Runtime.getRuntime();
try {
       Process mIpAddressProcess = runtime.exec("/system/bin/ping -c 1   8.8.8.8");
       int mExitValue = mIpAddressProcess.waitFor();
       return mExitValue == 0;
} catch (InterruptedException | IOException ignore) {
            ignore.printStackTrace();
}

方法二 通过 ConnectivityManager 检查互联网连接:

public boolean checkNetwork() {

    ConnectivityManager internetManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = internetManager.getActiveNetworkInfo();
    return (networkInfo != null && networkInfo.isConnected() && networkInfo.isAvailable() && networkInfo.isConnectedOrConnecting());

}

我在异步任务中使用了方法 1,但它有时无法正常工作并且会降低应用程序的速度, 方法 2 (ConnectivityManager) 不检查互联网连接,它只检查网络连接!

我每次都使用广播来检查连接。为连接信息创建 class。

import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


public class ConnectivityStatus extends ContextWrapper{

    public ConnectivityStatus(Context base) {
        super(base);
    }

    public static boolean isConnected(Context context){

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo connection = manager.getActiveNetworkInfo();
        if (connection != null && connection.isConnectedOrConnecting()){
            return true;
        }
        return false;
    }
}

将代码应用到您的 Activity:

 private BroadcastReceiver receiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
        if(!ConnectivityStatus.isConnected(getContext())){
            // no connection
        }else {
            // connected
        }
    }
 };

在您的 activity 的 onCreate() 方法中注册广播:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    ..
    ...
    ....
  }

不要忘记 unregistered/register Activity 周期:

@Override
protected void onResume() {
    super.onResume();
    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

}

@Override
protected void onPause() {
    super.onPause();
    your_activity_context.unregisterReceiver(receiver);

}
public static boolean isNetworkAvailable(Context context) {
    try {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService
                (Context.CONNECTIVITY_SERVICE);
        if (connManager.getActiveNetworkInfo() != null && connManager.getActiveNetworkInfo()
                .isAvailable() && connManager.getActiveNetworkInfo().isConnected()) {
            return true;
        }
    } catch (Exception ex) {

        ex.printStackTrace();
        return false;
    }
    return false;
}

然后只需从您的 fragmentActivity 调用此函数即可

要检查互联网连接是否可用,您可以使用以下代码片段

    public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) 
                    (new URL("http://clients3.google.com/generate_204")
                    .openConnection());
            urlc.setRequestProperty("User-Agent", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(LOG_TAG, "No network available!");
    }
    return false;
}

即使您通过 wifi 网络连接,此代码段也将帮助您确定您的设备是否有互联网连接。

注意:请务必在后台线程中调用此方法,因为这可能需要一些时间,具体取决于您的网络速度,并且不应在主线程中调用

只需检查一下 LINK 这是连接和互联网的答案。

你可以这样做

使用权限android:name="android.permission.INTERNET"

使用权限android:name="android.permission.ACCESS_NETWORK_STATE"

 private boolean checkInternet(Context context) {
    // get Connectivity Manager object to check connection
    ConnectivityManager connec
            =(ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);

    // Check for network connections
    if ( connec.getNetworkInfo(0).getState() ==
            android.net.NetworkInfo.State.CONNECTED ||
            connec.getNetworkInfo(0).getState() ==
                    android.net.NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() ==
                    android.net.NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
        Toast.makeText(context, " Connected ", Toast.LENGTH_LONG).show();
        return true;
    }else if (
            connec.getNetworkInfo(0).getState() ==
                    android.net.NetworkInfo.State.DISCONNECTED ||
                    connec.getNetworkInfo(1).getState() ==
                            android.net.NetworkInfo.State.DISCONNECTED  ) {
        Toast.makeText(context, " Not Connected ", Toast.LENGTH_LONG).show();
        return false;
    }
    return false;
}

您可以使用以下代码检查网络连接是否可用。

public class NetworkConnection {
    public Context context;

    public NetworkConnection(Context applicationContext) {
        this.context=applicationContext;
    }

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }
}

public class MainActivity extends AppCompatActivity {
    NetworkConnection nt_check;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        nt_check=new NetworkConnection(context);
        if(nt_check.isOnline()) {
            // do logic
        } else {
            // show message network is not available.
        }
    }
}

这是我在 android 中尝试检查互联网连接的方法,它不是一个圆滑的解决方案,但如果您 已经检查了网络 :

try {
      HttpURLConnection urlConnection = (HttpURLConnection)
      (new URL("http://clients3.google.com/generate_204")
      .openConnection());
      urlConnection.setRequestProperty("User-Agent", "Android");
      urlConnection.setRequestProperty("Connection", "close");
      urlConnection.setConnectTimeout(1500);
      urlConnection.connect();
      if (urlConnection.getResponseCode() == 204 &&
      urlConnection.getContentLength() == 0) {
      Log.d("Network Checker", "Successfully connected to internet");
      return true;
      }
      } catch (IOException e) {
      Log.e("Network Checker", "Error checking internet connection", e);
      }

对于 me.Try 准确 如果您找到任何其他好的解决方案,请告诉我。