Android实现在当前进程打开网页可以将Cordova中的WebView嵌入Android项目中,实现简单,不需要自己实现,所以掌握如何嵌入WebView对项目快速开发很有帮助 官方也有这方面的教程操作,但最新版本的cordova android(4.0.0)对其代码库做了大的改动。这种变化,大多是一种设计模式,使得上面描述的方法不能正常工作。 本文将展示如何与cordova Android的新变化合作,嵌入cordova webview在本机Android应用程序。 创建Cordova安卓项目 cordova create test_cordova com.example.hello HelloWorld cordova platform add android cordova plugin add nl.x-services.plugins.toast cordova plugin add org.apache.cordova.device cordova build 上面第三行和第四行是将其他的第三方插件也嵌入安卓原生工程使用 创建Android Native项目 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startCordovaActivity(View view) { Intent intent = new Intent(this, TestCordovaActivity.class); startActivity(intent); } public void startCordovaActivityWithLayout(View view) { Intent intent = new Intent(this, TestCordovaWithLayoutActivity.class); startActivity(intent); } } startCordovaActivity 将转移到一个新活动,其布局是以程序方式创建的cordova webview。 startCordovaActivity 将转移到一个新的活动,其布局使用xml布局文件定义并嵌入cordova webview。 TestCordovaActivity public class TestCordovaActivity extends CordovaActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.init(); // Load your application launchUrl = "file:///android_asset/www/index.html"; // launchUrl = "file:///android_asset/www/index2.html"; loadUrl(launchUrl); } } 不需要xml布局,加载的是index.html网页 TestCordovaWithLayoutActivity public class TestCordovaWithLayoutActivity extends CordovaActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_cordova_with_layout); super.init(); // Load your application // launchUrl = "file:///android_asset/www/index.html" launchUrl = "file:///android_asset/www/index2.html"; loadUrl(launchUrl); } @Override protected CordovaWebView makeWebView() { SystemWebView webView = (SystemWebView)findViewById(R.id.cordovaWebView); return new CordovaWebViewImpl(new SystemWebViewEngine(webView)); } @Override protected void createViews() { //Why are we setting a constant as the ID? This should be investigated // appView.getView().setId(100); // appView.getView().setLayoutParams(new FrameLayout.LayoutParams( // ViewGroup.LayoutParams.MATCH_PARENT, // ViewGroup.LayoutParams.MATCH_PARENT)); // // setContentView(appView.getView()); if (preferences.contains("BackgroundColor")) { int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK); // Background of activity: appView.getView().setBackgroundColor(backgroundColor); } appView.getView().requestFocusFromTouch(); } } public class Main2Activity extends Activity implements CordovaInterface{ private SystemWebView cordova_webview; private String TAG = "CORDOVA_ACTIVITY"; private final ExecutorService threadPool = Executors.newCachedThreadPool(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); cordova_webview = (SystemWebView) findViewById(R.id.cordova_web_view); //从4.x开始CordovaWebView不再是View的子类,用SystemWebView代替 //下面这行代码非常关键,如果没有这行,的、diveceready就没有执行,显灰色状态 cordova_webview.getSettings().setJavaScriptEnabled(true); // Config.init(this); String url = "file:///android_asset/www/index.html"; cordova_webview.loadUrl(url); } @Override public void startActivityForResult(CordovaPlugin cordovaPlugin, Intent intent, int i) { Log.d(TAG, "setActivityResultCallback is unimplemented"); } @Override public void setActivityResultCallback(CordovaPlugin cordovaPlugin) { Log.d(TAG, "startActivityForResult is unimplemented"); } @Override public Activity getActivity() { return this; } @Override public Object onMessage(String s, Object o) { Log.d(TAG, s); if (s.equalsIgnoreCase("exit")) { super.finish(); } return null; } @Override public ExecutorService getThreadPool() { return threadPool; } } 使用setContentView显式设置布局xml。需要重写两个方法: makeWebView: 它使用R.id.cordovaWebView,在layout xml文件中定义 createViews : 我们重写它只是因为它将默认使用setContentView。但是我们想使用我们的xml布局,所以需要它。 activity_test_cordova_with_layout.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.jimmy.embeddedcordovawebviewdemo.TestCordovaWithLayoutActivity"> <TextView android:layout_width="match_parent" android:layout_height="100dp" android:background="#FF0000" android:textColor="#FFFFFF" android:gravity="center" android:text="This is native text view" /> <org.apache.cordova.engine.SystemWebView android:id="@+id/cordovaWebView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> 为了向后兼容,我们使用cordova库中的org.apache.cordova.engine.SystemWebView,直到4.0.0之前也是可以使用org.apache.cordova.CordovaWebView 将Cordova Android项目复制到本机Android应用程序 拷贝jar包 去Apache官方网站下载最新的cordova Android Packet,然后创建jar包。官方网站 下载好官方压缩文件cordova-android-xxx.zip,解压缩,通过ant工具导航到 /framework目录下,执行ant jar命令,如果提示 build fali, you need to create the file'local.properties' by running 'android update project -p .'命令,在cmd窗口执行如上命令之后再次执行ant jar 将会在当前目录生成cordova-4.0.0.jar 拷贝jar包到项目中,在build.gradle中添加依赖 compile files('libs/cordova-4.0.0.jar') 拷贝www目录 目录结构如下 platforms/android/assets/www -> src/main/assets/www 拷贝插件 注意:拷贝platforms/android/src/目录结构下的所有文件,而不是plugins/下的所有文件。因为在运行cordova build命令时,cordova将复制plugins/文件夹下的插件到目录platforms/android/src/下,并执行一些操作。 拷贝config.xml 注意:不要拷贝更目录下的config.xml,要拷贝的是platforms下的config.xml 目录结构如下 platforms/android/res/xml/config.xml -> src/main/res/xml/ 整个工程的目录结构如下图所示: 若工程点击事件报错: 06-11 17:47:24.708 12895-12895/com.intbird.soft.cordoca I/chromium﹕ [INFO:CONSOLE(41)] “Refused to execute inline event handler because it violates the following Content Security Policy directive: “default-src ‘self’ data: gap: https://ssl.gstatic.com ‘unsafe-eval’”. Note that ‘script-src’ was not explicitly set, so ‘default-src’ is used as a fallback. “, source: file:///android_asset/www/index.html (41) 直接注释掉 index.html meta 第一行,重新运行 <html> <head> <!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *"> --> <meta name="format-detection" content="telephone=no"> <meta name="msapplication-tap-highlight" content="no"> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width"> <link rel="stylesheet" type="text/css" href="css/index.css"> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8" src="js/index.js"></script> <title>Hello World</title> </head> <body οnlοad="onPageLoad()"> <input type="button" οnclick="btnStartActivity('web')" value="使用webView" class="button"/><br/> <input type="button" οnclick="btnStartActivity('camera')" value="使用相机" class="button"/><br/> <input type="button" οnclick="btnStartActivity('')" value="未处理" class="button"/> </body> </html> 参考文献: http://cordova.apache.org/docs/en/5.0.0/guide_platforms_android_webview.md.html http://richardgilmour.co.uk/2013/03/03/embedding-a-cordova-webview-in-a-native-android-app/ https://github.com/Adobe-Marketing-Cloud-Apps/app-sample-android-phonegap/wiki/Embed-Webview-in-Android-Fragment 作者:samychen 链接:https://www.jianshu.com/p/6be7ba97ad8a 来源:简书 简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。