WebView加载网页-进度显示-网络上传图片并压缩

布局中的实现代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <WebView 
        android:id="@+id/wv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</RelativeLayout>

主类中的实现代码

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.widget.Toast;

@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
    private String url = "http://101.200.142.201";
    private WebView my_web;
    private ProgressDialog proDlg;
    private Uri imageUri;
    public ValueCallback<Uri> mUploadMessage;
    public final static int REQ_CHOOSER = 1;
    private final static int REQ_CAMERA = 2;
    private File vFile;

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        my_web = (WebView) findViewById(R.id.wv);

        // 支持脚本
        my_web.getSettings().setJavaScriptEnabled(true);
        // 加载服务器的路径
        my_web.loadUrl(url);
        // 创建对话框
        proDlg = new ProgressDialog(MainActivity.this);
        my_web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // my_web.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                proDlg.setMessage("正在加载,请稍候...");
                // 显示加载进度对话框
                proDlg.show();
            }

            /**
             * 页面加载完成时,回调此方法
             */
            @Override
            public void onPageFinished(WebView view, String url) {
                // 隐藏加载进度对话框
                proDlg.dismiss();
            }
        });

        my_web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                proDlg.setMessage("loading" + newProgress + "%......");
            }

            // For Android 3.0+
            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooser(uploadMsg, "");
            }

            // For Android 3.0+
            public void openFileChooser(@SuppressWarnings("rawtypes") ValueCallback uploadMsg,
                    String acceptType) {
                openFileChooser(uploadMsg, acceptType);
            }

            // For Android 4.1
            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg,
                    String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                selectImage();
            }

        });
    }

    protected final void selectImage() {
        AlertDialog.Builder builder = new Builder(MainActivity.this);
        // builder.setTitle("插入照片");
        final String[] items = { "照相机", "相册" };
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @SuppressLint("SdCardPath")
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(), items[which],
                        Toast.LENGTH_SHORT).show();
                Intent intent = null;
                switch (which) {
                // 调用照相机
                case 0:
                    intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    // 必须确保文件夹路径存在,否则拍照后无法完成回调
                    vFile = new File(Environment.getExternalStorageDirectory()
                            .getPath()
                            + "/DCIM/Camera/"
                            + (System.currentTimeMillis() + ".jpg"));
                    /*
                     * 判断文件是否存在,如果不存在,在创建,如果存在,则删除
                     */
                    if (!vFile.exists()) {
                        File vDirPath = vFile.getParentFile();
                        vDirPath.mkdirs();
                    } else {
                        if (vFile.exists()) {
                            vFile.delete();
                        }
                    }
                    imageUri = Uri.fromFile(vFile);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    MainActivity.this
                            .startActivityForResult(intent, REQ_CAMERA);
                    break;
                    //相册
                case 1:
                    intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            "image/*");
                    MainActivity.this.startActivityForResult(
                            Intent.createChooser(intent, "选择图片"), REQ_CHOOSER);
                    break;
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

                if (mUploadMessage == null) {
                    mUploadMessage.onReceiveValue(null);
                    selectImage();
                }

            }
        });
        builder.create().show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        //照相机
        case REQ_CHOOSER:
            if (null == mUploadMessage)
                return;
            String path = getAbsoluteImagePath(data.getData());
            Bitmap bitmap = getimage(path);
            imageUri = Uri.parse(MediaStore.Images.Media.insertImage(
                    getContentResolver(), bitmap, null, null));
            Uri result = data == null || resultCode != RESULT_OK ? null : data
                    .getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
            break;
            //相册
        case REQ_CAMERA:
            if (resultCode == Activity.RESULT_OK) {
                //得到相册中图片的路径
                Bitmap bitmap1 = getimage(vFile.getPath());
                imageUri = Uri.parse(MediaStore.Images.Media.insertImage(
                        getContentResolver(), bitmap1, null, null));
                mUploadMessage.onReceiveValue(imageUri);
                mUploadMessage = null;
            }
            break;
        }
    }
/*
 * 压缩图片
 * */
    private Bitmap getimage(String srcPath) {

        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
        float hh = 800f;// 这里设置高度为800f
        float ww = 480f;// 这里设置宽度为480f
        // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据高度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
    }

    private Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    protected String getAbsoluteImagePath(Uri uri) {
        // can post image
        String[] proj = { MediaStore.Images.Media.DATA };
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(uri, proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)

        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
    }

    // 此按键监听的是返回键,能够返回到上一个网页(通过网页的hostlistery)
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && my_web.canGoBack()) {
            my_web.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

将上面的的两段代码粘上就能实现下面的效果
这里写图片描述

这里写图片描述
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值