Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

WebView 上傳圖片的那些坑:版本兼容與混淆陷阱

編輯:關於 Android 程式設計

最近項目需要在 WebView 頁面裡調起系統相冊上傳圖片,結果在不少機型上根本喚不起相冊。折騰一番後發現,這事兒的坑不止一個,而是整整三層。

先理清 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

以上就是本文的全部內容,希望對大家的學習有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved