Android 5.0WebView选择本地文件

原创 2016年06月01日 12:24:11
package com.bz365.project.activity.h5;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.bz365.project.R;
import com.bz365.project.beans.ShareBaseBean;
import com.bz365.project.beans.ShareBean;
import com.bz365.project.listener.SharecontentListener;
import com.bz365.project.utils.ShareUtils;
import com.bz365.project.utils.share.ShareAction;
import com.bz365.project.utils.share.ShareContentCallBack;
import com.bz365.project.widgets.SharPopupWindow;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;

import java.io.File;

import lib.bz365.activity.AppBaseActivity;
import lib.bz365.util.CommonUtils;
import lib.bz365.util.StringUtil;

public class WebActivity extends AppBaseActivity implements SharecontentListener {

    private ValueCallback mUploadMessage;

    private final static int FILECHOOSER_RESULTCODE = 1;

    private String title, url, shareKey;
    private String appImgUrl;
    private String shareTitle;
    private String shareUrl;
    private String memo;
    private ImageView img_share;

    private SharPopupWindow mSharPopupWindow;

    private ShareUtils mShareUtils;
    private WebView view;

    public static void startAction(Context context, @NonNull String title, @NonNull String url, String shareKey) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        intent.putExtra("shareKey", shareKey);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initVariables() {
        title = getIntent().getStringExtra("title");
        url = getIntent().getStringExtra("url");
        shareKey = getIntent().getStringExtra("shareKey");
        mSharPopupWindow = new SharPopupWindow(this, this);
        mShareUtils = new ShareUtils(this);
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_web_view);
        view = (WebView) findViewById(R.id.webView);
        String ua = view.getSettings().getUserAgentString();
        view.getSettings().setUserAgentString(ua + " app-channel/");
        view.getSettings().setJavaScriptEnabled(true);
        view.addJavascriptInterface(new WebViewContent(WebActivity.this), "Android");
        view.loadUrl(url, CommonUtils.getHeader());
        view.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url, CommonUtils.getHeader());
                return true;
            }
        });
        view.setWebChromeClient(new XHSWebChromeClient());
        ImageView img_back = (ImageView) findViewById(R.id.img_back);
        if (img_back != null) {
            img_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    returnPage();
                }
            });
        }
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        if (!StringUtil.isEmpty(title)) {
            if (tv_title != null) {
                tv_title.setText(title);
            }
        }
        img_share = (ImageView) findViewById(R.id.img_share);
        if (!StringUtil.isEmpty(shareKey)) {
            if (img_share != null) {
                img_share.setVisibility(View.VISIBLE);
                img_share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showProgress();
                        new ShareAction().getShareContent(new ShareContentCallBack() {
                            @Override
                            public void onShareContent(ShareBaseBean mShareBaseBean, String emptyMsg, String errorMsg) {
                                closeProgress();
                                if (mShareBaseBean != null) {
                                    ShareBean mShareBean = mShareBaseBean.getData();
                                    appImgUrl = mShareBean.getAppImgUrl();
                                    shareTitle = mShareBean.getShareTitle();
                                    shareUrl = mShareBean.getShareUrl();
                                    memo = mShareBean.getMemo();
                                    mSharPopupWindow.showAtLocation(img_share, Gravity.BOTTOM
                                            | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                                } else {
                                    if (!StringUtil.isEmpty(errorMsg)) {
                                        ShowToast(errorMsg);
                                    }
                                }
                            }
                        }, shareKey);
                    }
                });
            }
        }
    }

    @Override
    public void loadData() {

    }

    @Override
    public void setShareby(int index) {
        mShareUtils.setShare(this, memo, shareTitle, shareUrl, appImgUrl, index);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            returnPage();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void returnPage() {
        if (mSharPopupWindow != null && mSharPopupWindow.isShowing()) {
            mSharPopupWindow.dismiss();
        }
        if (view.canGoBack()) {
            view.goBack();// 返回上一页面
        } else {
            finish();
        }
    }

    public class XHSWebChromeClient extends WebChromeClient {

        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
            }
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
            }
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
            i.setType(type);
            startActivityForResult(Intent.createChooser(i, "File Chooser"),
                    FILECHOOSER_RESULTCODE);
        }

        // For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
            }
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
            i.setType(type);
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
        }


        //Android 5.0+
        @Override
        @SuppressLint("NewApi")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
            }
            mUploadMessage = filePathCallback;
            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("*/*");
            }
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            return true;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(title);
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(title);
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (result == null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
                return;
            }
            String path = FileUtils.getPath(this, result);
            if (TextUtils.isEmpty(path)) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
                return;
            }
            Uri uri = Uri.fromFile(new File(path));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mUploadMessage.onReceiveValue(new Uri[]{uri});
            } else {
                mUploadMessage.onReceiveValue(uri);
            }

            mUploadMessage = null;
        }
    }

    public static class FileUtils {
        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is ExternalStorageProvider.
         */
        public static boolean isExternalStorageDocument(Uri uri) {
            return "com.android.externalstorage.documents".equals(uri.getAuthority());
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is DownloadsProvider.
         */
        public static boolean isDownloadsDocument(Uri uri) {
            return "com.android.providers.downloads.documents".equals(uri.getAuthority());
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is MediaProvider.
         */
        public static boolean isMediaDocument(Uri uri) {
            return "com.android.providers.media.documents".equals(uri.getAuthority());
        }

        /**
         * Get the value of the data column for this Uri. This is useful for
         * MediaStore Uris, and other file-based ContentProviders.
         *
         * @param context       The context.
         * @param uri           The Uri to query.
         * @param selection     (Optional) Filter used in the query.
         * @param selectionArgs (Optional) Selection arguments used in the query.
         * @return The value of the _data column, which is typically a file path.
         */
        public static String getDataColumn(Context context, Uri uri, String selection,
                                           String[] selectionArgs) {

            Cursor cursor = null;
            final String column = "_data";
            final String[] projection = {
                    column
            };

            try {
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                        null);
                if (cursor != null && cursor.moveToFirst()) {
                    final int column_index = cursor.getColumnIndexOrThrow(column);
                    return cursor.getString(column_index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
            return null;
        }

        /**
         * Get a file path from a Uri. This will get the the path for Storage Access
         * Framework Documents, as well as the _data field for the MediaStore and
         * other file-based ContentProviders.
         *
         * @param context The context.
         * @param uri     The Uri to query.
         * @author paulburke
         */
        @SuppressLint("NewApi")
        public static String getPath(final Context context, final Uri uri) {

            final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

            // DocumentProvider
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {

                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }

                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{
                            split[1]
                    };

                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            // MediaStore (and general)
            else if ("content".equalsIgnoreCase(uri.getScheme())) {
                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }

            return null;
        }

    }
}

如何设置word页码 第几页共几页 从第二页算起

要实现的效果 假设你有一个20页的文档,本文的目的是要实现在页脚中自动填充格式为 “第X页,共X页” 的页码,且首页不显示页码,同时 “共X页” 还要显示为 “共19页”(即首页不计,第二 页 显示为...

Webview之H5页面调用android的图库及文件管理

h5页面打开图片管理器 一般页面在pc打开文件管理器是用 type=”file”的代码,可是这在Android的webview是无效的,必须为webview设定WebChromeClient代码...

Android5.0以上Webview上传文件注意事项

Webview执行上传操作的逻辑是这样的:首先准备上传时会回调 WebChromeClient类下的 openFileChooser 方法,在这个方法中给我们机会发起Intent来打开支持提供文件的第...

android studio 打包webview 5.0文件上传问题

之前在eclipse上打包的项目在5.0的手机上正常,这俩天项目转到android studio 上,5.0之上的系统文件上传反而无反应,之后根据网络资料整理解决,代码如下 private ...

Android5.0以上WebView的兼容问题

最近在维护一个项目同时要兼容Android4.4和Android5.0两种机型,在调试Android5.0的时候多次因为WebView而造成程序崩溃。在项目完成之后,就来总结一下WebView的兼容性...

Android5.0及以上系统WebView上传图片遇到的那些坑

之前项目中有做在WebView中上传文件的操作(调用系统相册选择照片来进行上传),当我们在web页面上点击选择文件的控件 ()时,会回調WebChromeClient下的openFileChoo...

android5.0以上webview无法播放腾讯等视频

android5.0以上webview无法播放腾讯等视频

Android webview支持type="file" 打开相机和相册兼容5.0+

既上一篇文章转载了知乎上一位作者的Android webview支持type=”file” 打开相机和相册,发现原来webview上传文件要这么处理,依葫芦画瓢,在测试机上(版本全是4.4的)都没问题...

Android5.0 WebView中Http和Https混合问题

场景复现: 在Android5.0 以及以上的系统,当WebView加载的链接为Https开头,但是链接里面的内容,比如图片为Http链接,这时候,图片就会加载不出来,在浏览器中的Conso...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Android 5.0WebView选择本地文件
举报原因:
原因补充:

(最多只允许输入30个字)