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

发布于 2024-11-25 09:10:21 字数 10563 浏览 0 评论 0原文

我当前正在使用线程加载网页,并且需要在页面加载时显示进度条。实现这个的最好方法是什么?我加载网页的代码是这样的

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

这是我尝试使用 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();
        }
    }
}

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

独木成林 2024-12-02 09:10:21

AsyncTask 将帮助您处理进度。阅读此处: http://developer.android.com/reference/android/os/ AsyncTask.html

An AsyncTask will help handle progress for you. Read here: http://developer.android.com/reference/android/os/AsyncTask.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文