检查android中的互联网连接(不是网络连接)
作者:互联网
我在运行时检查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)不检查互联网连接,它只检查网络连接!
解决方法:
我每次都使用广播来检查连接.创建连接信息的类.
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);
}
标签:internet-connection,android-networking,android,android-connectivitymanager 来源: https://codeday.me/bug/20191002/1843797.html