我在运行时检查 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) 不检查互联网连接,它只检查网络连接!
最佳答案
您可以使用下面的代码来检查网络连接是否可用。
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 - 检查 android 中的互联网连接(不是网络连接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41545504/