Android WebView基本使用(二)(页面浏览:前进,后退,退出、拍照或从文件中选择图片、安全)

  • 页面浏览
    1. 根据webView中维护的页面浏览历史,允许用户向前向后浏览页面。

使用后退键进行网页后退:

/**

 * 按键响应,在WebView中查看网页时,按返回键的时候按浏览历史退回,如果不做此项处 理则整个WebView返回退出

 */

    @Override

    public boolean onKeyDown(int keyCode, KeyEvent event)

    {

        // Check if the key event was the Back button and if there's history

        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())

        {

            // 返回键退回,返回上一个页面

            myWebView.goBack();

            return true;

        }

        // If it wasn't the Back key or there's no web page history, bubble up

        // to the default

        // system behavior (probably exit the activity)

// 退出H5界面

        return super.onKeyDown(keyCode, event);

    }

    1.  
    2.  

 

  • 拍照或者从文件选择照片
    1. 申请动态权限

private static final int ACTION_REQUEST_PERMISSIONS = 0x001;

/**

     * 所需的所有权限信息

     */

    private static final String[] NEEDED_PERMISSIONS = new String[]{

            Manifest.permission.CAMERA,

            Manifest.permission.WRITE_EXTERNAL_STORAGE,

            Manifest.permission.READ_EXTERNAL_STORAGE

};

 

//界面可见的时候申请

@Override

    public void initView() {

        if (!checkPermissions(NEEDED_PERMISSIONS)) {

            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);

        } else {

  //存在权限的操作

            ....

        }

 

    }

 

/**

 * 检查权限

 *

 * @param neededPermissions

 * @return

 */

 private boolean checkPermissions(String[] neededPermissions) {

    if (neededPermissions == null || neededPermissions.length == 0) {

        return true;

    }

    boolean allGranted = true;

    for (String neededPermission : neededPermissions) {

        allGranted &= ContextCompat.checkSelfPermission(this, neededPermission) == PackageManager.PERMISSION_GRANTED;

    }

    return allGranted;

}

 

//申请权限返回

@Override

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == ACTION_REQUEST_PERMISSIONS) {

            boolean isAllGranted = true;

            for (int grantResult : grantResults) {

                isAllGranted &= (grantResult == PackageManager.PERMISSION_GRANTED);

            }

            if (isAllGranted) {

                weakHandler = new WeakHandler(this);

                weakHandler.sendEmptyMessageDelayed(1, 3000);

            } else {

                Toast.makeText(this, "权限被拒绝!", Toast.LENGTH_SHORT).show();

            }

        }

    }

    1. android Q对于文件读写引入了新特性,在这个版本中,READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE均受到了限制,无法再像之前的版本直接获取到文件。如果希望恢复之前的权限逻辑,可以在manifest文件中设置:

android:requestLegacyExternalStorage="true"

    1. 常量,Android版本兼容

//5.0以下使用

private ValueCallback<Uri> uploadMessage;

// 5.0及以上使用

private ValueCallback<Uri[]> uploadMessageAboveL;

//拍照图片路径

private String cameraFielPath;

private final static int FILE_CAMERA_RESULT_CODE = 0x129;

WebView.setWebChromeClient(new WebChromeClient() {

    // For Android < 3.0

    public void openFileChooser(ValueCallback<Uri> valueCallback) {

         uploadMessage = valueCallback;

         takeCameraPhoto();

    }

 

    // For Android  >= 3.0

    public void openFileChooser(ValueCallback valueCallback, String acceptType) {

         uploadMessage = valueCallback;

         takeCameraPhoto();

    }

 

    //For Android  >= 4.1

    public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {

          uploadMessage = valueCallback;

          takeCameraPhoto();

    }

 

    // For Android >= 5.0

    @Override

    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {

          uploadMessageAboveL = filePathCallback;

          takeCameraPhoto();

          return true;

     }

});

 

//调用拍照或文件中选择

private void takeCameraPhoto() {

   //拍照图片保存位置

   File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");

   if (!imageStorageDir.exists()) {

        imageStorageDir.mkdirs();

   }

   cameraFielPath = imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg";

   File file = new File(cameraFielPath);

   //需要显示应用的意图列表,这个list的顺序和选择菜单上的图标顺序是相关的,请注意。

   final List<Intent> cameraIntents = new ArrayList<Intent>();

   final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

   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, Uri.fromFile(file));

        cameraIntents.add(i);

   }

   //相册选择器

   Intent i = new Intent(Intent.ACTION_GET_CONTENT);

   i.addCategory(Intent.CATEGORY_OPENABLE);

   i.setType("image/*");

   //intent选择器

   Intent chooserIntent = Intent.createChooser(i, "选择模式");

   chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));

   this.startActivityForResult(chooserIntent, FILE_CAMERA_RESULT_CODE);

  }

 

//返回数据监听

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

   super.onActivityResult(requestCode, resultCode, data);

    //没有返回值时的处理

    if (resultCode != RESULT_OK) {

            //需要回调onReceiveValue方法防止下次无法响应js方法

            if (uploadMessageAboveL != null) {

                uploadMessageAboveL.onReceiveValue(null);

                uploadMessageAboveL = null;

            }

            if (uploadMessage != null) {

                uploadMessage.onReceiveValue(null);

                uploadMessage = null;

            }

            return;

        }

 

        Uri result = null;

        if (requestCode == FILE_CAMERA_RESULT_CODE) {

            if (null != data && null != data.getData()) {

                result = data.getData();

            }

            if (result == null) {

                result = Uri.fromFile(new File(cameraFielPath));

            }

            //5.0以上设备的数据处理

            if (uploadMessageAboveL != null) {

                uploadMessageAboveL.onReceiveValue(new Uri[]{result});

                uploadMessageAboveL = null;

            } else if (uploadMessage != null) {

                //5.0以下设备的数据处理

                uploadMessage.onReceiveValue(result);

                uploadMessage = null;

            }

        }

    }

 

  • 避免内存泄漏,安全
    1. 建议不要在xml布局文件中getApplicationgContext()定义Webview控件 ,而是在需要的时候在Activity中直接创建,并且Context上下文对象推荐使用

LinearLayout.LayoutParams params =

new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

webView = new WebView(getApplicationContext());

webView.setLayoutParams(params);

mLayout.addView(webView);

    1. 在Activity销毁(WebView)时,先让WebView加载null内容,然后移除WebView,再销毁WebView,最后把WebView设置为null。

@Override

protected void onDestroy() {

    if (webView != null) {

        webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);

        webView.clearHistory();

 ((ViewGroup) webView.getParent()).removeView(mWebView);

        webView.destroy();

        webView = null;

    }

    super.onDestroy();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值