Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebView is not loading webpage

I am using WebView for loading a website. But it is very slow and is leaking when specific websites are loaded. I am loading WebView with the following code.

@Override
    protected void onNewIntent(Intent intent) {
        if (intent.getStringExtra("url") != null) {
            webView.loadurl(intent.getStringExtra("url"));

            }
    }

But I am calling webView.loadUrl(Config.URL); (Config.URL may contain same url as specified above) in onCreate() method after initializing WebView with the following.

        this.webView = (WebView) findViewById(R.id.wv);
        this.webView.getSettings().setJavaScriptEnabled(true);
        this.webView.getSettings().setLoadsImagesAutomatically(true);
        this.webView.getSettings().setDomStorageEnabled(true);
        this.webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        MyClient client = new MyClient(WebActivity.this, (ProgressBar)findViewById(R.id.progressBar));
        webView.setWebViewClient(client);

Loading a from onCreate() is working fine (not fine, it's too slow). But the same URL that is loading from onNewIntent() is not working!!!. After I did this inonNewIntent() no URLs got loaded using webView.loadurl() and the current page is getting immovable. ie. the scrollbars are moving in WebView but page is not scrolling. I tested the same URL in onCreate() and it is working.

For doing that I am passing url with

intent.putExtra("url", Config.URL+targetUrl);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

with the pending intent from the notifications. Although it is working in some devices i.e Google Nexus. But it is not working on most of the phones. I have

android:hardwareAccelerated="true"

Myclient

public class MyClient extends WebViewClient{
    private Context context;
    private Activity activity;
    private Handler handler;
    private Runnable runnable;
    private ProgressBar viewBar;
    private String ret,ret2;
    public void setFirstLoad(boolean firstLoad) {
        this.firstLoad = firstLoad;
    }

    private boolean firstLoad=false;
    public MyClient(Activity activity, ProgressBar bar) {
        this.context = activity.getApplicationContext();
        this.activity = activity;
        viewBar=bar;
        handler=new Handler();
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        /*if (url.startsWith("tel:")) {
            Intent intent = new Intent(Intent.ACTION_DIAL,
                    Uri.parse(url));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }else if(url.startsWith("http:") || url.startsWith("https:")) {
            *//*view.setVisibility(View.GONE);
            viewBar.setVisibility(View.VISIBLE);*//*
            view.loadUrl(url);
        }
        return true;*/
        if (Uri.parse(url).getHost().equals("www.somepage.com")) {
            return false;
        }
        // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            Answers.getInstance().logShare(new ShareEvent()
            .putContentId(Build.USER)
            .putMethod(shareName(url))
            .putContentName(contentDecode(url))
            .putContentType("news_share"));
        }catch (android.content.ActivityNotFoundException e){
            Log.e("Activity not found",e.toString());
            Toast.makeText(context,"Application not found",Toast.LENGTH_LONG).show();
        }

        return true;

    }

    @Override
    public void onReceivedError(final WebView view, int errorCode, String description, final String failingUrl) {
        //Clearing the WebView
        try {
            view.stopLoading();
        } catch (Exception e) {
        }
        try {
            view.clearView();
        } catch (Exception e) {
        }
        if (view.canGoBack()) {
            view.goBack();
        }
        view.loadUrl("about:blank");

        //Showing and creating an alet dialog
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);
        alertDialog.setTitle("Error");
        alertDialog.setMessage("No internet connection was found!");
        alertDialog.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                view.loadUrl(failingUrl);

            }
        });
        AlertDialog alert = alertDialog.create();
        alert.show();

        //Don't forget to call supper!
        super.onReceivedError(view, errorCode, description, failingUrl);
    }

    @Override
    public void onLoadResource(final WebView view, String url) {
        super.onLoadResource(view, url);
        //injectScriptFile(view, "js/script.js");
        injectCSS(view,"css/style.css");
        if (firstLoad){
            firstLoad=false;
            view.setVisibility(View.INVISIBLE);
            viewBar.setVisibility(View.VISIBLE);
            runnable=new Runnable() {
                @Override
                public void run() {
                    viewBar.setVisibility(View.GONE);
                    view.setVisibility(View.VISIBLE);
                }
            };
            handler.postDelayed(runnable,2000);
        }

        // test if the script was loaded
       // view.loadUrl("javascript:setTimeout(hideMe(), 200)");
    }

    /*@Override
    public void onPageFinished(final WebView view, String url) {

        //System.gc();
    }*/


    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        System.gc();
    }

The question is: What is the problem when using loadurl() method in onNewIntent()?

like image 661
Kiran Benny Joseph Avatar asked Feb 15 '17 05:02

Kiran Benny Joseph


People also ask

What can I use instead of WebView?

Alternatives to WebView If you want to send users to a mobile site, build a progressive web app (PWA). If you want to display third-party web content, send an intent to installed web browsers. If you want to avoid leaving your app to open the browser, or if you want to customize the browser's UI, use Custom Tabs.

How can I improve my WebView performance?

Enhance webView performance - disable the WebView cache to make WebView much faster. Supercharging the Android WebView - cache critical assets that drastically reduce the load time.

How do I open WebView in browser?

Android Webview open link in browser code snippet. myWebWiev = (WebView)findViewById(R. id. myWebWiev); myWebWiev.

What browser is used in WebView?

On Android 7.0, 8.0 and 9.0, Google Chrome handles the embedded browsing functions. On other Android OS versions, web app performance may suffer without WebView enabled.


2 Answers

Try this from where you loads webview

   web.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }
    });
like image 87
Nazim ch Avatar answered Oct 14 '22 23:10

Nazim ch


You can use the webclient to handle the webview. Here I include the javascript with loading.

         String aboutURL="YOUR URL";

        final ProgressDialog pd = ProgressDialog.show(, "", "Please wait", true);

        WebSettings settings=Webview.getSettings();

        settings.setJavaScriptEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setLoadsImagesAutomatically(true);
        settings.setDatabaseEnabled(true);
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);

        Webview.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon)
            {
                pd.show();
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                pd.dismiss();
            }
        });
        Webview.loadUrl(aboutURL);

Here Loading is processed based on network

like image 25
sivaprakash Avatar answered Oct 14 '22 21:10

sivaprakash