我在运行时检查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)不检查互联网连接,它只检查网络连接!
答案 0 :(得分:3)
我每次都使用广播检查连接。为连接信息创建一个类。
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);
}
答案 1 :(得分: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.
}
}
}
答案 2 :(得分:2)
请检查LINK 这是Connection& amp;的答案。因特网。
答案 3 :(得分:2)
你可以这样做
uses-permission android:name =" android.permission.INTERNET"
uses-permission 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;
}
答案 4 :(得分: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
或Activity
调用此功能即可
答案 5 :(得分: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网络连接也是如此。
注意:请确保在后台线程中调用此方法,因为这可能需要一些时间,具体取决于您的网络速度,并且不应在主线程中调用
答案 6 :(得分: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);
}
对我而言 准确 。如果您找到其他任何好的解决方案,请试着告诉我。