简体   繁体   English

在 android 中加载网页时使用进度条

[英]Using a progress Bar while I load a webpage in android

I'm currently loading a webpage using a thread and I need a progress bar to display while the page loads up.我目前正在使用线程加载网页,我需要在页面加载时显示进度条。 Whats the best way to implement this?实现这一点的最佳方法是什么? My code to load the webpage is this我加载网页的代码是这样的

private Thread checkUpdate = new Thread() {

        @Override
        public void run() {
            try {
                /**
                 * establish a URL connection
                 */

                URL updateURL = new URL("http://www.mtsu.edu/alertupdates/");
                URLConnection conn = updateURL.openConnection();

                /**
                 * create an Input stream and buffered array to
                 * prepare for parsing.
                 */
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                /**
                 * read in the html and parse it to bytes.
                 */

                int current = 0;
                while((current = bis.read()) != -1){
                    baf.append((byte)current);
                }

                /**
                 *  Convert the Bytes read to a String. 
                 */

                html = new String(baf.toByteArray());
                int position = html.indexOf("<h1>");
                int position2 = html.indexOf("<!--",position);
                html = html.substring(position, position2);
                mHandler.post(showUpdate);
            } catch (Exception e){}
        }
    };

Here is my attempt at Using AsyncTask and the entire code of my project.这是我尝试使用 AsyncTask 和我的项目的整个代码。

package com.MTSUAndroid;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import java.lang.String;
import android.content.Context;

public class Alerts extends Activity {
    /**
     * private variables to hold the html strings for parsing.
     */
    private String html = "";
    private Handler mHandler;
    private TextView text1;
    private TextView timestamp;
    private Button home;
    private Button refresh;
    private ProgressDialog myProgress;
    private int myProgressStatus = 0;

    private Handler myHandler = new Handler();


    /**
     * overriding on create with a new handler for threading
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alerts);
        initialControls();
        //mHandler = new Handler();
        //checkUpdate.start();
   }

   public void connectivityMessage(String msg){
        Context context = getApplicationContext();
        Toast toast = Toast.makeText(context, "", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setText(msg);
        toast.show();
   }

    /**
     * InitialControls function to set up all the initial controls for the GUI
     * Such as buttons, etc...
     */
    private void initialControls(){
    text1 = (TextView)findViewById(R.id.textView1);
    home = (Button)findViewById(R.id.home_button);
    //myProgress = (ProgressBar)findViewById(R.id.progressBar1);

        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        /**
         * TimeStamp for the alerts refresh button
         */
    timestamp = (TextView)findViewById(R.id.timestamp); 
    refresh = (Button)findViewById(R.id.update);

    /**
     * implementing the refresh button/loading the website
     */

    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                /**
                 * establish a URL connection
                 */
                URL updateURL = new URL("http://www.mtsu.edu/alertupdates/");
                URLConnection conn = updateURL.openConnection();

                /**
                 * create an Input stream and buffered array to
                 * prepare for parsing.
                 */

                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                /**
                 * read in the html and parse it to bytes.
                 */

                int current = 0;
                while((current = bis.read()) != -1){
                    baf.append((byte)current);
                }

                /**
                 *  Convert the Bytes read to a String. 
                 */

                html = new String(baf.toByteArray());
                int position = html.indexOf("<h1>");
                int position2 = html.indexOf("<!--",position);
                html = html.substring(position, position2);
                mHandler.post(showUpdate);

                /**
                 * using calendar class for the refresh button
                 */

                Calendar c = Calendar.getInstance(); 
                int seconds = c.get(Calendar.SECOND);
                int minutes = c.get(Calendar.MINUTE);
                int hours = c.get(Calendar.HOUR);
                int years = c.get(Calendar.YEAR);
                int months = 1 + c.get(Calendar.MONTH);
                int days = c.get(Calendar.DAY_OF_MONTH);

                try{
                    if (c.get(Calendar.AM_PM) == 0)
                    {
                        String AM = "";
                        AM = "AM";
                        if (hours == 0)
                        {
                            hours = 12;
                        }
                        timestamp.setText("Refreshed on " + days + "-"
                        + months + "-" + years + " " +  hours + ":" + minutes + ":" + seconds + " " + AM);
                        timestamp.setTextSize(17f);
                        timestamp.setTextColor(Color.GREEN);
                    }
                    else
                    {
                        String PM = "";
                        PM = "PM";
                        timestamp.setText("Refreshed on " + days + "-"
                        + months + "-" + years + " " +  hours + ":" + minutes + ":" + seconds + " " + PM);
                        timestamp.setTextSize(17f);
                        timestamp.setTextColor(Color.GREEN);
                    }
                }
                catch (Exception e){}       
            }

            /**
             * Catch exception E to catch all errors.
             */
            catch (Exception e) {}
            }
        }
    );}

    /**
     * creating a new thread to run the URL.
     */
    private Thread checkUpdate = new Thread() {

        @Override
        public void run() {
            try {
                /**
                 * establish a URL connection
                 */

                URL updateURL = new URL("http://www.mtsu.edu/alertupdates/");
                URLConnection conn = updateURL.openConnection();

                /**
                 * create an Input stream and buffered array to
                 * prepare for parsing.
                 */
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                /**
                 * read in the html and parse it to bytes.
                 */

                int current = 0;
                while((current = bis.read()) != -1){
                    baf.append((byte)current);
                }

                /**
                 *  Convert the Bytes read to a String. 
                 */

                html = new String(baf.toByteArray());
                int position = html.indexOf("<h1>");
                int position2 = html.indexOf("<!--",position);
                html = html.substring(position, position2);
                mHandler.post(showUpdate);
            } catch (Exception e){}
        }
    };

    /**
     * set the textView to the freshly parsed html for viewing
     */

    private Runnable showUpdate = new Runnable(){
        @Override
        public void run(){
            text1.setText(Html.fromHtml(html));
        }
    };

    public class myTask extends AsyncTask<Void,Void,Void>{
        ProgressDialog progress;
        public myTask(ProgressDialog progress) {
            this.progress = progress;   
        }
        @Override
        protected void onPreExecute() {
            progress = ProgressDialog.show(Alerts.this, "Loading data..", "Please Wait");
            super.onPreExecute();
        }
        @Override
        protected Void doInBackground(Void... params) {
            try {
                /**
                 * establish a URL connection
                 */

                URL updateURL = new URL("http://www.mtsu.edu/alertupdates/");
                URLConnection conn = updateURL.openConnection();

                /**
                 * create an Input stream and buffered array to
                 * prepare for parsing.
                 */
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                /**
                 * read in the html and parse it to bytes.
                 */

                int current = 0;
                while((current = bis.read()) != -1){
                    baf.append((byte)current);
                }

                /**
                 *  Convert the Bytes read to a String. 
                 */

                html = new String(baf.toByteArray());
                int position = html.indexOf("<h1>");
                int position2 = html.indexOf("<!--",position);
                html = html.substring(position, position2);
                mHandler.post(showUpdate);
            } catch (Exception e){}
            return null;
        }
        protected void onPostExecute() {
            progress.dismiss();
        }
    }
}

An AsyncTask will help handle progress for you. AsyncTask 将帮助您处理进度。 Read here: http://developer.android.com/reference/android/os/AsyncTask.html在这里阅读: http://developer.android.com/reference/android/os/AsyncTask.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM