轉載請註明出處:www.jianshu.com/p/48e688ce8…歡迎
歡迎你們關注個人知乎專欄:zhuanlan.zhihu.com/baron 之後全部文章都會在知乎專欄和掘金上首發html
最近公司項目須要在WebView
上調用手機系統相冊來上傳圖片,開發過程當中發如今不少機器上沒法正常喚起系統相冊來選擇圖片。android
解決問題以前咱們先來講說WebView
上傳文件的邏輯:當咱們在Web頁面上點擊選擇文件的控件(<input type="file">
)時,會回調WebChromeClient
下的openFileChooser()
(5.0及以上系統回調onShowFileChooser()
)。這個時候咱們在openFileChooser
方法中經過Intent
打開系統相冊或者支持該Intent
的第三方應用來選擇圖片。like this:git
public void openFileChooser(ValueCallbackvalueCallback, 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上傳。代碼以下:github
@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
就知道咱們選擇了什麼文件。web
到這裏你可能要問了,說了這麼多仍是沒解釋爲何在不少機型上沒法喚起系統相冊或者第三方app來選擇圖片啊?!這是由於爲了最求完美的Google攻城獅們對openFileChooser
作了屢次修改,在5.0上更是將回調方法該爲了onShowFileChooser
。因此爲了解決這一問題,兼容各個版本,咱們須要對openFileChooser()
進行重載,同時針對5.0及以上系統提供onShowFileChooser()
方法:app
webview.setWebChromeClient(new WebChromeClient() { // For Android < 3.0 public void openFileChooser(ValueCallbackvalueCallback) { *** } // For Android >= 3.0 public void openFileChooser(ValueCallback valueCallback, String acceptType) { *** } //For Android >= 4.1 public void openFileChooser(ValueCallback 複製代碼valueCallback, String acceptType, String capture) { *** } // For Android >= 5.0 @Override public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { *** return true; } });
你們應該注意到onShowFileChooser()
中的ValueCallback
包含了一組Uri(Uri[])
,因此針對5.0及以上系統,咱們還須要對onActivityResult()
作一點點處理。這裏不作描述,最後我再貼上完整代碼。ide
當處理完這些後你覺得就萬事大吉了?!當初我也這樣天真,但當咱們打好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(ValueCallbackuploadFile, String acceptType, String capture) { uploadFile.onReceiveValue(null); } 複製代碼
解決方案也很簡單,直接不混淆openFileChooser()
就行了。ui
-keepclassmembers class * extends android.webkit.WebChromeClient{
public void openFileChooser(...);
}複製代碼
支持關於上傳文件的全部坑都填完了,最後附上完整源碼: (源碼地址:github.com/BaronZ88/We…)this
public class MainActivity extends AppCompatActivity { private ValueCallbackuploadMessage; private ValueCallback 複製代碼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 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 valueCallback, String acceptType, String capture) { uploadMessage = valueCallback; openImageChooserActivity(); } // For Android >= 5.0 @Override public boolean onShowFileChooser(WebView webView, ValueCallback 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; } }
若是你們喜歡這一系列的文章,歡迎關注個人知乎專欄、GitHub、簡書博客。
- 知乎專欄:zhuanlan.zhihu.com/baron
- GitHub:github.com/BaronZ88
- 簡書博客:www.jianshu.com/users/cfdc5…