Embedding Cordova WebView on Android
Beginning in Cordova 1.9, with the assistance of the CordovaActivity
, you can use Cordova as a component in a larger native Android application. This component is known in Android
as the CordovaWebView
. New Cordova-based applications from 1.9 onwards will be using the CordovaWebView
as its main view, whether the legacy DroidGap
approach is
used or not.
The prerequisites are the same as the prerequisites for Android application development. It is assumed that you are familiar with Android development. If not, please look at the Getting Started guide to developing a Cordova Application and start there before continuing with this approach. This is not the main approach used to author Android Cordova applications. Thus the instructions are currently manual. In the future, we may try to further automate project generation via this method.
Prerequisites
- Cordova 1.9 or greater
- Android SDK updated with 15
Guide to using CordovaWebView in an Android Project
- Use
bin/create
to fetch the commons-codec-1.6.jar -
cd
into/framework
and runant jar
to build the cordova jar (it will create the .jar file in the formcordova-x.x.x.jar
in the/framework
folder) - Copy the cordova jar into your Android project's
/libs
directory -
Edit your application's
main.xml
file (under/res/xml
) to look similar the following. Thelayout_height
,layout_width
andid
can be modified to suit your application<org.apache.cordova.CordovaWebView android:id="@+id/tutorialView" android:layout_width="match_parent" android:layout_height="match_parent" />
-
Modify your activity so that it implements the
CordovaInterface
. It is recommended that you implement the methods that are included. You may wish to copy the methods from/framework/src/org/apache/cordova/DroidGap.java
, or you may wish to implement your own methods. Below is a fragment of code from a basic application that uses the interface (note how the view id referenced matches theid
attribute specified in the above XML fragment from step 4):public class CordovaViewTestActivity extends Activity implements CordovaInterface { CordovaWebView cwv; /* Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); cwv = (CordovaWebView) findViewById(R.id.tutorialView); cwv.loadUrl("file:///android_asset/www/index.html"); }
Copy your application's HTML and JavaScript used to the
/assets/www
directory of your Android project- Copy
cordova.xml
andplugins.xml
from/framework/res/xml
to the/res/xml
folder in your project