首先,在您的 Activity 中,创建静态变量 appContext,它保存应用程序上下文和以下函数:
//Initialize Application Context
private static Context appContext;
//Get Application Context (for use in external functions)
public static Context getContext() {
return appContext;
}
...并在onCreate(Bundle savedInstanceState)中设置变量:
//Set application context (for use in external functions)
appContext = this;
第二,在下面的单独文件中创建类:
文件:JavaScriptInterface.java
import android.content.Context;
import android.util.Log;
import android.webkit.JavascriptInterface;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
class JavaScriptInterface {
@JavascriptInterface
public String getFileContents(String assetName){
return readAssetsContent(MainActivity.getContext(), assetName);
}
//Read resources from "assets" folder in string
public String readAssetsContent(Context context, String name) {
BufferedReader in = null;
try {
StringBuilder buf = new StringBuilder();
InputStream is = context.getAssets().open(name);
in = new BufferedReader(new InputStreamReader(is));
String str;
boolean isFirst = true;
while ( (str = in.readLine()) != null ) {
if (isFirst)
isFirst = false;
else
buf.append('\n');
buf.append(str);
}
return buf.toString();
} catch (IOException e) {
Log.e("error", "Error opening asset " + name);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e("error", "Error closing asset " + name);
}
}
}
return null;
}
}
第三,别忘了初始化你的Webview来使用JavaScriptInterface:
//Set JS interface from JS/HTML code execution
mWebView.addJavascriptInterface(new JavaScriptInterface(), "android");
第四,调用android方法getFileContents()用JavaScript在你的HTML中加载本地资源:
<script type="text/javascript">
var s = document.createElement('script');
s.innerHTML = window.android.getFileContents('js/jquery.min.js');
document.head.appendChild(s);
//check if jquery is loaded now...
if(typeof $ != "undefined") {
$(document).ready(function() {
alert("jQuery is loaded!");
});
} else {
alert("jQuery is NOT loaded!");
}
</script>
注意:本示例中的本地资源位于/assets/js/ 子文件夹中。