今天项目接入了别的项目中的H5页面,接完后发现上传图片的时候点击没反应,后来才知道android中WebView上传图片还得自己实现。实现方法记录一下:

public class OADetailActivity extends BaseActivity {    private WebView wv_project_brief;    private ProgressBar progressBar;    private int screenWidth;    private ImageView iv_finish;    private ValueCallback mUploadFile;    private ValueCallback mUploadCallbackAboveL;    private LinearLayout ll_main;    /**拍照/选择文件请求码*/    private final int REQUESTCODE_TAKE = 1;    private final int REQUESTCODE_PICK = 2;    private final int REQUESTCODE_CUTTING = 3;    private String headPath = "";    private Uri uritempFile;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_oa_detail);        DisplayMetrics dm = new DisplayMetrics();        getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);        screenWidth = dm.widthPixels;        initView();        initData();    }    private void initView() {        TextView tv_topview_title = (TextView) findViewById(R.id.tv_topview_title);        iv_finish = (ImageView) findViewById(R.id.iv_finish);        ll_main = (LinearLayout) findViewById(R.id.ll_main);        tv_topview_title.setText(getString(R.string.oa_system));        wv_project_brief = (WebView) findViewById(R.id.wv_project_brief);        progressBar = (ProgressBar) findViewById(R.id.progressBar);        wv_project_brief.getSettings().setJavaScriptEnabled(true);        wv_project_brief.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);        wv_project_brief.getSettings().setAllowFileAccess(true);        wv_project_brief.getSettings().setDefaultTextEncodingName("UTF-8");        wv_project_brief.getSettings().setLoadWithOverviewMode(true);        wv_project_brief.getSettings().setUseWideViewPort(true);        iv_finish.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                finish();            }        });    }    private void initData() {        String url = getIntent().getStringExtra("url");        wv_project_brief.loadUrl(url);        wv_project_brief.setWebViewClient(new WebViewClient() {            public boolean shouldOverrideUrlLoading(WebView view, String url) {                view.loadUrl(url);                return true;            }            @Override            public void onPageFinished(WebView view, String url) {                super.onPageFinished(view, url);                progressBar.setVisibility(View.GONE);            }        });        wv_project_brief.setWebChromeClient(new WebChromeClient()        {   //5.0以上调用此处            @Override            @SuppressLint("NewApi")            public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {                if (mUploadCallbackAboveL != null) {                    mUploadCallbackAboveL.onReceiveValue(null);                }                mUploadCallbackAboveL = filePathCallback;                new PopupWindows(OADetailActivity.this, ll_main);                return true;            }            // Andorid 4.1+            public void openFileChooser(ValueCallback uploadFile, String acceptType, String capture)            {                openFileChooser(uploadFile,acceptType);            }            // Andorid 3.0 +            public void openFileChooser(ValueCallback uploadFile, String acceptType)            {                mUploadFile = uploadFile;                new PopupWindows(OADetailActivity.this, ll_main);//                openFileChooser(uploadFile);            }            // Android 3.0            public void openFileChooser(ValueCallback uploadFile)            {                // Toast.makeText(WebviewActivity.this, "上传文件/图片",Toast.LENGTH_SHORT).show();                openFileChooser(uploadFile,"");            }        });    }    public boolean onKeyDown(int keyCode, KeyEvent event) {        if ((keyCode == KeyEvent.KEYCODE_BACK) && wv_project_brief.canGoBack()) {            wv_project_brief.goBack();            return true;        }        return super.onKeyDown(keyCode, event);    }    public class PopupWindows extends PopupWindow {        public PopupWindows(Context mContext, View parent) {            View view = View.inflate(mContext, R.layout.add_photo_pupwindow, null);            view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);            setFocusable(true);            setOutsideTouchable(true);            setContentView(view);            showAtLocation(parent, Gravity.BOTTOM, 0, 0);            update();            TextView tv_take_photo = (TextView) view.findViewById(R.id.tv_take_photo);            TextView tv_pick_photo = (TextView) view.findViewById(R.id.tv_pick_photo);            TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);            tv_take_photo.setOnClickListener(new View.OnClickListener() {                public void onClick(View v) {                    takePhoto();                    dismiss();                }            });            tv_pick_photo.setOnClickListener(new View.OnClickListener() {                public void onClick(View v) {                    doPickPhotoFromGallery();                    dismiss();                }            });            tv_cancel.setOnClickListener(new View.OnClickListener() {                public void onClick(View v) {                    dismiss();                }            });        }    }    public void takePhoto() {        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);        File vFile = new File(Environment.getExternalStorageDirectory()                + "/bxt_image/", String.valueOf(System.currentTimeMillis())                + ".jpg");        if (!vFile.exists()) {            File vDirPath = vFile.getParentFile();            vDirPath.mkdirs();        } else {            if (vFile.exists()) {                vFile.delete();            }        }        headPath = vFile.getPath();        Uri cameraUri = Uri.fromFile(vFile);        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);        startActivityForResult(openCameraIntent, REQUESTCODE_TAKE);    }    protected void doPickPhotoFromGallery() {        Intent intent = new Intent(Intent.ACTION_PICK, null);        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");        startActivityForResult(intent, REQUESTCODE_PICK);    }    /**     * 裁剪图片方法实现     *     * @param uri     */    public void startPhotoZoom(Uri uri) {        Intent intent = new Intent("com.android.camera.action.CROP");        intent.setDataAndType(uri, "image/*");        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪        intent.putExtra("crop", "true");        // aspectX aspectY 是宽高的比例        intent.putExtra("aspectX", 1);        intent.putExtra("aspectY", 1);        // outputX outputY 是裁剪图片宽高        intent.putExtra("outputX", 300);        intent.putExtra("outputY", 300);//        intent.putExtra("return-data", true);        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());        startActivityForResult(intent, REQUESTCODE_CUTTING);    }    String urlpath;//裁剪后的图片路径    /**     * 保存裁剪之后的图片数据     *     * @param picdata     */    private void setPicToView(Intent picdata) {//        Bundle extras = picdata.getExtras();//        if (extras != null) {            // 取得SDCard图片路径做显示//            Bitmap photo = extras.getParcelable("data");            try {                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));                urlpath = FileUtil.saveFile(this, System.currentTimeMillis()+".jpg", bitmap);            } catch (FileNotFoundException e) {                e.printStackTrace();            }            try {                postFile(urlpath);            } catch (Exception e) {                e.printStackTrace();            }//        }    }    public void postFile(String path) throws Exception {        File file = new File(path);        if (file.exists() && file.length() > 0) {            Uri uri = Uri.fromFile(file);            if(mUploadFile!=null){                mUploadFile.onReceiveValue(uri);                mUploadFile = null;            }            if(mUploadCallbackAboveL!=null){                mUploadCallbackAboveL.onReceiveValue(new Uri[]{uri});                mUploadCallbackAboveL = null;            }        } else {            LogUtils.i(TAG, "no file");        }    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        switch (requestCode) {            case REQUESTCODE_TAKE:// 调用相机拍照                if (resultCode == RESULT_OK) {                    File temp = new File(headPath);                    startPhotoZoom(Uri.fromFile(temp));                }                break;            case REQUESTCODE_PICK:// 直接从相册获取                try {                    startPhotoZoom(data.getData());                } catch (NullPointerException e) {                    e.printStackTrace();// 用户点击取消操作                }                break;            case REQUESTCODE_CUTTING:// 取得裁剪后的图片                if (data != null) {                    setPicToView(data);                }                break;        }        if(resultCode==0){            if(mUploadFile!=null){                mUploadFile.onReceiveValue(null);            }            if(mUploadCallbackAboveL!=null){                mUploadCallbackAboveL.onReceiveValue(null);            }        }        super.onActivityResult(requestCode, resultCode, data);    }    @Override    public void onResume() {        super.onResume();        try {            wv_project_brief.getClass().getMethod("onResume").invoke(wv_project_brief, (Object[])null);        } catch (IllegalAccessException e) {            e.printStackTrace();        } catch (InvocationTargetException e) {            e.printStackTrace();        } catch (NoSuchMethodException e) {            e.printStackTrace();        }    }    @Override    public void onPause() {        super.onPause();        try {            wv_project_brief.getClass().getMethod("onPause").invoke(wv_project_brief, (Object[])null);        } catch (IllegalAccessException e) {            e.printStackTrace();        } catch (InvocationTargetException e) {            e.printStackTrace();        } catch (NoSuchMethodException e) {            e.printStackTrace();        }    }}
public class FileUtil {    /**     * 将Bitmap 图片保存到本地路径,并返回路径     *     * @param c     * @param mType    资源类型,参照  MultimediaContentType 枚举,根据此类型,保存时可自动归类     * @param fileName 文件名称     * @param bitmap   图片     * @return     */    public static String saveFile(Context c, String fileName, Bitmap bitmap) {        return saveFile(c, "", fileName, bitmap);    }    public static String saveFile(Context c, String filePath, String fileName, Bitmap bitmap) {        byte[] bytes = bitmapToBytes(bitmap);        return saveFile(c, filePath, fileName, bytes);    }    public static byte[] bitmapToBytes(Bitmap bm) {        ByteArrayOutputStream baos = new ByteArrayOutputStream();        bm.compress(CompressFormat.JPEG, 100, baos);        return baos.toByteArray();    }    public static String saveFile(Context c, String filePath, String fileName, byte[] bytes) {        String fileFullName = "";        FileOutputStream fos = null;        String dateFolder = new SimpleDateFormat("yyyyMMdd", Locale.CHINA)                .format(new Date());        try {            String suffix = "";            if (filePath == null || filePath.trim().length() == 0) {                filePath = Environment.getExternalStorageDirectory() + "/BXT_SetPic/" + dateFolder + "/";            }            File file = new File(filePath);            if (!file.exists()) {                file.mkdirs();            }            File fullFile = new File(filePath, fileName + suffix);            fileFullName = fullFile.getPath();            fos = new FileOutputStream(new File(filePath, fileName + suffix));            fos.write(bytes);        } catch (Exception e) {            fileFullName = "";        } finally {            if (fos != null) {                try {                    fos.close();                } catch (IOException e) {                    fileFullName = "";                }            }        }        return fileFullName;    }}



更多相关文章

  1. android 一年过期
  2. ubuntu-11.04下android开发环境搭建
  3. android上传图片到服务器,求服务器那边和android的Activity的完整
  4. android上传图片到服务器,求服务器那边和android的Activity的完整
  5. Android学习之图片异步加载框架Picasso
  6. Android学习之系统默认路径
  7. Android(安卓)使用level-list改变对应的状态图片
  8. 工程 android上传图片至服务器
  9. 开发环境的搭建-----------Day01 2014-5-26

随机推荐

  1. Android(安卓)TimeLine 时间节点轴的实现
  2. android 处理图片的工具类
  3. Android(安卓)全面屏的和有导航栏的判断
  4. Android的NDK开发(5)————Android(安
  5. Android(安卓)DOC文档分析——Dialog
  6. android 获取屏幕的方向
  7. 【notification】Android(安卓)中创建状
  8. Android(安卓)studio Caused by: org.gra
  9. 关于android studio报错transformClasses
  10. Known Free Software Android(安卓)Appli