欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android WebView那些坑之上传文件示例

程序员文章站 2023-12-20 19:36:58
最近公司项目需要在webview上调用手机系统相册来上传图片,开发过程中发现在很多机器上无法正常唤起系统相册来选择图片。 解决问题之前我们先来说说webview上传文件的...

最近公司项目需要在webview上调用手机系统相册来上传图片,开发过程中发现在很多机器上无法正常唤起系统相册来选择图片。

解决问题之前我们先来说说webview上传文件的逻辑:当我们在web页面上点击选择文件的控件(<input type="file">)时,会回调webchromeclient下的openfilechooser()(5.0及以上系统回调onshowfilechooser())。这个时候我们在openfilechooser方法中通过intent打开系统相册或者支持该intent的第三方应用来选择图片。like this:

public void openfilechooser(valuecallback<uri> valuecallback, string accepttype, string capture) {
 uploadmessage = valuecallback;
  openimagechooseractivity();
}

private void openimagechooseractivity() {
 intent i = new intent(intent.action_get_content);
 i.addcategory(intent.category_openable);
 i.settype("image/*");
 startactivityforresult(intent.createchooser(i, 
    "image chooser"), file_chooser_result_code);
}

最后我们在onactivityresult()中将选择的图片内容通过valuecallback的onreceivevalue方法返回给webview,然后通过js上传。代码如下:

@override
protected void onactivityresult(int requestcode, int resultcode, intent data) {
 super.onactivityresult(requestcode, resultcode, data);
 if (requestcode == file_chooser_result_code) {
  uri result = data == null || resultcode != result_ok ? null : data.getdata();
  if (uploadmessage != null) {
   uploadmessage.onreceivevalue(result);
   uploadmessage = null;
  }
 }
}

ps:valuecallbacks是webview组件通过openfilechooser()或者onshowfilechooser()提供给我们的,它里面包含了一个或者一组uri,然后我们在onactivityresult()里将uri传给valuecallbacks的onreceivevalue()方法,这样webview就知道我们选择了什么文件。

webview.setwebchromeclient(new webchromeclient() {

  // for android < 3.0
  public void openfilechooser(valuecallback<uri> valuecallback) {
   ***
  }

  // for android >= 3.0
  public void openfilechooser(valuecallback valuecallback, string accepttype) {
   ***
  }

  //for android >= 4.1
  public void openfilechooser(valuecallback<uri> valuecallback, 
    string accepttype, string capture) {
   ***
  }

  // for android >= 5.0
  @override
  public boolean onshowfilechooser(webview webview, 
    valuecallback<uri[]> filepathcallback, 
    webchromeclient.filechooserparams filechooserparams) {
   ***
   return true;
  }
 });

到这里你可能要问了,说了这么多还是没解释为什么在很多机型上无法唤起系统相册或者第三方app来选择图片啊?!这是因为为了最求完美的google攻城狮们对openfilechooser做了多次修改,在5.0上更是将回调方法该为了onshowfilechooser。所以为了解决这一问题,兼容各个版本,我们需要对openfilechooser()进行重载,同时针对5.0及以上系统提供onshowfilechooser()方法:

webview.setwebchromeclient(new webchromeclient() {

  // for android < 3.0
  public void openfilechooser(valuecallback<uri> valuecallback) {
   ***
  }

  // for android >= 3.0
  public void openfilechooser(valuecallback valuecallback, string accepttype) {
   ***
  }

  //for android >= 4.1
  public void openfilechooser(valuecallback<uri> valuecallback, 
    string accepttype, string capture) {
   ***
  }

  // for android >= 5.0
  @override
  public boolean onshowfilechooser(webview webview, 
    valuecallback<uri[]> filepathcallback, 
    webchromeclient.filechooserparams filechooserparams) {
   ***
   return true;
  }
 });

大家应该注意到onshowfilechooser()中的valuecallback包含了一组uri(uri[]),所以针对5.0及以上系统,我们还需要对onactivityresult()做一点点处理。这里不做描述,最后我再贴上完整代码。

当处理完这些后你以为就万事大吉了?!当初我也这样天真,但当我们打好release包测试的时候却又发现没法选择图片了!!!真是坑了个爹啊!!!无奈去翻webchromeclient的源码,发现openfilechooser()是系统api,我们的release包是开启了混淆的,所以在打包的时候混淆了openfilechooser(),这就导致无法回调openfilechooser()了。

