国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

適配Android WebView支持上傳圖片,視頻

roadtogeek / 1172人閱讀

摘要:問題原因訪問本地文件的時候,使用的出于安全性的考慮,是限制了以上操作。解決辦法重寫中的和方法響應,然后使用原生代碼來實現調用本地相冊和拍照的功能,最后在把選擇的圖片回傳給。注意系統,使用該方法在已經被廢棄。

問題原因:

H5訪問本地文件的時候, 使用的 ,WebView 出于安全性的考慮,是限制了以上操作。

解決辦法:

重寫 WebviewChromeClient 中的 openFileChooser() 和 onShowFileChooser()方法響應,然后使用原生代碼來實現調用本地相冊和拍照的功能,最后在 onActiivtyResult 把選擇的圖片 URI 回傳給 WebviewChromeClient。

注意:

Android4.1系統,使用openFileChooser(),該方法在Android5.0已經被廢棄。

Android5.0以上類型, 使用onShowFileChooser()

一,初始化操作
  ButtomDialogView mSelectImgDialog;
  public static final int INPUT_FILE_REQUEST_CODE1;
  public static final int INPUT_VIDEO_CODE = 2;
  private static final int REQUEST_CODE_ALBUM = 3;
  private ValueCallback mFilePathCallback;
  private ValueCallback nFilePathCallback;
  private String mCameraPhotoPath;
  private Uri photoURI;
  
二,重寫 WebChromeClient
mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            //for  Android 4.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
                Log.d("nimei", "openFileChooser" + "----> acceptType:" + acceptType);
                if (nFilePathCallback != null) {
                    nFilePathCallback.onReceiveValue(null);
                }
                nFilePathCallback = uploadMsg;
                if ("image/*".equals(acceptType)) {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 調用后置攝像頭
                    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                        File photoFile = null;
                        try {
                            photoFile = createImageFile();
                            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                        } catch (IOException ex) {
                            Log.e("TAG", "Unable to create Image File", ex);
                        }
                        if (photoFile != null) {
                            mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photoFile));
                            Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                        } else {
                            takePictureIntent = null;
                        }
                    }
                    startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);
                } else if ("video/*".equals(acceptType) || mWebView.getUrl().startsWith("https://ida.webank.com/") || "video/webank".equals(acceptType)) {
//                    Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//                    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
//                        startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
//                    }
                    try {
                        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        takeVideoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1); // 調用前置攝像頭
                        activity.startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else { // 支持拍照or選擇照片
                    openSelectImgDialog();
                }
            }

            @SuppressLint("NewApi")
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                }
                mFilePathCallback = filePathCallback;
                String[] acceptTypes = fileChooserParams.getAcceptTypes();
                Log.d("nimei", "onShowFileChooser" + "----> acceptType:" + acceptTypes[0]);
                if (acceptTypes[0].equals("image/*")) {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 調用后置攝像頭
                    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                        File photoFile = null;
                        try {
                            photoFile = createImageFile();
                            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                        } catch (IOException ex) {
                            Log.e("TAG", "Unable to create Image File", ex);
                        }
                        //適配7.0
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                            if (photoFile != null) {
                                photoURI = FileProvider.getUriForFile(NewFreshJNWebViewActivity.this,
                                        BuildConfig.APPLICATION_ID + ".bga_update.file_provider", photoFile);
                                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                            }
                        } else {
                            if (photoFile != null) {
                                mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                        Uri.fromFile(photoFile));
                                Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                            } else {
                                takePictureIntent = null;
                            }
                        }
                    }
                    startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);
                } else if (acceptTypes[0].equals("video/*") || mWebView.getUrl().startsWith("https://ida.webank.com/") || acceptTypes[0].equals("video/webank")) {
//                  錄制視頻
//                       Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//                    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
//                        startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
//                    }
                    try {
                        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        takeVideoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1); // 調用前置攝像頭
                        activity.startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else { // 支持拍照or選擇照片
                    openSelectImgDialog();
                }
                return true;
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                return true;
            }
        });
