Android混合开发之H5调用系统相机和相册

曾经接触一个项目,需要利用H5显示页面,于是自然而然想到了WebView。又由于Android系统自带的WebView被人吐槽过多,所以决定使用腾讯封装的X5内核的WebView,使用和方法上和系统的相差不大。

第一步:在布局中使用WebView。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="3dp" />
    <com.tencent.smtt.sdk.WebView
        android:id="@+id/wv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="" />

</LinearLayout>

我们设置一个progressbar用来提示加载进度,我想从用户体验上来说还是很必要的。

第二步:WebActivity开始初始化progressbar。

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        webview = findViewById(R.id.wv);
        initProgressBar();
        init();
    }
private void initProgressBar() {
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
        mProgressBar.setMax(100);
        mProgressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.color_progressbar));
    }
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- 设置背景色(白色) -->
    <item android:id="@android:id/background">
    <shape>   
        <corners android:radius="3dip" />   
        <gradient android:startColor="#ffedeff2"   
                android:centerColor="#ffedeff2"   
                android:centerY="0.75"   
                android:endColor="#ffedeff2"   
                android:angle="270"   
        />   
    </shape> 
    </item>

    <!-- 设置进度条颜色(蓝色) -->
    <item android:id="@android:id/progress">
        <clip>
        <shape>   
            <corners android:radius="3dip" />   
            <gradient android:startColor="#ff399afb"   
                android:endColor="#ff399afb"   />   
        </shape> 
        </clip>
    </item>

第三步:初始化WebView。

private void init() {
      
        initWebview("https://...");
}

private void initWebview(String data) {
        com.tencent.smtt.sdk.WebSettings webSettings = webview.getSettings();

        //加载需要显示的网页

        MyWebChromeClient myWebChromeClient = new MyWebChromeClient();
        webview.setWebChromeClient(myWebChromeClient);
        webview.loadUrl(data);
        //    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setUseWideViewPort(true);//关键点
        webSettings.setLoadWithOverviewMode(true);
        //    webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        //    webSettings.setDisplayZoomControls(false);
        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        webSettings.setAllowFileAccess(true); // 允许访问文件
        webSettings.setBuiltInZoomControls(true); // 设置显示缩放按钮
        webSettings.setSupportZoom(true); // 支持缩放
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setLoadsImagesAutomatically(true);
        //    webview.setScrollBarStyle(0);
        webview.setWebViewClient(new com.tencent.smtt.sdk.WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                //  重写此方法表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边
                view.loadUrl(url);
                return true;
            }
        });


    }


  public class MyWebChromeClient extends com.tencent.smtt.sdk.WebChromeClient {

    @Override
    public void onProgressChanged(com.tencent.smtt.sdk.WebView view, int newProgress) {
        //监听页面加载进度
//		            ProgressBar progressbar = webView.getProgressbar();
        if (newProgress == 100) {
            // 加载完成隐藏进度条
            mProgressBar.setVisibility(View.GONE);

        } else {
            mProgressBar.setVisibility(View.VISIBLE);
            mProgressBar.setProgress(newProgress);
        }
        super.onProgressChanged(view, newProgress);
    }

      @Override
      public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
          if (mUploadMessage != null) {
              mUploadMessage.onReceiveValue(null);
          }
          mUploadMessage = valueCallback;
          take(fileChooserParams);
          return true;
      }

      @Override
      public void openFileChooser(ValueCallback<Uri> valueCallback, String s, String s1) {
          mValueCallbackTake = valueCallback;
          take();
      }

  }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (result == null&&imageUri==null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
                return;
            }
            if (mUploadMessage != null&&result != null){
                String path =  FileUtils.getPath(this, result);
                if (TextUtils.isEmpty(path)) {
                    mUploadMessage.onReceiveValue(null);
                    mUploadMessage = null;
                    return;
                }
                Uri u = Uri.fromFile(new File(path));

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    mUploadMessage.onReceiveValue(new Uri[]{u});
                }
                mUploadMessage = null;
            } else{
                if (imageUri != null) {
                   /* String path = getPath(getApplicationContext(),
                            result);
                    Uri uri = Uri.fromFile(new File(path));*/
                    mUploadMessage
                            .onReceiveValue(new Uri[]{imageUri});
                } else {
                    mUploadMessage.onReceiveValue(new Uri[]{imageUri});
                }
                mUploadMessage = null;
            }


        }
    }

 

public void take(WebChromeClient.FileChooserParams fileChooserParams){
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");
        // Create the storage directory if it does not exist
        if (! imageStorageDir.exists()){
            imageStorageDir.mkdirs();
        }
        File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        imageUri = Uri.fromFile(file);
        final List<Intent> cameraIntents = new ArrayList<Intent>();
        final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri mCameraTempUri;
        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
        values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
        mCameraTempUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        captureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        if (mCameraTempUri != null) {
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraTempUri);
            captureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        }
        final PackageManager packageManager = getPackageManager();
        final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for(ResolveInfo res : listCam) {
            final String packageName = res.activityInfo.packageName;
            final Intent i = new Intent(captureIntent);
            i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            i.setPackage(packageName);
            i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            cameraIntents.add(i);
        }

        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null
                && fileChooserParams.getAcceptTypes().length > 0) {
            i.setType(fileChooserParams.getAcceptTypes()[0]);
        } else {
            i.setType("*/*");
        }
        Intent chooserIntent = Intent.createChooser(i,"请选择:");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AD钙奶-lalala

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值