Home » Android » Start android activity from cordova plugin

Start android activity from cordova plugin

Posted by: admin June 15, 2020 Leave a comment

Questions:

I know this may is a duplicate question, i have tried all answers from stack, but non has a complete answer.

Most answers just give how to start an activity but no hints how to configure activity in Android Manifest file and where to save activity layout and manifest file.

Can anyone please give a complete code structure to start an activity from cordova plugin.

How to&Answers:

Here is the complete steps to start an activity from a cordova plugin

1. Install Plugman to create plugin

npm install -g plugman

2. Create cordova plugin using plugman

plugman create --name PluginName --plugin_id com.example.sample.plugin --plugin_version 0.0.1

N.B : plugin id never start with Uppercase

Now PluginName directory will be created. Plugin structure will be

PluginName/

|- plugin.xml

|- src/

|- www/PluginName.js

3. Add android platform to plugin

plugman platform add --platform_name android

Now plugin structure will be

PluginName/

|- plugin.xml

|- src/android/PluginName.java

|- www/PluginName.js

4. Now create a java file named NewActivity.java in src/android directory

This activity will be shown using our plugin.

NewActivity.java

package com.example.sample.plugin;

import android.app.Activity;
import android.os.Bundle;

public class NewActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String package_name = getApplication().getPackageName();
        setContentView(getApplication().getResources().getIdentifier("activity_new", "layout", package_name));
    }
}

5. Now create layout file activity_new.xml in src/android directory

This is the layout file for our new activity

activity_new.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context="com.example.sample.plugin.NewActivity">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="New Activity"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="77dp" />
</RelativeLayout>

6. Now edit PluginName.java in src/android

Now we need to handle the request and start our new activity.

PluginName.java

package com.example.sample.plugin;

import android.content.Context;
import android.content.Intent;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaInterface;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PluginName extends CordovaPlugin {

    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        Context context = cordova.getActivity().getApplicationContext();
        if(action.equals("new_activity")) {
            this.openNewActivity(context);
            return true;
        }
        return false;
    }

    private void openNewActivity(Context context) {
        Intent intent = new Intent(context, NewActivity.class);
        this.cordova.getActivity().startActivity(intent);
    }
}

7. Now edit PluginName.js in www directory

Now create new method to call to start our new activity.

var exec = require('cordova/exec');

function plugin() {

}

plugin.prototype.new_activity = function() {
    exec(function(res){}, function(err){}, "PluginName", "new_activity", []);
}

module.exports = new plugin();

8. Now edit plugin.xml

Now we need to specify our files to plugin and make necessary changes in cordova AndroidManifest.xml file

plugin.xml

<?xml version='1.0' encoding='utf-8'?>
<plugin id="com.example.sample.plugin" version="0.0.1" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
    <name>PluginName</name>
    <js-module name="PluginName" src="www/PluginName.js">
        <clobbers target="PluginName" />
    </js-module>
    <platform name="android">
        <config-file parent="/*" target="res/xml/config.xml">
            <feature name="PluginName">
                <param name="android-package" value="com.example.sample.plugin.PluginName" />
            </feature>
        </config-file>
        <config-file target="AndroidManifest.xml" parent="/manifest/application">
            <activity android:label="New Activity" android:name="com.example.sample.plugin.NewActivity"></activity>
        </config-file>
        <config-file parent="/*" target="AndroidManifest.xml"></config-file>
        <source-file src="src/android/PluginName.java" target-dir="src/com/example/sample/plugin" />
        <source-file src="src/android/NewActivity.java" target-dir="src/com/example/sample/plugin" />
        <source-file src="src/android/activity_new.xml" target-dir="res/layout"/>
    </platform>
</plugin>

9. Now create a cordova project

cordova create CordovaProject com.example.sample.cordovaproject "Cordova App"

10. Add android platform to your cordova project

cordova platform add android

11. Now add your plugin

cordova plugin add your-plugin-local-path
eg: cordova plugin add "C:\PluginName"

12. Add a button to index.html in www directory

index.html

<!DOCTYPE html>
<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">
        <title>Hello World</title>
    </head>
    <body>
        <div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
            </div>
            <button id = "new_activity">New Activity</button>
        </div>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>

13. Add click handler for new button in index.js in www/js directory

When our button is clicked, we will call our plugin method to start our new activity

index.js

var app = {
    initialize: function() {
        this.bindEvents();
    },
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
        document.getElementById("new_activity").addEventListener("click", new_activity);
    }
};

app.initialize();

function new_activity() {
    PluginName.new_activity();
}

14. Now run this app in android phone

cordova run android

If all these steps are success and when we click New Activity button, our new activity will show up.

Answer:

Hi you can use this plugin

cordova plugin add sevensky-cordova-plugin-intent

Usage :

    document.getElementById("btn_device_name").addEventListener("click", test);

    function test() {
        var obj = new Object();
        obj.name = "Ahmad"; //bundle string extra 1 string
        obj.family = "Aghazadeh"; //bundle string extra 2
        intentPlugin.startActivity("com.sevensky.test", "TestActivity", JSON.stringify(obj));
    }