Hasan
Hasan

Reputation: 36

How to close an android app if webview is not able to load a webpage

Basically my android app loads a link on a webview which i do not want to be displayed if there is no internet connection, so i want to either force close the app or hide the link from the user. Below is my code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class AndroidMobileAppSampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    WebView mainWebView = (WebView) findViewById(R.id.mainWebView);

    WebSettings webSettings = mainWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    mainWebView.setWebViewClient(new MyCustomWebViewClient());
    mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    mainWebView.loadUrl("my link which should not be displayed to user");
}

private class MyCustomWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
}`enter code here`

i have tried connection manager, finish(),System.out.exit(0) and other functions, but it does not kill the app. So any help would be great.

Upvotes: 0

Views: 1589

Answers (2)

Hasan
Hasan

Reputation: 36

I got an answer just type the code

mWebView.setWebViewClient(new WebViewClient() {
   public void onReceivedError(WebView view, int errorCode, 
    String description, String failingUrl) {
      mWebView.loadUrl("file:///android_asset/myerrorpage.html");

    }
});`

` This will take care of hiding the url from the user

Upvotes: 0

Mohammad Rahchamani
Mohammad Rahchamani

Reputation: 5220

try this :

private class MyCustomWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, 
             String description, String failingUrl) {
        AndroidMobileAppSampleActivity.this.finish();
    }
}

Upvotes: 1

Related Questions