2

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

方法 1通过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();
}

方法 2通过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) 不检查互联网连接,它只检查网络连接!

4

7 回答 7

3

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

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.
        }
    }
}
于 2017-01-09T10:48:38.927 回答
2

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

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;
    }
}

将代码应用到您的活动中:

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

在您的活动方法中注册广播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));
    ..
    ...
    ....
  }

不要忘记在活动周期中取消注册/注册:

@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);

}
于 2017-01-09T10:11:11.057 回答
2

只需检查此链接 这是连接和互联网的答案。

于 2017-01-09T10:21:51.740 回答
2

你可以这样做

使用权限 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;
}
于 2017-01-09T10:23:50.777 回答
0
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;
}

fragment然后只需从您的orActivity中调用此函数即可

于 2017-01-09T10:12:00.200 回答
0

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

    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 网络连接,此代码段也将帮助您识别您的设备是否有互联网连接。

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

于 2017-01-09T10:21:11.383 回答
0

这是我在 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);
      }

这对我来说是准确的。如果您找到任何其他好的解决方案,请尝试让我知道。

于 2017-01-09T11:16:56.407 回答