更新:回避するためにコードを更新しましたNetworkOnMainThreadException
現在、次の方法を使用して、デバイスがインターネットにアクセスできるかどうかを判断しています。
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);
}
}
これを次のように呼び出します。
@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
}
}
});
....
}
お役に立てれば!