Android WebView那些坑之上傳文件示例
最近公司項(xiàng)目需要在WebView上調(diào)用手機(jī)系統(tǒng)相冊(cè)來上傳圖片,開發(fā)過程中發(fā)現(xiàn)在很多機(jī)器上無法正常喚起系統(tǒng)相冊(cè)來選擇圖片。
解決問題之前我們先來說說WebView上傳文件的邏輯:當(dāng)我們?cè)赪eb頁面上點(diǎn)擊選擇文件的控件(<input type="file">)時(shí),會(huì)回調(diào)WebChromeClient下的openFileChooser()(5.0及以上系統(tǒng)回調(diào)onShowFileChooser())。這個(gè)時(shí)候我們?cè)趏penFileChooser方法中通過Intent打開系統(tǒng)相冊(cè)或者支持該Intent的第三方應(yīng)用來選擇圖片。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); }
最后我們?cè)趏nActivityResult()中將選擇的圖片內(nèi)容通過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()提供給我們的,它里面包含了一個(gè)或者一組Uri,然后我們?cè)趏nActivityResult()里將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; } });
到這里你可能要問了,說了這么多還是沒解釋為什么在很多機(jī)型上無法喚起系統(tǒng)相冊(cè)或者第三方app來選擇圖片啊?!這是因?yàn)闉榱俗钋笸昝赖腉oogle攻城獅們對(duì)openFileChooser做了多次修改,在5.0上更是將回調(diào)方法該為了onShowFileChooser。所以為了解決這一問題,兼容各個(gè)版本,我們需要對(duì)openFileChooser()進(jìn)行重載,同時(shí)針對(duì)5.0及以上系統(tǒng)提供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; } });
大家應(yīng)該注意到onShowFileChooser()中的ValueCallback包含了一組Uri(Uri[]),所以針對(duì)5.0及以上系統(tǒng),我們還需要對(duì)onActivityResult()做一點(diǎn)點(diǎn)處理。這里不做描述,最后我再貼上完整代碼。
當(dāng)處理完這些后你以為就萬事大吉了?!當(dāng)初我也這樣天真,但當(dāng)我們打好release包測(cè)試的時(shí)候卻又發(fā)現(xiàn)沒法選擇圖片了!??!真是坑了個(gè)爹啊?。?!無奈去翻WebChromeClient的源碼,發(fā)現(xiàn)openFileChooser()是系統(tǒng)API,我們的release包是開啟了混淆的,所以在打包的時(shí)候混淆了openFileChooser(),這就導(dǎo)致無法回調(diào)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); }
解決方案也很簡(jiǎn)單,直接不混淆openFileChooser()就好了。
-keepclassmembers class * extends android.webkit.WebChromeClient{ public void openFileChooser(...); }
支持關(guān)于上傳文件的所有坑都填完了,最后附上完整源碼:
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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android復(fù)選框?qū)υ捒蛴梅▽?shí)例簡(jiǎn)析
這篇文章主要介紹了Android復(fù)選框?qū)υ捒蛴梅?結(jié)合實(shí)例形式簡(jiǎn)單分析了Android復(fù)選對(duì)話框的創(chuàng)建與使用技巧,需要的朋友可以參考下2016-01-01Android Studio實(shí)現(xiàn)QQ的注冊(cè)登錄和好友列表跳轉(zhuǎn)
最近做了一個(gè)項(xiàng)目,這篇文章主要介紹了Android Studio界面跳轉(zhuǎn),本次項(xiàng)目主要包含了注冊(cè)、登錄和好友列表三個(gè)界面以及之間相互跳轉(zhuǎn),感興趣的可以了解一下2021-05-05Android利用Intent啟動(dòng)和關(guān)閉Activity
這篇文章主要為大家詳細(xì)介紹了Android利用Intent啟動(dòng)和關(guān)閉Activity的相關(guān)操作,感興趣的小伙伴們可以參考一下2016-06-06Android Studio中CodeStyle模板的配置方式
這篇文章主要介紹了Android Studio中CodeStyle模板的配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03Android調(diào)用系統(tǒng)裁剪的實(shí)現(xiàn)方法
下面小編就為大家分享一篇Android調(diào)用系統(tǒng)裁剪的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-02-02詳解Android ScrollView嵌套EditText出現(xiàn)的滑動(dòng)問題
本篇文章主要介紹了詳解ScrollView嵌套EditText出現(xiàn)的滑動(dòng)問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-01-01Android WebView如何判定網(wǎng)頁加載的錯(cuò)誤
這篇文章主要介紹了Android WebView如何判定網(wǎng)頁加載的錯(cuò)誤,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-04-04Android編程實(shí)現(xiàn)創(chuàng)建,刪除,判斷快捷方式的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)創(chuàng)建,刪除,判斷快捷方式的方法,結(jié)合實(shí)例形式分析了Android編程針對(duì)快捷方式的常用操作技巧,需要的朋友可以參考下2017-02-02Android實(shí)現(xiàn)監(jiān)聽音量的變化
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)監(jiān)聽音量的變化,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-05-05