【问题标题】:Progress bar only work on loading page?进度条仅适用于加载页面?
【发布时间】:2012-04-02 09:18:47
【问题描述】:

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

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

谢谢,

安德烈。

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

【问题讨论】:

    标签: android webkit webview progress-bar


    【解决方案1】:

    使用下面的工作代码::

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

    【讨论】:

    • 这行好像有问题:getApplicationContext().setProgress(progress * 100); setProgress : Context 类型的方法 setProgress(int) 未定义
    • 工作得更好,网页加载,但进度条没有消失?
    • 不,我在屏幕中间看到“进度条”,它是一个带有标题和圆轮的框。
    • 对不起,我没有使用好代码,我使用的是旧版本...我在状态栏中看不到活动。
    • 您知道如何在加载过程中在网页上放置一个背面透明层吗?
    【解决方案2】:
    <?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> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多