Embed Cordova Webview in Android Native App

Embed Cordova Webview in Android Native App

Some articles have shown how to embed cordova webview to android native application, for example:

But unfortunately, the latest release of cordova android(4.0.0) make big changes on its code base. This changes, mostly kind of design pattern, have made the methods described in above article not work. What make me confused is that the cordova official website still use the old method in its example, which may waste others a lot of time.

This article will show how to cooperate with the new changes of cordova android to embed cordova webview in native android application.

Create Cordova Android Project

First of all, we need to create a cordova android project. It is better to use cordova-cli.

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
  • The first line of code create a new cordova project in folder test_cordova.
  • The second line of code add android platform for new created project.
  • The third and fourth line of code add two plugin for project(we will use these plugins in the example).
  • The last line of code build the new created project

Create Native Android Application

Google now suggest Android Studio for building android project, so we will use it here. Create a new project with blank activity using Android Studio. Here, the new created activity is called MainActivity.

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);
    }

}

Nothing special, we just define two methods: startCordovaActivity and startCordovaActivity. These two method is bind with two buttons, which we will see later.

  • startCordovaActivity will transfer to a new activity whose layout is a cordova webview created programmaticly.
  • startCordovaActivity will transfer to a new activity whose layout is defined using xml layout file and embedded with a cordova webview.

Lets have a look at MainActivity's layout xml file.

<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=".MainActivity">

    <Button
        android:text="Start Cordova Activity Without Layout"
        android:onClick="startCordovaActivity"
        android:layout_width="200dp"
        android:layout_height="100dp" />

    <Button
        android:text="Start Cordova Activity With Layout"
        android:onClick="startCordovaActivityWithLayout"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:layout_marginTop="50dp"/>

</LinearLayout>

Two buttons are defined, corresponding to the two methods above.

TestCordovaActivity

This activity is created to show how to create an activity with a cordova webview without the need of layout xml file.

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);
   }
}

Noted that we extends the CordovaActivity , which is from cordova library and implement most of stuff in order to cooperate with a cordova webview. We don't need to set the layout xml file using setContentView here, because the CordovaActivity create set it for us, a default cordova webview.

TestCordovaWithLayoutActivity

This activity has its layout xml file.

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();
    }

}

Again, we need to extend the CordovaActivity. But this time, we use setContentView to set layout xml explicitly. In order to make things work, we need to override two methods: makeWebView and createViews.

  • makeWebView is important, it use the R.id.cordovaWebView, which we define in layout xml file(we will see later).
  • createViews is not so important, we override it just because it will use setContentView by default. But we want to use our xml, so just comment it.

The 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>

We use a org.apache.cordova.engine.SystemWebView from cordova library. If you have read the articles listed above, you may remember that most of examples use org.apache.cordova.CordovaWebView. For example, below xml file is used in cordova official site.

<org.apache.cordova.CordovaWebView
     android:id="@+id/tutorialView"
     android:layout_width="match_parent"
     android:layout_height="match_parent" />

This still works until release 4.0.0 ... Now, the CordovaWebView class has changed to an interface. So we can not use like this anymore.

Copy Cordova Android Project to Native Android Application

Now comes the most excited part, we need to copy useful stuff of cordova project to the native android project.

cordova jar

The first and most important thing is that we need a cordova lib. You can download the latest cordova android 4.0.0 package, then create a jar file. Check the cordova offiicial website.

Navigate to the Android package's /framework directory and run ant jar. It creates the Cordova .jar file, formed as /framework/cordova-x.x.x.jar.

After creating the jar file, we need to import it into our Android Studio project. Copy the jar file to libs folder and add the follow line in build.gradle.

compile files('libs/cordova-4.0.0.jar')

Try to access the class in cordova lib after you finish to see if everything is ok.

www folder

Copy the www folder in cordova project to the android project. Note that the folder structure on the right is for Android Studio.

platforms/android/assets/www -> src/main/assets/www

plugins

We have added plugins for cordova project above, so we need to add them to our android project.

We need to use the cordova plugins in folder platforms/android/src/, instead of plugins/, because when you run cordova build, cordova will copy the plugins in folder plugins/ to folder platforms/android/src/ and perform some magic under the table(the config.xml indeed).

platforms/android/src/plugin_folder -> src/main/java/ 

config.xml

Cordova use the config.xml for its configuration, likes plugins declarations. Note that do NOT use the file in root path of cordova project, use that in platforms folder instead.

platforms/android/res/xml/config.xml -> src/main/res/xml/

Bonus

You can checkout the final project in github.

Current rating: 4.6

Comments

ADDRESS

  • Email: jimmykobe1171@126.com
  • Website: www.catharinegeek.com