怎麼解決安卓4.4.1和4.4.2 webview 不支持<input type="file" />?

RT.

在web前端有什麼好的解決辦法?


不是不支持&,而是因為Google攻城獅們對WebChromeClient做了多次修改,並且特么次次都不向下兼容,針對於4.1到5.0的設備需要我們重寫openFileChooser(ValueCallback& valueCallback,String acceptType, String capture)方法。具體內容可以參照我之前的文章:https://zhuanlan.zhihu.com/p/21643401

demo地址:https://github.com/BaronZ88/WebViewSample

=========================以下為文章全文=========================

最近公司項目需要在WebView上調用手機系統相冊來上傳圖片,開發過程中發現在很多機器上無法正常喚起系統相冊來選擇圖片。

解決問題之前我們先來說說WebView上傳文件的邏輯:當我們在Web頁面上點擊選擇文件的控制項(&)時,會回調WebChromeClient下的openFileChooser()(5.0及以上系統回調onShowFileChooser())。這個時候我們在openFileChooser方法中通過Intent打開系統相冊或者支持該Intent的第三方應用來選擇圖片。like this:

public void openFileChooser(ValueCallback& 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就知道我們選擇了什麼文件。

到這裡你可能要問了,說了這麼多還是沒解釋為什麼在很多機型上無法喚起系統相冊或者第三方app來選擇圖片啊?!這是因為為了最求完美的Google攻城獅們對openFileChooser做了多次修改,在5.0上更是將回調方法該為了onShowFileChooser。所以為了解決這一問題,兼容各個版本,我們需要對openFileChooser()進行重載,同時針對5.0及以上系統提供onShowFileChooser()方法:

webview.setWebChromeClient(new WebChromeClient() {

// For Android &< 3.0 public void openFileChooser(ValueCallback& valueCallback) {
***
}

// 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()做一點點處理。這裡不做描述,最後我再貼上完整代碼。

當處理完這些後你以為就萬事大吉了?!當初我也這樣天真,但當我們打好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& uploadFile, String acceptType, String capture) {
uploadFile.onReceiveValue(null);
}

解決方案也很簡單,直接不混淆openFileChooser()就好了。

-keepclassmembers class * extends android.webkit.WebChromeClient{
public void openFileChooser(...);
}

支持關於上傳文件的所有坑都填完了,最後附上完整源碼:

(源碼地址:GitHub - BaronZ88/WebViewSample: WebView填坑)

public class MainActivity extends AppCompatActivity {

private ValueCallback& uploadMessage;
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; } }

源碼地址:https://github.com/BaronZ88/WebViewSample


4.4.2系統對於各位答主的回答親測都不行,在項目中防止兼容性問題還是改為了用JS調用Java代碼,由Java代碼打開相冊,選擇完成圖片後再由Java代碼調用JS代碼將圖片地址傳遞過去。目前這是能想到最簡單並且兼容性好的方法。之前想過用phonegap,不知道是否可行?


mWebView.setWebChromeClient(new WebChromeClient() {

// 關鍵代碼,以下函數是沒有API文檔的,所以在Eclipse中會報錯,如果添加了@Override關鍵字在這裡的話。

// For Android 3.0+

public void openFileChooser(ValueCallback& uploadMsg) {

mUploadMessage = uploadMsg;

Intent i = new Intent(Intent.ACTION_GET_CONTENT);

i.addCategory(Intent.CATEGORY_OPENABLE);

i.setType("image/*");

MainActivity.this.startActivityForResult(

Intent.createChooser(i, "File Chooser"),

FILECHOOSER_RESULTCODE);

}

// For Android 3.0+

public void openFileChooser(ValueCallback uploadMsg,

String acceptType) {

mUploadMessage = uploadMsg;

Intent i = new Intent(Intent.ACTION_GET_CONTENT);

i.addCategory(Intent.CATEGORY_OPENABLE);

i.setType("*/*");

MainActivity.this.startActivityForResult(

Intent.createChooser(i, "File Chooser"),

FILECHOOSER_RESULTCODE);

}

// For Android 4.1

public void openFileChooser(ValueCallback& uploadMsg,

String acceptType, String capture) {

mUploadMessage = uploadMsg;

Intent i = new Intent(Intent.ACTION_GET_CONTENT);

i.addCategory(Intent.CATEGORY_OPENABLE);

i.setType("image/*");

MainActivity.this.startActivityForResult(

Intent.createChooser(i, "File Chooser"),

MainActivity.FILECHOOSER_RESULTCODE);

}

});


在4.2.2版本上樓上3個方法都不可行?有沒有解決方法?


推薦閱讀:

有沒有製作APP demo的工具?
如何用python開發移動App(android、iOS)後台?需要掌握哪些技術?
怎麼做好互聯網公司的技術團隊負責人?
vysor的實現原理是什麼?
如何看待谷歌要求OEM廠家保留並不得修改安卓6.0的Doze省電模式?

TAG:前端開發 | Android開發 | 前端工程師 | 移動開發 |