總網頁瀏覽量

關於我自己

我的相片
人生的必修課是接受無常,人生的選修課是放下執著。
顯示具有 Progress 標籤的文章。 顯示所有文章
顯示具有 Progress 標籤的文章。 顯示所有文章

2012年1月21日 星期六

連上網際網路~WebView.loadUrl~搭配Progress Dialog與ACCESS_NETWORK_STATE權限







一開始的畫面
正在讀取網頁中


為取得網路的權限, 記得在Manifest.xml加上<uses-permission android:name="android.permission.INTERNET"/>, 按下ImageButton後會產生兩種結果:
1. 正確load到網頁->透過Handler關掉Progress
2. 沒有訊號or網路太慢->透過Handler關掉Progress
本範例設計超過15秒仍未載到網頁則判定為情況2., 然後用Toast提示user稍候再試.

另外在主程式中加入checkInternet(android.content.Context context)來判定Device目前有無網路服務, Manifest.xml要先加入<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>喔!
網頁讀取完畢!會主動關掉Progress哦
超過15秒了還沒下載完


package com.tsots.WebView_loadUrl;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;

public class WebView_loadUrl extends Activity
{
  Context context = WebView_loadUrl.this;
  ProgressDialog myDialog = null;  
  ImageButton mImageButton1;
  EditText mEditText1;
  ProgressBar progressbar;
  WebView mWebView1;
  String TAG = "WebView_loadUrl.this";
    
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   
    mImageButton1 = (ImageButton)findViewById(R.id.myImageButton1);
    mEditText1 = (EditText)findViewById(R.id.myEditText1);
    mEditText1.setText("http://www.eprice.com.tw/");
    progressbar = (ProgressBar) findViewById (R.id.progressbar1);
    mWebView1 = (WebView) findViewById(R.id.myWebView1);
    final String str_dialog_title = getResources().getString(R.string.str_dialog_title);
    
    mWebView1.setWebViewClient(new WebViewClient() 
    {
      @Override
      public void onPageFinished(WebView view, String url)
      {
        handler.sendEmptyMessage(0);
        super.onPageFinished(view, url);
      }
    });
    
    mImageButton1.setOnClickListener(new ImageButton.OnClickListener()
    {
      public void onClick(View arg0)
      {
        {                    
          //mImageButton1.setImageResource(R.drawable.ok_2);
          mImageButton1.setBackgroundDrawable(getResources().getDrawable(R.drawable.ok_2));
          if (checkInternet(context) == true)
          {
            String strURI = (mEditText1.getText().toString());
            progressbar.setVisibility(View.VISIBLE);
            myDialog = ProgressDialog.show
            (
              context,
              str_dialog_title,
              getString(R.string.load)+strURI, 
              true
            );
            /*
             * 1. 當使用者按下button後, 顯示Progress Bar
             * 2. 擷取網路資料
             * 需在Manifest.xml加入權限:INTERNET
             */
            mWebView1.setVisibility(View.VISIBLE);
            mWebView1.loadUrl(strURI);
            fun_thread(); 
          }
          else
          {
            Toast.makeText(context, getResources().getString(R.string.toast_check_network), Toast.LENGTH_SHORT).show();
          }
          
        }
      }
    });
  }
  
  public void fun_thread()
  {
      new Thread()
      { 
        public void run()
        { 
          try
          { 
           //若15後仍未讀到網頁, 則顯示網路雍塞中
           for(int i=0; i<15; i++)
           {
            sleep(1000);   
           }           
          }
          catch (Exception e)
          {
            e.printStackTrace();
          }
          //為了能與handler建立關聯進而控制Progress Dialog / Progress Bar的關閉
          Message m = new Message();
          Bundle b = m.getData();
          b.putInt("WHICH", 1);
          m.setData(b);
          handler.sendMessage(m);          
        }
      }.start(); 
  }

  /*
   * 透過Handler將Progress Dialog / Progress Bar關閉
   */
  Handler handler = new Handler()
  {
      public void handleMessage(Message msg)
      {         
          int which = msg.getData().getInt("WHICH");
          progressbar.setVisibility(View.GONE);
          myDialog.dismiss();
          if(which == 1)
          {
            Toast.makeText(context, getString(R.string.str_busy), Toast.LENGTH_SHORT).show();
          }
      }
  };
  
  /*
   * 判別網路連線狀態
   * 需在Manifest.xml加入權限:ACCESS_NETWORK_STATE
   */
  public boolean checkInternet(android.content.Context context)
  {    
    boolean result = false;
    ConnectivityManager connManager = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);    
    NetworkInfo info = connManager.getActiveNetworkInfo();
    if (info == null || !info.isConnected())
    {
      Log.d(TAG, "info == null || !info.isConnected()");
      result = false;
    }
    else
    {
      if (!info.isAvailable())
      {
        Log.d(TAG, "!info.isAvailable()");
        result = false;
      }
      else
      {
        Log.d(TAG, "info.isAvailable()");
        result = true;
      }
    }
    return result;
  }
}

2012年1月20日 星期五

ProgressDialog~ProgressBar~搭配Handler顯示執行進度