三,選擇相機or選擇相冊
public void openSelectImgDialog() {
        View ShippingInformationView = LayoutInflater.from(NewFreshJNWebViewActivity.this).inflate(R.layout.layout_shipping_inf_dialog, null);
        mSelectImgDialog = new ButtomDialogView(NewFreshJNWebViewActivity.this, ShippingInformationView, false, false);

        TextView tv_supplier_selection_address = (TextView) ShippingInformationView.findViewById(R.id.tv_supplier_selection_address);
        tv_supplier_selection_address.setText("拍照");
        TextView tv_cancel = (TextView) ShippingInformationView.findViewById(R.id.tv_cancel);
        TextView tv_choose_consignee = (TextView) ShippingInformationView.findViewById(R.id.tv_choose_consignee);
        tv_choose_consignee.setText("相冊");
        //拍照
        tv_supplier_selection_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 調用后置攝像頭
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                    } catch (IOException ex) {
                        Log.e("TAG", "Unable to create Image File", ex);
                    }
                    //適配7.0
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                        if (photoFile != null) {
                            photoURI = FileProvider.getUriForFile(NewFreshJNWebViewActivity.this,
                                    BuildConfig.APPLICATION_ID + ".bga_update.file_provider", photoFile);
                            takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        }
                    } else {
                        if (photoFile != null) {
                            mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photoFile));
                            Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                        } else {
                            takePictureIntent = null;
                        }
                    }
                }
                startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);

            }
        });
        //相冊選擇照片
        tv_choose_consignee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "Image Chooser"), REQUEST_CODE_ALBUM);
            }
        });
        //取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                //一定要返回null,否則
                if (nFilePathCallback != null) {
                    nFilePathCallback.onReceiveValue(null);
                    nFilePathCallback = null;
                }
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                    mFilePathCallback = null;

                }
            }
        });
        mSelectImgDialog.show();
    }
    
 private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* 前綴 */
                ".jpg",         /* 后綴 */
                storageDir      /* 文件夾 */
        );
        mCameraPhotoPath = image.getAbsolutePath();
        return image;
    }
    
四,選擇相機or選擇相冊
@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri[] results = null;
        Uri mUri = null;
        if (resultCode == Activity.RESULT_OK && requestCode == INPUT_FILE_REQUEST_CODE) {
            if (data == null) {
                if (Build.VERSION.SDK_INT > M) {
                    mUri = photoURI;
                    results = new Uri[]{mUri};
                } else {
                    if (mCameraPhotoPath != null) {
                        mUri = Uri.parse(mCameraPhotoPath);
                        results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                    }
                }
            } else {
                Uri nUri = data.getData();
                if (nUri != null) {
                    mUri = nUri;
                    results = new Uri[]{nUri};
                }
            }
        } else if (resultCode == Activity.RESULT_OK && requestCode == INPUT_VIDEO_CODE) { //錄制視頻
            mUri = data.getData();
            results = new Uri[]{mUri};
        } else if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_ALBUM) {
            //選擇相冊
            if (data != null) {
                mUri = data.getData();
            }
            results = new Uri[]{mUri};
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            nFilePathCallback.onReceiveValue(mUri);
            nFilePathCallback = null;
            return;
        } else {
            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
            return;
        }
    }
完整代碼
package com.xxxxx;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xxxxx.plugin.JsApi;
import com.xxxxx.plugin.WebviewEvent;
import com.xxxxx.ui.BaseActivity;
import com.xxxxx.ui.activity.JNChooseConsigneeSupplierActivity;
import com.xxxxx.ui.activity.JNTakeOrderActivity;
import com.xxxxx.ui.widget.ButtomDialogView;
import com.tencent.smtt.export.external.interfaces.ConsoleMessage;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import wendu.dsbridge.DWebView;

import static android.os.Build.VERSION_CODES.M;

/**
 * webview activity
 */
public class NewFreshJNWebViewActivity extends BaseActivity {
    public static final String TAG = "NewFreshJNWebViewActivity";
    private DWebView mWebView;
    public String url, title, name;
    TextView tv_title;
    ButtomDialogView mSelectImgDialog;
    public static final int INPUT_FILE_REQUEST_CODE = 1;
    public static final int INPUT_VIDEO_CODE = 2;
    private static final int REQUEST_CODE_ALBUM = 3;
    private ValueCallback mFilePathCallback;
    private ValueCallback nFilePathCallback;
    private String mCameraPhotoPath;
    private Uri photoURI;
    ImageView img_close;

