final String jsName ="JsCallbackToApp";webView.addJsCallback(jsName, new JsCallback(){@Overridepublic String onCallback(String msg){// 增加自定義處理return"jsResult";}});
在頁面內通過 JavaScript 代碼調用注入對象:
function callToApp(){if(window.JsCallbackToApp && window.JsCallbackToApp.call){var result = JsCallbackToApp.call("message from web");}}
在應用內調用頁面內的 JavaScript 方法:
webView.executeJs("javascript:callFuncInWeb()", new AsyncCallback<String>(){@Overridepublic voidonReceive(String msg){// 在此確認返回結果}});
public class ExampleDataAbility extends Ability {private static final String PLACEHOLDER_RAW_FILE ="/rawfile/";private static final String PLACEHOLDER_LOCAL_FILE ="/local/";private static final String ENTRY_PATH_PREFIX ="entry/resources";@Overridepublic RawFileDescriptor openRawFile(Uri uri, String mode) throws FileNotFoundException {final int splitChar ='/';if(uri == null){throw new FileNotFoundException("Invalid Uri");}// path will be like /com.example.dataability/rawfile/example.htmlString path = uri.getEncodedPath();final int splitIndex = path.indexOf(splitChar,1);if(splitIndex <0){throw new FileNotFoundException("Invalid Uri "+ uri);}String targetPath = path.substring(splitIndex);if(targetPath.startsWith(PLACEHOLDER_RAW_FILE)){// 根據自定義規則訪問資源文件try {returngetResourceManager().getRawFileEntry(ENTRY_PATH_PREFIX + targetPath).openRawFileDescriptor();}catch(IOException e){throw new FileNotFoundException("Not found support raw file at "+ uri);}}elseif(targetPath.startsWith(PLACEHOLDER_LOCAL_FILE)){// 根據自定義規則訪問本地文件File file = new File(getContext().getFilesDir(), targetPath.replace(PLACEHOLDER_LOCAL_FILE,""));if(!file.exists()){throw new FileNotFoundException("Not found support local file at "+ uri);}returngetRawFileDescriptor(file, uri);}else{throw new FileNotFoundException("Not found support file at "+ uri);}}private RawFileDescriptor getRawFileDescriptor(File file, Uri uri) throws FileNotFoundException {try {final FileDescriptor fileDescriptor = new FileInputStream(file).getFD();return new RawFileDescriptor(){@Overridepublic FileDescriptor getFileDescriptor(){return fileDescriptor;}@Overridepublic longgetFileSize(){return-1;}@Overridepublic longgetStartPosition(){return0;}@Overridepublic voidclose() throws IOException {}};}catch(IOException e){throw new FileNotFoundException("Not found support local file at "+ uri);}}}
在 config.json 中注冊 Data Ability,以及在 resources/base/profile 目錄新增 path.xml: