Android之WebView仿微信中圖片操作(含二維碼識別)
阿新 • • 發佈:2019-02-15
HitTestResult類: WebView中被點選內容的相應資訊,通過WebView的getHitTestResult()獲取!
自定義WebView
/**
* 自定義WebView,長按圖片獲取圖片url
* @author LinZhang
*
*/
public class CustomWebView extends WebView implements OnLongClickListener{
private Context context;
private LongClickCallBack mCallBack;
public CustomWebView (Context context, LongClickCallBack mCallBack) {
super(context);
this.context = context;
this.mCallBack = mCallBack;
initSettings();
}
private void initSettings() {
// 初始化設定
WebSettings mSettings = this.getSettings();
mSettings.setJavaScriptEnabled(true );//開啟javascript
mSettings.setDomStorageEnabled(true);//開啟DOM
mSettings.setDefaultTextEncodingName("utf-8");//設定字元編碼
//設定web頁面
mSettings.setAllowFileAccess(true);//設定支援檔案流
mSettings.setSupportZoom(true);// 支援縮放
mSettings.setBuiltInZoomControls(true);// 支援縮放
mSettings.setUseWideViewPort(true );// 調整到適合webview大小
mSettings.setLoadWithOverviewMode(true);// 調整到適合webview大小
mSettings.setDefaultZoom(ZoomDensity.FAR);// 螢幕自適應網頁,如果沒有這個,在低解析度的手機上顯示可能會異常
mSettings.setRenderPriority(RenderPriority.HIGH);
//提高網頁載入速度,暫時阻塞圖片載入,然後網頁載入好了,在進行載入圖片
mSettings.setBlockNetworkImage(true);
mSettings.setAppCacheEnabled(true);//開啟快取機制
setWebViewClient(new MyWebViewClient());
setOnLongClickListener(this);
}
@Override
public boolean onLongClick(View v) {
// 長按事件監聽(注意:需要實現LongClickCallBack介面並傳入物件)
final HitTestResult htr = getHitTestResult();//獲取所點選的內容
if (htr.getType() == WebView.HitTestResult.IMAGE_TYPE) {//判斷被點選的型別為圖片
mCallBack.onLongClickCallBack(htr.getExtra());
}
return false;
}
private class MyWebViewClient extends WebViewClient {
/**
* 載入過程中 攔截載入的地址url
* @param view
* @param url 被攔截的url
* @return
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
/**
* 頁面載入過程中,載入資源回撥的方法
* @param view
* @param url
*/
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
/**
* 頁面載入完成回撥的方法
* @param view
* @param url
*/
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// 關閉圖片載入阻塞
view.getSettings().setBlockNetworkImage(false);
}
/**
* 頁面開始載入呼叫的方法
* @param view
* @param url
* @param favicon
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public void onScaleChanged(WebView view, float oldScale, float newScale) {
super.onScaleChanged(view, oldScale, newScale);
CustomWebView.this.requestFocus();
CustomWebView.this.requestFocusFromTouch();
}
}
/**
* 長按事件回撥介面,傳遞圖片地址
* @author LinZhang
*/
public interface LongClickCallBack{
/**用於傳遞圖片地址*/
void onLongClickCallBack(String imgUrl);
}
}
自定義Dialog,用於長按圖片彈出
/**
* 彈出圖片操作Dialog
* @author LinZhang
*
*/
public abstract class CustomDialog extends Dialog {
private Context context;
/**
* 構造器
* @param context 上下文
* @param layoutId 資原始檔id
*/
public CustomDialog(Context context, int layoutId) {
super(context, R.style.CustomDialog);
this.context = context;
createDialog(layoutId);
}
/**
* 設定dialog
* @param layoutId
*/
public void createDialog(int layoutId){
setContentView(layoutId);
Window window = getWindow();
WindowManager.LayoutParams params = window.getAttributes();
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.gravity = Gravity.CENTER;
window.setAttributes(params);
initViews();
if(!(context instanceof Activity)){
getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}
}
public void closeDialog(){
dismiss();
}
/**
* 用於初始化相應的控制元件
*/
public abstract void initViews();
}
MainActivity:
public class MainActivity extends Activity implements LongClickCallBack{
private CustomWebView mCustomWebView;
private CustomDialog mCustomDialog;
private ArrayAdapter<String> adapter;
private boolean isQR;//判斷是否為二維碼
private Result result;//二維碼解析結果
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
public void handleMessage(Message msg) {
if (msg.what == 0){
if (isQR){
adapter.add("識別圖中二維碼");
}
adapter.notifyDataSetChanged();
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initWebView();
}
private void initWebView() {
// 初始WebView化控制元件
mCustomWebView = new CustomWebView(this, this);
mCustomWebView.loadUrl("http://keeganlee.me/post/android/20121206");//載入頁面
mCustomWebView.setFocusable(true);
mCustomWebView.setFocusableInTouchMode(true);
addContentView(mCustomWebView, new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
}
@Override
public void onLongClickCallBack(final String imgUrl) {
// 獲取到圖片地址後做相應的處理
new Thread(){
public void run() {
decodeImage(imgUrl);
handler.sendEmptyMessage(0);
};
}.start();
showDialog();
}
/**
* 判斷是否為二維碼
* @param url 圖片地址
* @return
*/
private boolean decodeImage(String sUrl){
result = DecodeImage.handleQRCodeFormBitmap(getBitmap(sUrl));
if(result == null){
isQR = false;
}else {
isQR = true;
}
return isQR;
}
/**
* 根據地址獲取網路圖片
* @param sUrl 圖片地址
* @return
* @throws IOException
*/
public static Bitmap getBitmap(String sUrl){
try {
URL url = new URL(sUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
InputStream inputStream = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 顯示Dialog
* @param v
*/
private void showDialog() {
adapter = new ArrayAdapter<String>(this,R.layout.item_dialog);
adapter.add("傳送給朋友");
adapter.add("儲存到手機");
adapter.add("收藏");
mCustomDialog = new CustomDialog(this, R.layout.custom_dialog) {
@Override
public void initViews() {
// 初始CustomDialog化控制元件
ListView mListView = (ListView) findViewById(R.id.lv_dialog);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 點選事件
switch (position) {
case 0:
Toast.makeText(MainActivity.this, "已傳送給朋友", Toast.LENGTH_LONG).show();
closeDialog();
break;
case 1:
Toast.makeText(MainActivity.this, "已儲存到手機", Toast.LENGTH_LONG).show();
closeDialog();
break;
case 2:
Toast.makeText(MainActivity.this, "已收藏", Toast.LENGTH_LONG).show();
closeDialog();
break;
case 3:
Toast.makeText(MainActivity.this, "二維碼識別結果: " + result.toString(), Toast.LENGTH_LONG).show();
closeDialog();
break;
}
}
});
}
};
mCustomDialog.show();
}
}