デバイスがインターネットに接続されているかどうかを確認したい。私は多くの解決策を見つけましたが、例では次のようなことはできません:
if(device has Internet connection){
webview.loadUrl("http://the.url.com")
}
else{
Toast.makeText(context, text, duration).show()
}
デバイスがインターネットに接続されているかどうかを確認したい。私は多くの解決策を見つけましたが、例では次のようなことはできません:
if(device has Internet connection){
webview.loadUrl("http://the.url.com")
}
else{
Toast.makeText(context, text, duration).show()
}
接続を確認するクラスにこのメソッドを配置します。
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
次に、接続を確認する必要がある場合は、これを実行します(例を使用):
if(isOnline(getApplicationContext()){
webview.loadUrl("http://the.url.com")
}
else{
Toast.makeText(context, text, duration).show()
}
ExampleClass.isOnline() のように、そのメソッドをクラスで作成し、そこから常に使用することもできます。
これを AndroidManifest に追加することを忘れないでください:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
これは小さな例です:
try {
URL url = new URL("http://the.url.com");
URLConnection conn = url.openConnection();
conn.connect();
webview.loadUrl("http://the.url.com");
} catch (MalformedURLException e) {
// the URL is not in a valid form
Toast.makeText(context, text, duration).show();
} catch (IOException e) {
// the connection couldn't be established
Toast.makeText(context, text, duration).show()
}