1. 程式人生 > >Html頁面Js呼叫android本地相機和圖片

Html頁面Js呼叫android本地相機和圖片

今天遇到了這個需求,4.4版本及以上有點變化需要新增@JavascriptInterface註釋

好了進入正題
先看效果
這裡寫圖片描述
一、在Html中(我放在了本地assets目錄內)

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
            "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>

        <script type="text/javascript">

        function scamera() {
                  shangyukeji.paizhao();
                }
        </script>


    </head>
    <body>

    <input onclick="scamera();" type="button" value="openCamera"/> <br/>

    HTML5呼叫相機拍照
    </body>
    </html>

二、在MainActivity中

package cn.hnshangyu.htmlopencamera;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

import cn.hnshangyu.htmlopencamera.utils.AppUtils;
import cn.hnshangyu.htmlopencamera.utils.FileUtils;
import cn.hnshangyu.htmlopencamera.utils.StringUtil;
import cn.hnshangyu.htmlopencamera.utils.UIUtils;
import me.nereo.multi_image_selector.MultiImageSelector;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private WebSettings webSettings;
    /**
     * 當前Activity的例項
     */
    protected Activity mActivity;
    /**
     * 當前上下文例項
     */
    protected Context mContext;
    private static final int TAKE_PICTURE = 0x000001;
    private static final int REQUEST_IMAGE = 0x012;

    private static final String DEFAULT_URL = "file:///android_asset/test.html";
    // 拍照,SD卡所需的全部許可權
    String[] mPermissionList = new String[]{Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE};
    private PopupWindow pop;
    private LinearLayout ll_popup;
    /**
     * 選擇的照片
     */
    private List<String> selectImages = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;
        mActivity = this;
        webView = (WebView) findViewById(R.id.webView);
        initWebView();
        Init();

        webView.loadUrl(DEFAULT_URL);
    }

    private void Init() {
        pop = new PopupWindow(this);

        View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);

        ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);

        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
        Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
        parent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!AppUtils.isCameraGranted(mContext) && AppUtils.getAPIVersionCode() >= 23) {
                    UIUtils.showToast("請設定攝像頭許可權");
                    return;
                }

                photo();
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!AppUtils.isReadExternalStoragGranted(mContext) && AppUtils.getAPIVersionCode() >= 23) {
                    UIUtils.showToast("請設定SD卡讀取許可權");
                    return;
                }

                MultiImageSelector selector = MultiImageSelector.create();
                selector.showCamera(false);
                // selector.count(5);
                selector.single();
                //selector.multi();
                selector.origin((ArrayList<String>) selectImages);
                selector.start(mActivity, REQUEST_IMAGE);

                overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE://拍照
                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    String path = FileUtils.saveBitmap(bm, fileName);
                    if (!StringUtil.isBland(path))
                        selectImages.add(path);
                    UIUtils.showToast("selectImages.size() = " + selectImages.size());
                    break;
                case REQUEST_IMAGE://相簿
                    selectImages = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);

                    UIUtils.showToast("selectImages.size() = " + selectImages.size());
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void photo() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    private void initWebView() {
        // 獲得 webView的設定
        webSettings = webView.getSettings();
        /**
         * 設定當前頁面可以執行js 程式碼,預設情況下是false
         */
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR); // 設定預設縮放級別
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);// 以單列的形式排列布局

        // webView 自帶 的縮放按鈕與webView的觸控事件有衝突
        //  webSettings.setBuiltInZoomControls(true); // 顯示預設的縮放按鈕

        webView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                System.out.println("onTouch============");

                return false;// 如果返回true 網頁就不能響應觸控操作了
            }
        });

        /*
         * 為webView 新增一個js 介面
         * 引數一: 是一個java物件
         * 引數二:是一個隨意的字串
         * 該方法的功能是在網頁中建立一個js 物件,物件名就是引數二字串。js物件中的功能,由引數一提供。
         */
        webView.addJavascriptInterface(new Object() {

            /**
             * 宣告一個在js 中可以呼叫的方法,
             * 注意:4.4以上這裡要加註解。
             * 類名:shangyukeji和方法名paizhao跟html保持一致
             */
            @JavascriptInterface
            public void paizhao() {
                // 缺少許可權時, 進入許可權配置頁面
                ActivityCompat.requestPermissions(mActivity, mPermissionList, 100);
                ll_popup.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.activity_translate_in));
                pop.showAtLocation(webView, Gravity.BOTTOM, 0, 0);
                UIUtils.showToast("paizhao");
            }

        }, "shangyukeji");
    }


}