總網頁瀏覽量

關於我自己

我的相片
人生的必修課是接受無常,人生的選修課是放下執著。

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

沒有留言:

張貼留言