UPDATE: cập nhật các mã để tránh NetworkOnMainThreadException
Tôi hiện đang sử dụng các phương pháp sau đây để xác định xem thiết bị có thể truy cập vào internet hay không:
public class NetworkConnectivityHelper {
public void isDeviceConnectedToInternet(final Activity activity, final ResultCallback callback){
new Thread(new Runnable() {
@Override
public void run() {
boolean isDeviceConnectedToInternet = false;
NetworkInfo activeNetworkInfo = ((ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if(activeNetworkInfo != null && activeNetworkInfo.isConnected()){
try {
InetAddress.getByName("google.com").isReachable(2);
isDeviceConnectedToInternet = true;
} catch (UnknownHostException e){
isDeviceConnectedToInternet = false;
} catch (IOException e){
isDeviceConnectedToInternet = false;
}
}
final boolean result = isDeviceConnectedToInternet;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
callback.done(result);
}
});
}
}).start();
}
public static abstract class ResultCallback{
public abstract void done(boolean connected);
}
}
cuộc gọi này bằng cách:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
//Populate
NetworkConnectivityHelper networkConnectivityHelper = new NetworkConnectivityHelper();
networkConnectivityHelper.isDeviceConnectedToInternet(activity, new NetworkConnectivityHelper.ResultCallback() {
@Override
public void done(boolean connected) {
if (connected) {
//Yey, the device is connected.
//Now, do some work
}else{
//The device is disconnected
}
}
});
....
}
hy vọng điều này giúp!
Thao tác này sẽ hủy xuất hiện trên các phiên bản Android mới hơn để sử dụng kết nối mạng trên chuỗi chính. Ngoài ra, trên mạng wifi tôi đã thử nghiệm trên đó yêu cầu đăng nhập, kiểm tra này vẫn trở lại như được kết nối khi nó không nên. – schwiz