This blog post was written under the Pusher Guest Writer program.

Writing a native Android app is not possible for everyone of us. As a web developer, I would have to learn the the Android SDK from ground up, which is too intimidating and a lot of work. Rather, what if I could make a web app and convert it into an Android app? – Sounds good enough to be true?

One of the options would be to embed the web view of your hosted whole web app directly into Android – but it’s not productive! Sometimes, we only need a very limited set of features in our app, or the UI needs to be a bit different to better suit mobile usability and many other such limitations. Embedding a web app in a web view doesn’t always work.

Having a similar use-case in one of my recent projects, I came across Cordova. I wrote my Android app in JavaScript and converted it into an Android app in matter of minutes with a single command – It’s that simple!

Today, we will create a basic ToDo app for the Android platform.

Installation

Cordova command-line runs on Node and is available to install through npm. We can install Cordova with the following command:

    sudo npm install -g cordova

This will install all the necessary JavaScript libraries through npm.

Next, we need to make sure that the Android SDK is installed on our workstation. The SDK should be installed so as to make Cordova able to convert our JavaScript app into an Android app.

We can install download the latest SDK from this link.

After the SDK installation is completed, we need to download a set of SDK tools. You can do so in the following steps (or see a detailed set of instructions on this link):

  1. Open Android Studio
  2. Go to Preferences
  3. Go to Appearance & Behavior → System Settings → Android SDK
  4. You can see a list of tools as options to be installed
  5. Make sure the options shown in the image below are checked
  6. The download may take quite a bit of time depending on your network connectivity

Create a New Cordova App

Once we complete the installation, we need to first create a new app with Cordova. We can do so with the following command:

    cordova create todo-mobile-app-cordova-vue

Next, cd into the project directory, add a platform, for which you need to create an app. Cordova currently supports the following platforms:
1. Android
2. IOS
3. Blackberry
4. OSX
5. WebOS
6. Windows
7. Browser

We are making an Android app, hence, we will add the android platform:

    cd todo-mobile-app-cordova-vue 

    cordova platform add android

ToDo App

We will use Vue to create a ToDo SPA. The intent of this article is to guide on converting JavaScript app into an Android app, hence, we will focus on that and not concentrate on how to build a JavaScript app.

Let us set up our default routes, components and the bootstrap in the resources/assets/js/app.js file:


/** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue. */ require('./bootstrap'); window.Vue = require('vue'); import Vue from 'vue' import VueRouter from 'vue-router' // 1. Define route components. // These can be imported from other files let Todo = require('./components/Todo.vue'); // 2. Define some routes // Each route should map to a component. The "component" can // either be an actual component constructor created via // Vue.extend(), or just a component options object. const routes = [ { path: '/tasks', component: Todo } ] // 3. Create the router instance and pass the `routes` option // You can pass in additional options here, but let's // keep it simple for now. const router = new VueRouter({ routes }) Vue.use(VueRouter); Vue.component('navigation', require('./components/Navigation.vue')); Vue.component('create-task', require('./components/CreateTask.vue')); // 4. Create and mount the root instance. // Make sure to inject the router with the router option to make the // whole app router-aware. window.onload = function () { const app = new Vue({ router }).$mount('#app'); } router.push('/tasks');

In the above example, we have set up the application, necessary dependencies and the routes. At the end of the file, we are specifying the route that the application should be redirected to by default.

Next, let’s look into the ToDo Vue component:

    <template>
        <div class="container">
            <div class="row">
                <div class="col-sm-12">
                    <create-task @created="pushTask"></create-task>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-12" v-for="task in tasks">
                    <div class="panel panel-default">
                        <div class="panel-body">
                            <div class="pull-left">{{ task.title }}</div>
                            <div class="pull-right">
                                <button class="btn btn-danger btn-sm" @click.prevent="deleteTask(task)">
                                    Delete
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>
    <script>
        export default {
            data() {
                return {
                    tasks: []
                }
            },

            methods: {
                pushTask(task) {
                    this.tasks.unshift(task);
                },

                deleteTask(task) {
                    this.tasks.splice(this.tasks.indexOf(task), 1);
                }
            }
        }
    </script>

We reference a create-task component as a child in the above component. The above component displays the tasks and deletes them. The create-task component will take care of creating the task:

    <template>
        <div class="panel panel-default">
            <div class="panel-heading">Create Task</div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="form-group">
                            <input type="text" class="form-control" v-model='title' @keyup.enter="createTask">
                        </div>
                    </div>
                </div>

                </div>
            </div>
        </div>
    </template>

    <script>
        export default {
            data() {
                return {
                    title: ''
                }
            },

            methods: {
                createTask() {
                    let task = {
                        title: this.title
                    };

                    this.$emit('created', task);
                    this.title = '';
                }
            }
        }
    </script>

You can run the app on browser with following commands:

    cordova platform add browser

    cordova run browser

The below gif demonstrates the working app on the browser:

Converting to Android

Connect your mobile device to laptop or PC. Make sure that the debugging mode is switched on. To run the Android app on your mobile, you can execute the following command:

    cordova run android

It will build and install the apk on your mobile. The app will open on your device and you can play with it.

Alternatively, if you want to run the app on emulator, you can do so with the following command:

    cordova run android --emulator

Configuration

Your app has a config.xml file which serves as an configuration for variety of options:

The name of the app:

    <name>ToDo - Pusher</name>

The description:

    <description>
        A ToDo app for Pusher using Cordova and Vue
    </description>

Author information

    <author email="viraj@virajkhatavkar.com" href="https://virajkhatavkar.com">
        Apache Cordova Team
    </author>

Icon for the app:

    <icon src="res/ios/icon.png" platform="ios" width="57" height="57" density="mdpi" />

If you don’t specify a icon, the default icon from Cordova will be used.

You can go over the other configuration options as listed on the link here.

Plugins

Most of the times, we need to interact with native features of our device to be embedded into our app. Cordova gives a very fluent and user-friendly API to achieve the same. Cordova has many plugins available to take care of normal use-cases:
1. Battery Status
2. Camera
3. Console
4. Contacts
5. Device
6. Device Orientation
7. File Transfer
8. GeoLocation
9. Network Information

To add a plugin to your application, you can do so by using a simple command:

    cordova plugin add plugin-name

The above listed are only some of the plugins available. You can see the whole list of available plugins and their working on the official documentation

Conclusion

In this article, we have covered how to create an Android application using Vue and Cordova. We have covered the configuration options necessary to get started, and the example above should help you fill in the gaps and give an overview of some of the other configuration options available to you.

The code is hosted on public Github repository. You can download it for educational purposes. How do you intend to use Cordova? Can you think of any advanced use cases? What are they? Let us know in the comments!