    @SuppressLint("LongLogTag")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jnface_verify);
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        name = getIntent().getStringExtra("name");
        Log.d(TAG, url);
        initWebView();
        LinearLayout lay_back = (LinearLayout) findViewById(R.id.lay_back);
        img_close = (ImageView) findViewById(R.id.img_close);
        img_close.setOnClickListener(v -> {
            NewFreshJNWebViewActivity.this.finish();
            JSONObject newMap = new JSONObject();
            try {
                newMap.put("name", name);
                newMap.put("type", "click");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            EventBus.getDefault().post(new WebviewEvent(newMap, "colseWebviewNotice"));
        });
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(!TextUtils.isEmpty(title) ? title : "江楠鮮品");
        lay_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    private void initWebView() {
        mWebView = (DWebView) findViewById(R.id.main_webview);
        WBH5FaceVerifySDK.getInstance().setWebViewSettings(mWebView, getApplicationContext());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        mWebView.addJavascriptObject(new JsApi(NewFreshJNWebViewActivity.this), "freshjn.webview");
        mWebView.setWebViewClient(new WebViewClient());

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            //for  Android 4.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
                Log.d("nimei", "openFileChooser" + "----> acceptType:" + acceptType);
                if (nFilePathCallback != null) {
                    nFilePathCallback.onReceiveValue(null);
                }
                nFilePathCallback = uploadMsg;
                if ("image/*".equals(acceptType)) {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 調用后置攝像頭
                    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                        File photoFile = null;
                        try {
                            photoFile = createImageFile();
                            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                        } catch (IOException ex) {
                            Log.e("TAG", "Unable to create Image File", ex);
                        }
                        if (photoFile != null) {
                            mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photoFile));
                            Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                        } else {
                            takePictureIntent = null;
                        }
                    }
                    startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);
                } else if ("video/*".equals(acceptType) || mWebView.getUrl().startsWith("https://ida.webank.com/") || "video/webank".equals(acceptType)) {
//                    Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//                    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
//                        startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
//                    }
                    try {
                        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        takeVideoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1); // 調用前置攝像頭
                        activity.startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else { // 支持拍照or選擇照片
                    openSelectImgDialog();
                }
            }

            @SuppressLint("NewApi")
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                }
                mFilePathCallback = filePathCallback;
                String[] acceptTypes = fileChooserParams.getAcceptTypes();
                Log.d("nimei", "onShowFileChooser" + "----> acceptType:" + acceptTypes[0]);
                if (acceptTypes[0].equals("image/*")) {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 調用后置攝像頭
                    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                        File photoFile = null;
                        try {
                            photoFile = createImageFile();
                            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                        } catch (IOException ex) {
                            Log.e("TAG", "Unable to create Image File", ex);
                        }
                        //適配7.0
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                            if (photoFile != null) {
                                photoURI = FileProvider.getUriForFile(NewFreshJNWebViewActivity.this,
                                        BuildConfig.APPLICATION_ID + ".bga_update.file_provider", photoFile);
                                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                            }
                        } else {
                            if (photoFile != null) {
                                mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                        Uri.fromFile(photoFile));
                                Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                            } else {
                                takePictureIntent = null;
                            }
                        }
                    }
                    startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);
                } else if (acceptTypes[0].equals("video/*") || mWebView.getUrl().startsWith("https://ida.webank.com/") || acceptTypes[0].equals("video/webank")) {
//                  錄制視頻
//                       Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//                    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
//                        startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
//                    }
                    try {
                        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        takeVideoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1); // 調用前置攝像頭
                        activity.startActivityForResult(takeVideoIntent, INPUT_VIDEO_CODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else { // 支持拍照or選擇照片
                    openSelectImgDialog();
                }
                return true;
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                return true;
            }
        });

        if (!TextUtils.isEmpty(url)) {
            mWebView.loadUrl(url);
        }

