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

Cordova InAppBrowser 插件改造:讓 WebView 的 input type=file 支援選擇文件

編輯:關於 Android 程式設計

改造後支援的能力

1. 幾乎支援所有 Android 版本,從 2.x 到 7.0

Android 4.4、4.4.1 與 4.4.2 無法支援,因為當時 Google 認為 WebView 上傳檔案不安全而移除了這個功能,所以這三個版本沒有解法。不過現在基本上也很少遇到這三個系統版本的裝置了。4.4.3 與 4.4.4 則是支援的。

2. 支援 accept="" 屬性,可限制可選擇的檔案類型

如果指定 accept="image/*",就只會允許選擇圖片;若不指定,則可以選擇任何檔案。

3. 支援拍照上傳

指定 accept="image/*" 之後,除了選擇圖片,還可以直接拍照。

效果預覽

以下效果圖中的檔案選擇控制項都指定了 accept="image/*"。

Android 4.4.4:

Android 6.0:

Android 7.0:

一、修改 InAppChromeClient.java

路徑:cordova-plugin-inappbrowser\src\android\InAppChromeClient.java

增加成員變數

// added
private CordovaPlugin plugin;
public UploadHandler mUploadHandler;

增加建構函式

// added
public InAppChromeClient(CordovaWebView webView, CordovaPlugin plugin) {
    super();
    this.webView = webView;
    this.plugin = plugin;
}

增加成員函式與內部類別

// added all below

// Android 2.x
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
    openFileChooser(uploadMsg, "");
}

// Android 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
    openFileChooser(uploadMsg, "", "filesystem");
}

// Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
    mUploadHandler = new UploadHandler(new Controller());
    mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
}

// Android 4.4, 4.4.1, 4.4.2
// 這三個版本的 openFileChooser 不會被呼叫,
// 需要自行使用 JavaScript 介面或其他混合框架來處理。

// Android 5.0.1
@SuppressLint("NewApi")
public boolean onShowFileChooser(WebView webView,
                                 ValueCallback<Uri[]> filePathCallback,
                                 FileChooserParams fileChooserParams) {
    String acceptTypes[] = fileChooserParams.getAcceptTypes();
    String acceptType = "";
    for (int i = 0; i < acceptTypes.length; ++i) {
        if (acceptTypes[i] != null && acceptTypes[i].length() != 0) {
            acceptType += acceptTypes[i] + ";";
        }
    }
    if (acceptType.length() == 0) {
        acceptType = "*/*";
    }

    final ValueCallback<Uri[]> finalFilePathCallback = filePathCallback;
    ValueCallback<Uri> vc = new ValueCallback<Uri>() {
        @Override
        public void onReceiveValue(Uri value) {
            Uri[] result;
            if (value != null) {
                result = new Uri[]{value};
            } else {
                result = null;
            }
            finalFilePathCallback.onReceiveValue(result);
        }
    };

    openFileChooser(vc, acceptType, "filesystem");
    return true;
}

public class Controller {
    final static int FILE_SELECTED = 4;

    CordovaInterface getCordova() {
        return plugin.cordova;
    }
}

接著加入 UploadHandler 內部類別。這段程式碼取自 Android 4.4.3_r1 的 com/android/browser/UploadHandler.java(Apache License 2.0),核心邏輯如下:

class UploadHandler {

    private ValueCallback<Uri> mUploadMessage;
    private String mCameraFilePath;
    private boolean mHandled;
    private boolean mCaughtActivityNotFoundException;
    private Controller mController;

    public UploadHandler(Controller controller) {
        mController = controller;
    }

    String getFilePath() { return mCameraFilePath; }
    boolean handled() { return mHandled; }

