android - 进度条只在加载页面起作用吗?

标签 android webkit webview progress-bar

我在下面的代码中使进度条在第一页加载时工作。当我点击其他链接后,进度条不显示?

如果有人可以告诉我如何更改此代码以使进度条在所有加载过程中正常工作?

谢谢

安德烈。

public class Android_Activity extends Activity {
WebView webview;

@Override
protected void onSaveInstanceState(Bundle outState) {
    WebView webview = (WebView) findViewById(R.id.webview);
    webview.saveState(outState);
}   

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // set the main content view
    setContentView(R.layout.main);

    // check if an instance is stored and so restore it
    if (savedInstanceState != null){
        ((WebView)findViewById(R.id.webview)).restoreState(savedInstanceState);
    }

    final ProgressDialog progressBar = ProgressDialog.show(this, getString(R.string.progress_title),
            getString(R.string.progress_msg));

    webview = (WebView)findViewById(R.id.webview);
    webview.setHttpAuthUsernamePassword(getString(R.string.kdg_host),
            getString(R.string.kdg_realm),
            getString(R.string.kdg_user_name),
            getString(R.string.kdg_password)
            );
    //webview.setWebViewClient(new myWebViewClient());
    webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webview.getSettings().setRenderPriority(RenderPriority.HIGH);
    webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webview.getSettings().setAllowFileAccess(true);
    webview.getSettings().setJavaScriptEnabled(true);

    webview.setWebViewClient(new WebViewClient() {
        public void onPageStarted(WebView view, String url) {
            if (!progressBar.isShowing()) {
                progressBar.show();
            }
        }           
        public void onPageFinished(WebView view, String url) {
            //super.onPageFinished(view, url);
            if (progressBar.isShowing()) {
                progressBar.dismiss();
            }
        }           
    });

    webview.loadUrl(getString(R.string.base_url));
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
        webview.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

private class myWebViewClient extends WebViewClient {   
    @Override       
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        boolean error = false;          

        // check if it's an MAILTO URL
        if(url.substring(0, 6).equalsIgnoreCase("mailto")){
            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            emailIntent .setType("plain/text");
            emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{url.substring(7)});
            startActivity(Intent.createChooser(emailIntent, "Send mail..."));   
            return true;
        }
        // check if it's an EXT:// (Call Web Browser)
        else if(url.substring(0, 6).equalsIgnoreCase("ext://")){
            Uri uriUrl = Uri.parse(url.substring(6));
            Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl); 
            startActivity(launchBrowser);   
            return true;
        }               
        // check if it's an RTSP URL
        else if(url.substring(0, 4).equalsIgnoreCase("rtsp")){
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
            return true;
        }
        // else if it's an MP4 file link
        else if(url.endsWith(".mp4")){
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "video/mp4");
            startActivity(intent);
            return true;
        }
        // else if it's a 3GP file link
        else if(url.endsWith(".3gp")){
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "video/3gp");
            startActivity(intent);
            return true;
        }
        // else if it's a MP3 file link
        else if(url.endsWith(".mp3")){
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "audio/mp3");
            startActivity(intent);
            return true;
        }               
        // else if it's a page URL
        else{
            URL Url;
            try {
                Url = new URL(url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) Url
                        .openConnection();
                int response = httpURLConnection.getResponseCode();
                if ((response >= 200)&&(response < 400))
                    //view.loadUrl(url);
                    error = false;
                else
                    error = true;
            } catch (Exception e) {
                error = true;
            }
        }

        // if an error occurred
        if (error) {
            showErrorDialog();
        }

        view.loadUrl(url);          
        return true;                    
    }
}   

@Override
public void onResume() {
    super.onResume();
    webview.reload();
}   

public void onReceivedError(WebView view, int errorCode,
        String description, String failingUrl) {
    showErrorDialog();
}

public void showErrorDialog(){
    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle(getString(R.string.error_title));
    alertDialog.setMessage(getString(R.string.error_msg));
    alertDialog.setButton(getString(R.string.ok_btn),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,
                        int which) {
                }
            });
    alertDialog.show();
}
}

最佳答案

使用下面的工作代码::

public class Android_Activity extends Activity {
private Android_Activity _activity;
    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);     
            getWindow().requestFeature(Window.FEATURE_PROGRESS);
            _activity = this;   
            setContentView(R.layout.main);

            mwebview=(WebView)view.findViewById(R.id.webview);
            mwebview.getSettings().setJavaScriptEnabled(true);
            mwebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

            if(checkInternetConnection(_activity)==true){
                if(savedInstanceState==null)
                    mwebview.loadUrl(URL);
                else
                    mwebview.restoreState(savedInstanceState);
            }
            else{
                AlertDialog.Builder builder = new AlertDialog.Builder(_activity);
                builder.setMessage("Please check your network connection.")
                       .setCancelable(false)
                       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {

                           }
                       });

                AlertDialog alert = builder.create();    
                alert.show();
            }
            mwebview.setWebChromeClient(new WebChromeClient() {

                @Override
                public void onProgressChanged(WebView view, int progress) { 
                    if(mwebview.getVisibility()==View.VISIBLE)
                    {
                        _activity.setProgress(progress * 100);
                    }
                }
            });
            mwebview.setWebViewClient(new HelloWebViewClient());
        }


        //HelloWebViewClient class for webview
        private class HelloWebViewClient extends WebViewClient {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);
            }
            @Override
            public void onReceivedError(WebView view, int errorCode,
                    String description, String failingUrl) {
                // TODO Auto-generated method stub
                super.onReceivedError(view, errorCode, description, failingUrl);

            }
            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
                view.loadUrl(url);
                return true;
            }

        }   //HelloWebViewClient-class
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            // Check if the key event was the Back button and if there's history
            if ((keyCode == KeyEvent.KEYCODE_BACK) && mwebview.canGoBack() ){
                mwebview.goBack();
                return true;
            }
            // If it wasn't the Back key or there's no web page history, bubble up to the default
            // system behavior (probably exit the activity)
            return super.onKeyDown(keyCode, event);
        }
        //To check whether network connection is available on device or not
            public static boolean checkInternetConnection(Activity _activity) {
                ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (conMgr.getActiveNetworkInfo() != null
                        && conMgr.getActiveNetworkInfo().isAvailable()
                        && conMgr.getActiveNetworkInfo().isConnected()) 
                    return true;
                else
                    return false;
            }//checkInternetConnection()
}

关于android - 进度条只在加载页面起作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9973767/

相关文章:

javascript - Highcharts Legend Selection 在 Android WebView 中双重触发

java - 将输入流传递给其他线程时读取失败

android - 如何为 Android 设备找到正确的来源?

页面 fragment 之间的 Android ViewPager 填充/边距

jQuery $.css() 函数没有正确解释 "animation-delay"(在 webkit 浏览器中!)

xml - 无法在 webview Android 应用程序中打开 pdf

java - 通过 Whatsapp 上的移动链接捕获答案?

css - createjs Canvas 在滚动上重绘

cocoa - 在 OSX 上的 Web View 中显示的 Google map 顶部绘制 subview

javascript - 在android webview中打开javascript