Issue
Using an Android WebView, how can I force the application to close if the phone has no internet connection?
Alternatively, if this is not possible, is there any way to show a 404 html page if user is offline.
Here's my code:
public class MainActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_web_view);
webView = (WebView) findViewById(R.id.webView1);
startWebView("http://example.com/appsite/index.php");
}
private void startWebView(String url) {
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
}
Solution
First of all you have to try some code or search better, this kind of question was already done a lot here in this community.
Well, below is some code that can help you in your problem:
Create a method that check if has or not connectivity
public boolean hasConnectivity(Context context) {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager
.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isAvailable()
&& networkInfo.isConnected();
} else {
return false;
}
}
And then, call in your onCreate method:
if (hasConnectivity(this)) {
startWebView("http://example.com/appsite/index.php");
} else {
Toast.makeText(this, "you do not have connection", Toast.LENGTH_LONG).show();
}
Remember to add in your AndroidManifest.xml this permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Answered By - uiltonsantos
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.