本範例重點在於比較Google Default 的 Progress.
以4個Button分別啟動Progress Dialog / Progress Bar的圓與長條圖.
當Progress Dialog啟動時Activity模糊化(blur)進入OnPause()狀態, 並以執行緒(Thread)模擬事件進度.

在layout中加這一行android:visibility="gone"隱藏ProgressBar, 後兩種Button在使用者點選後, 才設為可見的setVisibility(View.VISIBLE), 而長條形的ProgressBar要特別在layout中定義style="?android:attr/progressBarStyleHorizontal"還有android:max="100"唷~








package com.tsots.Default_Progress;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class DefaultProgress extends Activity
{
  Context context = DefaultProgress.this;
  Button button1;
  Button button2;
  Button button3;
  Button button4;
  ProgressDialog myDialog = null;
  ProgressBar progressbar1;
  ProgressBar progressbar2;
  String which_progress = null;
  TextView text_percent;
  TextView text_progressbar1;
  TextView text_progressbar2;
  
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    button1 =(Button) findViewById (R.id.button1);
    button2 =(Button) findViewById (R.id.button2);
    button3 =(Button) findViewById (R.id.button3);
    button4 =(Button) findViewById (R.id.button4);
    progressbar1 = (ProgressBar) findViewById (R.id.progressbar1);
    progressbar2 = (ProgressBar) findViewById (R.id.progressbar2);
    text_percent = (TextView) findViewById (R.id.text_percent);
    text_progressbar1 = (TextView) findViewById (R.id.text_progressbar1);
    text_progressbar2 = (TextView) findViewById (R.id.text_progressbar2);
    
    final CharSequence str_Dialog_Title = getResources().getString(R.string.str_dialog_title);
    final CharSequence str_Dialog_Contents = getResources().getString(R.string.str_dialog_body);
    
    button1.setOnClickListener(new Button.OnClickListener()
    {
        public void onClick(View arg0)
        {
          which_progress = "progress_dialog";
          myDialog = ProgressDialog.show
                     (
                       context,
                       str_Dialog_Title,
                       str_Dialog_Contents, 
                       true
                     );
          fun_thread();  
        }
    });

    /*
     * 長條形的Progress, 起始值0, 最大值100
     */
    button2.setOnClickListener(new Button.OnClickListener()
    {
        public void onClick(View arg0)
        {
          which_progress = "progress_dialog";
          final CharSequence str_Dialog_Contents = getResources().getString(R.string.str_dialog_body);
          myDialog = new ProgressDialog(context);
          myDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
          myDialog.setProgress(0);
          myDialog.setMax(100);
          myDialog.setTitle(str_Dialog_Title);
          myDialog.setMessage(str_Dialog_Contents);
          myDialog.show();
          fun_thread();   
        }
    });
    
    button3.setOnClickListener(new Button.OnClickListener()
    {
        public void onClick(View arg0)
        {
          which_progress = "progress_bar1";
          progressbar1.setVisibility(View.VISIBLE);
          progressbar1.setProgress(0);
          progressbar1.setMax(100);
          text_progressbar1.setText(R.string.str_dialog_title);
          fun_thread();   
        }
    });
    
    button4.setOnClickListener(new Button.OnClickListener()
    {
        public void onClick(View arg0)
        {
          which_progress = "progress_bar2";
          progressbar2.setVisibility(View.VISIBLE);
          progressbar2.setProgress(0);
          progressbar2.setMax(100);  
          text_progressbar2.setText(R.string.str_dialog_body);
          fun_thread();   
        }
    });
  }
  
  /*
   * 透過Handler傳遞執行序的狀態
   */
  Handler handler = new Handler()
  {
      public void handleMessage(Message msg)
      {
        int p = msg.getData().getInt("PERCENT");
        //當事件進度抵達100時, 關掉/隱藏 ProgressDialog/ProgressBar
        if(p > 100)
        {          
            if(which_progress.equals("progress_dialog"))
            {
              myDialog.dismiss();
            }
            else if(which_progress.equals("progress_bar1"))
            {
              progressbar1.setVisibility(View.GONE);
              text_progressbar1.setText("");
            }
            else
            {
              progressbar2.setVisibility(View.GONE);
              text_progressbar2.setText("");
              text_percent.setText("");
            }
        }
        else
        {
          if(which_progress.equals("progress_dialog"))
          {
            myDialog.setProgress(p);
          }
          else if(which_progress.equals("progress_bar2"))
          {
            progressbar2.setProgress(p);
            text_percent.setText(p+"%");
          }
        }
      }
  };
  
  /*
   * 執行緒, 每隔一秒遞增值1, 用來模擬事件進度
   */
  public void fun_thread()
  {
      new Thread()
      { 
        public void run()
        { 
          try
          { 
            for(int i=0; i<6; i++)
            {
              sleep(1000);
              int percent = (i+1)*20;
              Message m = new Message();
              Bundle b = m.getData();
              b.putInt("PERCENT", percent);
              m.setData(b);
              handler.sendMessage(m);
            }
          }
          catch (Exception e)
          {
            e.printStackTrace();
          }
          finally
          {
            //myDialog.dismiss();
          }
        }
      }.start(); 
  }
}