UPDATE: aggiornati i codici per evitare NetworkOnMainThreadException
Attualmente sto usando il seguente metodo per determinare se il dispositivo può accedere a Internet o no:
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);
}
}
chiamata questo:
@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
}
}
});
....
}
speranza che questo aiuti!
Questo forzerà sulle versioni successive di Android per l'utilizzo di una connessione di rete sul thread principale. Inoltre, sulla rete wifi su cui ho eseguito il test è necessario il login, questo test è stato comunque restituito come connesso quando non dovrebbe. – schwiz