//        mWebView.loadUrl("http://qatest.fabigbig.com:8887/fddAuthenticationService/app/index.html#/agreement?id=2c9282926830c337016835d477e30249&operation=0&token=1721cf9e601342eaa7951727f961d583");
    }

    // 相機 或者 相冊
    public void openSelectImgDialog() {
        View ShippingInformationView = LayoutInflater.from(NewFreshJNWebViewActivity.this).inflate(R.layout.layout_shipping_inf_dialog, null);
        mSelectImgDialog = new ButtomDialogView(NewFreshJNWebViewActivity.this, ShippingInformationView, false, false);

        TextView tv_supplier_selection_address = (TextView) ShippingInformationView.findViewById(R.id.tv_supplier_selection_address);
        tv_supplier_selection_address.setText("拍照");
        TextView tv_cancel = (TextView) ShippingInformationView.findViewById(R.id.tv_cancel);
        TextView tv_choose_consignee = (TextView) ShippingInformationView.findViewById(R.id.tv_choose_consignee);
        tv_choose_consignee.setText("相冊");
        //拍照
        tv_supplier_selection_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 0); // 調用后置攝像頭
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                    } catch (IOException ex) {
                        Log.e("TAG", "Unable to create Image File", ex);
                    }
                    //適配7.0
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                        if (photoFile != null) {
                            photoURI = FileProvider.getUriForFile(NewFreshJNWebViewActivity.this,
                                    BuildConfig.APPLICATION_ID + ".bga_update.file_provider", photoFile);
                            takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        }
                    } else {
                        if (photoFile != null) {
                            mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photoFile));
                            Log.d("nimei", "mCameraPhotoPath:" + mCameraPhotoPath);
                        } else {
                            takePictureIntent = null;
                        }
                    }
                }
                startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);

            }
        });
        //相冊選擇照片
        tv_choose_consignee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "Image Chooser"), REQUEST_CODE_ALBUM);
            }
        });
        //取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectImgDialog.isShowing()) {
                    mSelectImgDialog.dismiss();
                }
                //一定要返回null,否則
                if (nFilePathCallback != null) {
                    nFilePathCallback.onReceiveValue(null);
                    nFilePathCallback = null;
                }
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                    mFilePathCallback = null;

                }
            }
        });
        mSelectImgDialog.show();
    }


    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* 前綴 */
                ".jpg",         /* 后綴 */
                storageDir      /* 文件夾 */
        );
        mCameraPhotoPath = image.getAbsolutePath();
        return image;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri[] results = null;
        Uri mUri = null;
        if (resultCode == Activity.RESULT_OK && requestCode == INPUT_FILE_REQUEST_CODE) {
            if (data == null) {
                if (Build.VERSION.SDK_INT > M) {
                    mUri = photoURI;
                    results = new Uri[]{mUri};
                } else {
                    if (mCameraPhotoPath != null) {
                        mUri = Uri.parse(mCameraPhotoPath);
                        results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                    }
                }
            } else {
                Uri nUri = data.getData();
                if (nUri != null) {
                    mUri = nUri;
                    results = new Uri[]{nUri};
                }
            }
        } else if (resultCode == Activity.RESULT_OK && requestCode == INPUT_VIDEO_CODE) { //錄制視頻
            mUri = data.getData();
            results = new Uri[]{mUri};
        } else if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_ALBUM) {
            //選擇相冊
            if (data != null) {
                mUri = data.getData();
            }
            results = new Uri[]{mUri};
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            nFilePathCallback.onReceiveValue(mUri);
            nFilePathCallback = null;
            return;
        } else {
            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
            return;
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            JSONObject newMap = new JSONObject();
            try {
                newMap.put("name", name);
                newMap.put("type", "click");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            EventBus.getDefault().post(new WebviewEvent(newMap, "colseWebviewNotice"));
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            } else {

                JSONObject newMap = new JSONObject();
                try {
                    newMap.put("name", name);
                    newMap.put("type", "click");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                EventBus.getDefault().post(new WebviewEvent(newMap, "colseWebviewNotice"));
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //注冊訂閱者
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        //注銷注冊
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWebviewEvent(WebviewEvent event) {
        if (event.getmObject() != null && event.getmType() != null) {
            if (event.getmType().equals("close")) {
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.destroy();
            mWebView = null;
        }
        if (mSelectImgDialog != null && mSelectImgDialog.isShowing()) {
            mSelectImgDialog.dismiss();
            mSelectImgDialog = null;
        }
    }
}


文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/73591.html

相關文章

  • Weex系列(6) —— web組件和webview

    摘要:安卓要麻煩許多,網上大多也都是安卓的講解,我也是遇到了好多坑。我是在里面重新繪制了一下,在適配的時候會用到,安卓倒是沒有怎么處理。 目錄 Weex系列(序) —— 總要知道原生的一點東東(iOS) Weex系列(序) —— 總要知道原生的一點東東(Android) Weex系列(1) —— Hello World項目 Weex系列(2) —— 頁面跳轉和通信 Weex系列(3) ——...

    LucasTwilight 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<