android 用webview自制帶有history和download功能的瀏覽器

package com.mysession;
 
import java.util.ArrayList;
 import java.util.List;
 
import android.app.Activity;
 import android.content.Intent;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Matrix;
 import android.graphics.Picture;
 import android.net.Uri;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.webkit.CookieManager;
 import android.webkit.CookieSyncManager;
 import android.webkit.DownloadListener;
 import android.webkit.ValueCallback;
 import android.webkit.WebChromeClient;
 import android.webkit.WebHistoryItem;
 import android.webkit.WebSettings;
 import android.webkit.WebView;
 import android.webkit.WebViewClient;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.GridView;
 import android.widget.ProgressBar;
 
import com.mysession.model.HistoryModel;
 
public class D_sessionActivity extends Activity implements OnClickListener,
         DownloadListener {
 
    private static final String TAG = "TAG";
     // private String detailUrl =
     // "https://www.google.com";
     // private String detailUrl =
     // "https://172.20.230.67:8900/iportal/servlet/GetMobileContent?&user=administrator&vol=allen_iServer&profile=myserver&password=uaABd7AZ0ThXe6WFM2FdqA%3D%3D&respFormat=html&subID=7fb249ba-1470-4663-9863-a743c740aeeb&enc=1";
 
    // private String detailUrl = "https://music.sogou.com/";
     private WebView webview;
     private Button btnLoad, btnReset, btnHistory, btnBack, btnForward;
     private EditText etUrl;
     private ProgressBar mProgressBar;
     private GridView mGridView;
     private CookieManager cookieManager;
     private BrowserHistoryAdapter browserHistoryAdapter;
     private List<HistoryModel> historyModels = new ArrayList<HistoryModel>();
 
    /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
 
        CookieSyncManager.createInstance(this);
         cookieManager = CookieManager.getInstance();
 
        webview = (WebView) findViewById(R.id.webView1);
         btnLoad = (Button) findViewById(R.id.btnLoad);
         btnReset = (Button) findViewById(R.id.btnReset);
         btnHistory = (Button) findViewById(R.id.btnHistory);
         mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
         etUrl = (EditText) findViewById(R.id.etUrl);
         btnBack = (Button) findViewById(R.id.btnBack);
         btnForward = (Button) findViewById(R.id.btnForward);
         mGridView = (GridView) findViewById(R.id.gridView1);
 
        btnLoad.setOnClickListener(this);
         btnReset.setOnClickListener(this);
         btnHistory.setOnClickListener(this);
         btnBack.setOnClickListener(this);
         btnForward.setOnClickListener(this);
 
        webview.getSettings().setJavaScriptEnabled(true);
         webview.setWebViewClient(new BirtMobileWebViewClient());
         webview.setWebChromeClient(new GeoClient());
         webview.setDownloadListener(this);
         webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
 
        // WebBackForwardList history = webview.copyBackForwardList();
         // if (history != null) {
         // browserHistoryAdapter = new BrowserHistoryAdapter(history, this);
         // mGridView.setAdapter(browserHistoryAdapter);
         // }
 
        webview.setVisibility(View.VISIBLE);
         mGridView.setVisibility(View.GONE);
     }
 
    @Override
     public void onClick(View v) {
         if (v == btnLoad) {
             cookieManager.setAcceptCookie(true);
             webview.setVisibility(View.VISIBLE);
             mGridView.setVisibility(View.GONE);
 
            if (!"".equalsIgnoreCase(etUrl.getText().toString())) {
                 webview.loadUrl(etUrl.getText().toString());
             }
 
        } else if (v == btnReset) {
             cookieManager.removeAllCookie();
         } else if (v == btnHistory) {
             if (webview.copyBackForwardList() == null) {
                 return;
             } else {
                 webview.setVisibility(View.GONE);
                 mGridView.setVisibility(View.VISIBLE);
 
                if (browserHistoryAdapter == null) {
                     browserHistoryAdapter = new BrowserHistoryAdapter(
                             historyModels, this);
                     mGridView.setAdapter(browserHistoryAdapter);
 
                } else {
                     browserHistoryAdapter.setHostory(historyModels);
                     browserHistoryAdapter.notifyDataSetChanged();
                 }
             }
 
        } else if (v == btnBack) {
             webview.goBack();
         } else if (v == btnForward) {
             webview.goForward();
         }
     }
 
    // create a webview client that handles mailto links within the webview
     private class BirtMobileWebViewClient extends WebViewClient {
         @Override
         public boolean shouldOverrideUrlLoading(WebView view, String url) {
             Log.d("——redirect:—–", url);
             return false;
         }
 
        @Override
         public void onPageStarted(WebView view, String url, Bitmap favicon) {
             etUrl.setText(url);
             Log.d(TAG + "start:", url);
         }
 
        @Override
         public void onPageFinished(WebView view, String url) {
             HistoryModel historyModel = new HistoryModel();
 
// 獲取瀏覽器history,包含id,name,url等
 
            WebHistoryItem item = webview.copyBackForwardList()
 
                    .getCurrentItem();
 
//為browser history獲取瀏覽器頁面快照
 
            Picture snapShot = view.capturePicture();
 
            if (snapShot.getWidth() > 0 && snapShot.getHeight() > 0) {
                 Bitmap b = Bitmap.createBitmap(snapShot.getWidth(),
                         snapShot.getHeight(), Bitmap.Config.ARGB_8888);
 
                Canvas c = new Canvas(b);
                 snapShot.draw(c);
 
               Bitmap newBitmap = zoomBitmap(b, 250, 250);
                 historyModel.setSnapshot(newBitmap);
 
 // 寫入手機sd卡
 
//                FileOutputStream fos = null;
 //                try {
 //                    fos = new FileOutputStream("/sdcard/" + item.getTitle()
 //                            + ".jpg");
 //                    if (fos != null) {
 //                        b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
 //                        fos.close();
 //                    }
 //                } catch (Exception e) {
 //
 //                }
 //
 //                b = BitmapFactory.decodeFile("/sdcard/" + item.getTitle()
 //                        + ".jpg");
             }
 
            historyModel.setId(item.getId());
             historyModel.setName(item.getTitle());
             historyModel.setUrl(item.getUrl());
             historyModels.add(historyModel);
 
            Log.d(TAG + "finish:", url);
         }
     };
 
    /**
      * for #43616 from Hyron
      *
      * @author allen_fang
      *
      */
     private class GeoClient extends WebChromeClient {
 
        @Override
         public void onGeolocationPermissionsShowPrompt(String origin,
                 android.webkit.GeolocationPermissions.Callback callback) {
             super.onGeolocationPermissionsShowPrompt(origin, callback);
             callback.invoke(origin, true, false);
         }
 
        @Override
         public void onProgressChanged(WebView view, int newProgress) {
             mProgressBar.setProgress(newProgress);
             super.onProgressChanged(view, newProgress);
         }
 
        @Override
         public void getVisitedHistory(ValueCallback<String[]> callback) {
             super.getVisitedHistory(callback);
         }
     }
 
    @Override
     public void onDownloadStart(String url, String userAgent,
             String contentDisposition, String mimetype, long contentLength) {
 
        Log.d("————————–", mimetype);
         Log.d("————————–", url);
         Uri uri = Uri.parse(url);
         Intent intent = new Intent(Intent.ACTION_VIEW, uri);
         startActivity(intent);
 
    }
 
    public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
         int w = bitmap.getWidth();
         int h = bitmap.getHeight();
         Matrix matrix = new Matrix();
         float scaleWidth = ((float) width / w);
         float scaleHeight = ((float) height / h);
         matrix.postScale(scaleWidth, scaleHeight);
         Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
         return newbmp;
     }
 }
 
 
摘自fhy_2008的專欄
 

發佈留言