    void onResult(int resultCode, Intent intent) {
        // 若找不到可處理的 Activity,會重試一次,因此跳過這次結果
        if (resultCode == Activity.RESULT_CANCELED && mCaughtActivityNotFoundException) {
            mCaughtActivityNotFoundException = false;
            return;
        }

        Uri result = intent == null || resultCode != Activity.RESULT_OK
                ? null : intent.getData();

        // 拍照時相機應用不會回傳資料,只回傳 RESULT_OK,
        // 因此需檢查預期檔案是否真的寫入磁碟
        if (result == null && intent == null && resultCode == Activity.RESULT_OK) {
            File cameraFile = new File(mCameraFilePath);
            if (cameraFile.exists()) {
                result = Uri.fromFile(cameraFile);
                // 通知媒體掃描器有新照片,讓它加入相簿
                mController.getCordova().getActivity().sendBroadcast(
                        new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
            }
        }

        mUploadMessage.onReceiveValue(result);
        mHandled = true;
        mCaughtActivityNotFoundException = false;
    }

    void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {

        final String imageMimeType = "image/*";
        final String videoMimeType = "video/*";
        final String audioMimeType = "audio/*";

        final String mediaSourceKey = "capture";
        final String mediaSourceValueCamera = "camera";
        final String mediaSourceValueFileSystem = "filesystem";
        final String mediaSourceValueCamcorder = "camcorder";
        final String mediaSourceValueMicrophone = "microphone";

        // 依規格,media source 可為 filesystem / camera / camcorder / microphone,
        // 預設值應為 filesystem
        String mediaSource = mediaSourceValueFileSystem;

        if (mUploadMessage != null) {
            // 已經有檔案選擇作業進行中
            return;
        }
        mUploadMessage = uploadMsg;

        // 解析 accept type
        String params[] = acceptType.split(";");
        String mimeType = params[0];

        if (capture.length() > 0) {
            mediaSource = capture;
        }

        if (capture.equals(mediaSourceValueFileSystem)) {
            // 為向後相容,若 capture 值為 filesystem,
            // 需進一步檢查 accept-type 中是否指定了不同的 capture 值
            for (String p : params) {
                String[] keyValue = p.split("=");
                if (keyValue.length == 2) {
                    if (mediaSourceKey.equals(keyValue[0])) {
                        mediaSource = keyValue[1];
                    }
                }
            }
        }

        // 確保不會殘留上一次的設定
        mCameraFilePath = null;

        if (mimeType.equals(imageMimeType)) {
            if (mediaSource.equals(mediaSourceValueCamera)) {
                // 指定 image/* 且要求使用相機,直接啟動相機
                startActivity(createCameraIntent());
                return;
            } else {
                // 只指定 image/*,capture=filesystem,或傳入無效的 capture 參數
                // 這種情況顯示傳統選擇器,同時提供相機與 image/* OPENABLE
                Intent chooser = createChooserIntent(createCameraIntent());
                chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(imageMimeType));
                startActivity(chooser);
                return;
            }
        } else if (mimeType.equals(videoMimeType)) {
            if (mediaSource.equals(mediaSourceValueCamcorder)) {
                startActivity(createCamcorderIntent());
                return;
            } else {
                Intent chooser = createChooserIntent(createCamcorderIntent());
                chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(videoMimeType));
                startActivity(chooser);
                return;
            }
        } else if (mimeType.equals(audioMimeType)) {
            if (mediaSource.equals(mediaSourceValueMicrophone)) {
                startActivity(createSoundRecorderIntent());
                return;
            } else {
                Intent chooser = createChooserIntent(createSoundRecorderIntent());
                chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(audioMimeType));
                startActivity(chooser);
                return;
            }
        }

        // 無需依 accept type 特殊處理時,觸發預設的檔案上傳選擇器
        startActivity(createDefaultOpenableIntent());
    }

    private void startActivity(Intent intent) {
        try {
            mController.getCordova().startActivityForResult(
                    plugin, intent, Controller.FILE_SELECTED);
        } catch (ActivityNotFoundException e) {
            // 沒有任何已安裝的 App 能處理這個 Intent,退回預設的檔案選擇控制項
            try {
                mCaughtActivityNotFoundException = true;
                mController.getCordova().startActivityForResult(
                        plugin, createDefaultOpenableIntent(), Controller.FILE_SELECTED);
            } catch (ActivityNotFoundException e2) {
                // 沒有任何 App 能回傳檔案,檔案上傳等於被停用
                Toast.makeText(mController.getCordova().getActivity(),
                        "File uploads are disabled.", Toast.LENGTH_LONG).show();
            }
        }
    }

    private Intent createDefaultOpenableIntent() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");

        Intent chooser = createChooserIntent(
                createCameraIntent(), createCamcorderIntent(), createSoundRecorderIntent());
        chooser.putExtra(Intent.EXTRA_INTENT, i);
        return chooser;
    }

    private Intent createChooserIntent(Intent... intents) {
        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
        chooser.putExtra(Intent.EXTRA_TITLE, "Choose file for upload");
        return chooser;
    }

    private Intent createOpenableIntent(String type) {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType(type);
        return i;
    }

    private Intent createCameraIntent() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        File externalDataDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(
                externalDataDir.getAbsolutePath() + File.separator + "browser-photos");
        cameraDataDir.mkdirs();

        mCameraFilePath = cameraDataDir.getAbsolutePath()
                + File.separator + System.currentTimeMillis() + ".jpg";

        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(mCameraFilePath)));
        return cameraIntent;
    }

    private Intent createCamcorderIntent() {
        return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    }

    private Intent createSoundRecorderIntent() {
        return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
    }
}

別忘了在檔案頂部加入必要的 import:

// added
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.webkit.ValueCallback;
import android.widget.Toast;

import java.io.File;

二、修改 InAppBrowser.java

路徑:cordova-plugin-inappbrowser\src\android\InAppBrowser.java

增加成員變數

// added
private InAppChromeClient chromeClient;

修改 showWebPage 方法

// WebView inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setId(Integer.valueOf(6));

// inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView)); 這一句註解掉
// 改為下面兩句
chromeClient = new InAppChromeClient(thatWebView, InAppBrowser.this);
inAppWebView.setWebChromeClient(chromeClient);

WebViewClient client = new InAppBrowserClient(thatWebView, edittext);

增加一個覆寫方法

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == InAppChromeClient.Controller.FILE_SELECTED) {
        // 從檔案選擇器選了一個檔案
        if (chromeClient != null && chromeClient.mUploadHandler != null) {
            chromeClient.mUploadHandler.onResult(resultCode, intent);
        }
    }
    super.onActivityResult(requestCode, resultCode, intent);
}

至於 iOS 版本,最新的 InAppBrowser 外掛 1.5.0 以上已經支援選擇檔案(1.5.0 之前的版本不行,有 bug)。

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