/**
 * tell the client to open a file chooser.
 * @param uploadfile a valuecallback to set the uri of the file to upload.
 *  onreceivevalue must be called to wake up the thread.a
 * @param accepttype the value of the 'accept' attribute of the input tag
 *   associated with this file picker.
 * @param capture the value of the 'capture' attribute of the input tag
 *   associated with this file picker.
 *
 * @deprecated use {@link #showfilechooser} instead.
 * @hide this method was not published in any sdk version.
 */
@systemapi
@deprecated
public void openfilechooser(valuecallback<uri> uploadfile, string accepttype, string capture) {
 uploadfile.onreceivevalue(null);
}

解决方案也很简单,直接不混淆openfilechooser()就好了。

-keepclassmembers class * extends android.webkit.webchromeclient{
  public void openfilechooser(...);
}

支持关于上传文件的所有坑都填完了,最后附上完整源码:

public class mainactivity extends appcompatactivity {

 private valuecallback<uri> uploadmessage;
 private valuecallback<uri[]> uploadmessageabovel;
 private final static int file_chooser_result_code = 10000;

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);

  webview webview = (webview) findviewbyid(r.id.web_view);
  assert webview != null;
  websettings settings = webview.getsettings();
  settings.setusewideviewport(true);
  settings.setloadwithoverviewmode(true);
  settings.setjavascriptenabled(true);
  webview.setwebchromeclient(new webchromeclient() {

   // for android < 3.0
   public void openfilechooser(valuecallback<uri> valuecallback) {
    uploadmessage = valuecallback;
    openimagechooseractivity();
   }

   // for android >= 3.0
   public void openfilechooser(valuecallback valuecallback, string accepttype) {
    uploadmessage = valuecallback;
    openimagechooseractivity();
   }

   //for android >= 4.1
   public void openfilechooser(valuecallback<uri> valuecallback, string accepttype, string capture) {
    uploadmessage = valuecallback;
    openimagechooseractivity();
   }

   // for android >= 5.0
   @override
   public boolean onshowfilechooser(webview webview, valuecallback<uri[]> filepathcallback, webchromeclient.filechooserparams filechooserparams) {
    uploadmessageabovel = filepathcallback;
    openimagechooseractivity();
    return true;
   }
  });
  string targeturl = "file:///android_asset/up.html";
  webview.loadurl(targeturl);
 }

 private void openimagechooseractivity() {
  intent i = new intent(intent.action_get_content);
  i.addcategory(intent.category_openable);
  i.settype("image/*");
  startactivityforresult(intent.createchooser(i, "image chooser"), file_chooser_result_code);
 }

 @override
 protected void onactivityresult(int requestcode, int resultcode, intent data) {
  super.onactivityresult(requestcode, resultcode, data);
  if (requestcode == file_chooser_result_code) {
   if (null == uploadmessage && null == uploadmessageabovel) return;
   uri result = data == null || resultcode != result_ok ? null : data.getdata();
   if (uploadmessageabovel != null) {
    onactivityresultabovel(requestcode, resultcode, data);
   } else if (uploadmessage != null) {
    uploadmessage.onreceivevalue(result);
    uploadmessage = null;
   }
  }
 }

 @targetapi(build.version_codes.lollipop)
 private void onactivityresultabovel(int requestcode, int resultcode, intent intent) {
  if (requestcode != file_chooser_result_code || uploadmessageabovel == null)
   return;
  uri[] results = null;
  if (resultcode == activity.result_ok) {
   if (intent != null) {
    string datastring = intent.getdatastring();
    clipdata clipdata = intent.getclipdata();
    if (clipdata != null) {
     results = new uri[clipdata.getitemcount()];
     for (int i = 0; i < clipdata.getitemcount(); i++) {
      clipdata.item item = clipdata.getitemat(i);
      results[i] = item.geturi();
     }
    }
    if (datastring != null)
     results = new uri[]{uri.parse(datastring)};
   }
  }
  uploadmessageabovel.onreceivevalue(results);
  uploadmessageabovel = null;
 }
}

源码地址: http://xiazai.jb51.net/201701/yuanma/webviewsample_jb51.rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: