編輯:關於 Android 程式設計
最近項目需要在 WebView 頁面裡調起系統相冊上傳圖片,結果在不少機型上根本喚不起相冊。折騰一番後發現,這事兒的坑不止一個,而是整整三層。
當用戶在網頁上點擊選擇文件的控件(<input type="file">)時,系統會回調 WebChromeClient 的 openFileChooser();Android 5.0 及以上則改為回調 onShowFileChooser()。我們在這個方法裡用 Intent 打開系統相冊或任何支持該 Intent 的第三方應用:
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:ValueCallback 是 WebView 通過 openFileChooser() 或 onShowFileChooser() 交給我們的,裡面包著一個或一組 Uri。我們在 onActivityResult() 中調用它的 onReceiveValue(),WebView 才知道用戶到底選了什麼文件。
為什麼很多機型喚不起相冊?因為 openFileChooser 這個方法在版本演進中被改了好幾次,5.0 更是直接換成了 onShowFileChooser。不解決的話,5.0 以上設備自然毫無反應。所以我們需要把三個重載全部實現,並額外覆寫 5.0 的新方法:
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() 也要相應改造,需要從 ClipData 中逐個取出。
處理完兼容問題,我以為萬事大吉。結果打 release 包一測——又不能選圖了。翻 WebChromeClient 源碼才明白:openFileChooser() 屬於系統 API,而 release 包開啟了混淆,方法名被改寫,系統自然找不到它去回調。
/**
* 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.
* @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);
}
解法很直接——別混淆它:
-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;
}
}
源碼地址:https://xiazai.jb51.net/201701/yuanma/WebViewSample_jb51.rar
以上就是本文的全部內容,希望對大家的學習有所幫助。
Android 用 ExpandableListView 實現仿 QQ 分組列表與搜索
項目開發中,我們常常需要把用戶信息按「組」來分層展示,同時支持按關鍵字搜索、並用顏色選擇器為列表項設置背景色。本文用 ExpandableListView 打造一個仿 Q
Android 自定義 View 學習(5):手刻指針式進度條與圓環進度條
自定義 View 系列走到最後一期,先來看成品。 相信讀到這裡,各位心中多少都已經有了自己的實作思路。以下把我的做法貼出來供參考。 第一個:指針刻度式進度條 先準備兩
怎麼在安卓模擬器裡安裝 App:BlueStacks 安裝 APK 檔
怎麼在安卓模擬器裡裝 App?它不像一般軟體那樣拉進視窗就裝好了,我起初也一直裝不上去,試過幾種方式之後才找到訣竅。以下把流程分享出來。 BlueStacks 安卓模擬器
Android 開發疑難:Private Libraries 無法附加原始碼的處理方式
一、問題描述 在 ADT 中查看 android.jar 的類別時,會看到類似這樣的提示: The JAR of this class file belongs to c