I am creating the application that using
<uses-permission android:name="android.permission.INTERNET" />
And I am using WebView to launch URL. But when mobile didn't connected to WIFI and Internet 3G, in WebView appear exactly URL link.
I don't want user can see the URL link in WebView if no internet connection, how can i do it?
Best Regards, Virak
Check the return of the following function (true for online, false for not) and modify the output depending on what you're after.
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
If what you want is to show a popup or a toast if there is no connectivity, then having that function in your activity will allow you to do the following, which will show the Toast.
if(!haveNetworkConnection()){
Toast.makeText(this,"No internet connection",Toast.LENGTH_LONG).show();
}else{
//Do whatever you need if there IS connectivity
}
I like using the function I'm giving you (have no idea where I copied it from, months ago) because it allows me to easily modify it if I need it to only return true if I have wifi or mobile internet, allowing me for instance to download a high definition video only if the wifi connection is available.
sample code on checking internet connection;
public static boolean checkInternetConnection(Context context) {
ConnectivityManager conMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET?
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
Log.w(TAG, "Internet Connection NOT Present");
return false;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.