进度条仅适用于加载页面?

时间:2012-04-02 09:18:48

标签: android webkit webview progress-bar

我在以下代码中处理第一页加载的进度条。在我点击其他链接后,没有显示progrss栏?

如果有人可以告诉我如何更改此代码以使进度条适用于所有加载?

谢谢,

安德烈。

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();
}
}

2 个答案:

答案 0 :(得分:2)

使用以下工作代码::

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()
}

答案 1 :(得分:0)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.KDG_EPG_Iphone"
  android:versionCode="1"
  android:versionName="1.00.00" android:installLocation="auto">
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

  <supports-screens 
    android:resizeable="false"
    android:smallScreens = "false"
    android:normalScreens = "true"
    android:largeScreens = "false"
    android:anyDensity = "true"/>
  <uses-sdk android:minSdkVersion="8"/>

<application android:label="@string/app_name" android:icon="@drawable/icon">
    <activity android:screenOrientation="portrait"
              android:theme="@android:style/Theme.Black.NoTitleBar"
              android:configChanges="keyboardHidden|orientation"
              android:label="@string/app_label" android:name="com.KDG_EPG_Iphone.KDG_EPG_Iphone_Activity" android:icon="@drawable/icon">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity> 
</application>


</manifest>