Tutorial geolocation cordova plugin and google map API V3 for iOS and android

It is very easy to detect device’s current location (latitude and longitude) with Cordova org.apache.cordova.geolocation plugin. This plugins detect current location based on GPS, IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. But there is no guarantee that location will be detected precisely enough.

Create project com.revivalx.cordova.geolocation and install geolocation cordova plugin into your cordova project.

cordova plugin add org.apache.cordova.geolocation

Open up your config.xml file and replace with this code.

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.revivalx.cordova.geolocation" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>GeolocationCordova</name>
    <description>
        This source code provides example about the device's location, such as latitude and longitude.
    </description>
    <author email="nurdinnorazanservices@gmail.com" href="http://revivalx.com">
        Mohammad Nurdin bin Norazan
    </author>
    <content src="index.html" />
    <access origin="*" />
</widget>

After that you need to add iOS and android platform into your cordova project using this command. If you using windows, you can’t create iOS platform because you need iOS SDK installed in your machine.

cordova platform add iOS
cordova platform add android
cordova platform add

cordova platform add

Open up index.html file in www folder. Replace with this code.

<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />
        <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <title>Geolocation Cordova Plugin</title>
    </head>
    <body>
        
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>

Then open up index.js file in js folder add replace all with this code

var onSuccess = function(position) {
    alert('Latitude: '          + position.coords.latitude          + '\n' +
          'Longitude: '         + position.coords.longitude         + '\n' +
          'Altitude: '          + position.coords.altitude          + '\n' +
          'Accuracy: '          + position.coords.accuracy          + '\n' +
          'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
          'Heading: '           + position.coords.heading           + '\n' +
          'Speed: '             + position.coords.speed             + '\n' +
          'Timestamp: '         + position.timestamp                + '\n');
};

function onError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}

navigator.geolocation.getCurrentPosition(onSuccess, onError);

Build and run the app. I hope you enjoy this article. You may download the source code here, https://github.com/datomnurdin/com.revivalx.cordova.geolocation .

AngularJs Ionic Mobile App Development Tutorial – Marketing App – Part 1

In this tutorial you will develop a marketing app for iOS and android with these features

  • Login (Facebook Login)
  • Edit profile
  • Create and view all campaign details
  • View reports

What you will be learn from this tutorial are

  • Setup development environment using certain IDE for iOS and android.
  • Preview your iOS and android hybrid app on actual device (smart phone).
  • Develop iOS and android hybrid app using client side language.
  • Create multi page application for iOS and android hybrid app.
  • Connect iOS and android hybrid app with server side language.

Download the required software packages.

Download and install Eclipse Juno SR2 and Xcode 6 (if you’re using Mac for mobile development).

Eclipse Juno SR2 – http://www.eclipse.org/downloads/packages/release/juno/sr2
Xcode 6 – https://developer.apple.com/xcode/downloads/

Setup ADT and Android SDK into your eclipse.

Then you need to setup cordova using NPM (node package manager).

ADT and Android SDK Setup

Don’t forget to install or update your machine with latest JDK 7. Download at http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html.

After you download, make sure you set the correct java path. If not, you can’t start your eclipse. You can download eclipse Juno http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/junosr2.

Then install it. After you install the tool that I tell you, make sure you install ADT (android development tools).

Go to Help and choose Install New Software.

eclipse - Install New Software

eclipse – Install New Software

Click Add button then popup box will appear. Enter ‘ADT’ in name textfield and ‘https://dl-ssl.google.com/android/eclipse/’ in location textfield.

eclipse - Install ADT

eclipse – Install ADT

Click Select All button and click Next.

eclipse - Install ADT

eclipse – Install ADT

Click Next.

eclipse - Install ADT

eclipse – Install ADT

Select I accept the terms of the license of agreement. Click Finish.

eclipse - Install ADT

eclipse – Install ADT

After finished setup ADT in your eclipse, download android SDK (http://developer.android.com/sdk/index.html#Other) and update latest android version or depends on your device for testing. After you install the android SDK, open android SDK , /android-sdk/tools. For this tutorial we will using latest android SDK, Android 5.0 aka Lolipop. Open your terminal/cmd, type android command and enter.

android terminal

android terminal

Select Android 5.0 and click Install 12 packages.

Android SDK Manager

Android SDK Manager

Select all packages, choose Accept License and click Install.

Android SDK Manager

Android SDK Manager

After that, install node.js (http://nodejs.org/) to use npm for package manager. If you not install node.js, you should not be able to invoke node or npm on your command line to install cordova apache. Then install cordova apache using terminal for Mac, command prompt for Windows.

Type this command to install cordova apache.

For Mac

sudo npm install -g cordova ionic

For Windows. If you can’t install, make sure you run the command prompt as administrator.

npm install -g cordova ionic
sudo npm install -g cordova ionic

sudo npm install -g cordova ionic

sudo npm install -g cordova ionic

sudo npm install -g cordova ionic

After you finish install the cordova apache. You can start create your project using cordova command. Open your terminal/command prompt, type these command. You can ignore sudo if you using Windows.

ionic start com.revivalx.cordova.marketing
ionic create project

ionic create project

Open config.xml inside cordova project that you already created just now. Change id and name. Others are optional.

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.revivalx.cordova.marketing" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>ToDo</name>
    <description>
        Marketing App.
    </description>
    <author email="mohammadnrdn@gmail.com" href="http://revivalx.com">
        Mohammad Nurdin bin Norazan
    </author>
    <content src="index.html" />
    <access origin="*" />
</widget>

Go back to terminal and add platform for android/iOS. Type these command to add both platforms.

ionic platform add android
ionic platform add android

ionic platform add android

ionic platform add ios
ionic platform add ios

ionic platform add ios

Note, if you got some error message during add andorid platform, you can refer to this link

Common errors during developing hybrid android app– http://blog.revivalx.com/2014/11/02/common-errors-during-developing-android-hybrid-app/

Android part.

Go to eclipse and import android project. Click File and choose Import.

eclipse - import project

eclipse – import project

Choose Existing Android Code into Workspace and click Next.

eclipse - existing android code into workspace

eclipse – existing android code into workspace

Browse your android project and select all. Click Finish.

eclipse – import projects

eclipse – import projects

Make sure you already connect your mobile device (android phone) and enable USB debugging.

Enable USB debugging: http://www.phonearena.com/news/How-to-enable-USB-debugging-on-Android_id53909

Right click android project > Run As > Android Application.

Run As Android Application

Run As Android Application

Select your phone and click Ok.

Android Device Chooser

Android Device Chooser

If successful, your app shown like this.

cordova app preview on android

ionic app preview on android

iOS part.

Open your cordova project for iOS. Go to../com.revivalx.ionic.marketing/platforms/ios/com.revivalx.ionic.marketing.xcodeproj . Select iPhone6 simulator and click Play button.

xcode6

xcode6

If successful, your app shown like this.

ionic app preview on iOS

ionic app preview on iOS

I think thats all for

  • Setup development environment using certain IDE for iOS and android.
  • Preview your iOS and android hybrid app using emulator and actual device (smart phone).

Next tutorial we will develop iOS and android hybrid app using client side language.

Cordova/PhoneGap MissedCall Plugin for android

This MissedCall phonegap plugin can track for those missed call you easily. Internally, the plugin uses both the Native and the JavaScript implementations, it has sometimes been hard for the plugin to keep up with new versions of these SDKs, as well as new versions of Cordova.

The approach used in MissedCall is simple and lightweight, but it is definitely not perfect.

function missedCall(){
	cordova.exec(missedCallSuccess, missedCallFailure, "MissedCallPlugin", "missedCall", []);
}

Source Code

MissedCall plugin is available in this repository on GitHub.

Getting Started

To run the sample on your own app:

  • Install this phonegap plugin into your project.
  • Trigger missedCall() function.

Tutorial: How To Write a PhoneGap plugin for Android

In this tutorial you will write a custom phonegap plugin for your cordova project.

  • Declaring the plug-in.
  • Implementing the phonegap plugin by using Java code.
  • Calling the phonegap plugin from JavaScript.

Overview

  • With Apache Cordova, developers can create an Apache Cordova plugin, which means that they create custom native code blocks, and call these code blocks in their applications by using JavaScript.
  • In this tutorial, you learn how to create a simple Android Apache Cordova plugin and how to use it in your code.
  • Unlike with Cordova-based applications where a developer is required to check for the deviceready event before using the Cordova API set, in a cordova application this check is done internally.

Creating and using an Android Apache Cordova plugin consists of three steps:

  • Declare your plug-in in the plugin.xml file.
  • Create a plug-in class, which will run natively in Android.
  • Use the cordova.exec() API method in the JavaScript code.

The plugin performs the required action, and calls a JavaScript callback method that is specified during the cordova.exec() invocation.

cordova exec

cordova exec

Declaring your plugin

Create a new folder call HelloWorld. Then create a few of folders and files similar to image below.

cordova plugin structure

cordova plugin structure

You must first declare the new plugin in the project, so that Cordova knows about it. The creation process of the plugin is covered in the following slides.

  • Add your plug-in definition to the plugin.xml file, which is located in the www folder in the HelloWorld folder.
  • Add your custom plugin.
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
            id="com.revivalx.HelloWorldPlugin" version="0.0.1">
        <name>Hello World Plugin</name>
        <description>Cordova Hello World Plugin</description>
        <license>Apache 2.0</license>
        <keywords>cordova</keywords>
        <js-module src="www/HelloWorld.js" name="HelloWorld">
            <clobbers target="HelloWorld" />
        </js-module>
        <platform name="android">
        <config-file target="res/xml/config.xml" parent="/*">
            <feature name="HelloWorldPlugin" >
                <param name="android-package" value="com.revivalx.HelloWorldPlugin"/>
            </feature>
        </config-file>
        <source-file src="src/android/HelloWorldPlugin.java" target-dir="src/com/revivalx/HelloWorldPlugin" />
    </platform>
    </plugin>

Open HelloWorldPlugin.java, extend the org.apache.cordova.CordovaPlugin class, add required imports and implement an execute method.

package com.revivalx.HelloWorldPlugin;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

public class HelloWorldPlugin extends CordovaPlugin {

	@Override
	public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
			throws JSONException {
		if (action.equals("sayHello")){
			try {
				final String responseText = "Hello " + args.getString(0);
				cordova.getThreadPool().execute(new Runnable() {
					public void run() {
						callbackContext.success(responseText); // Thread-safe.
					}
				});
			} catch (JSONException e){
				callbackContext.error("Failed to parse parameters");
			}
			return true;
	    }
		return false;
	}
}

Now you are ready to call the plug-in from JavaScript

function greetMe(){
	var name = "Hi!!";
	cordova.exec(sayHelloSuccess, sayHelloFailure, "HelloWorldPlugin", "sayHello", [name]);
}

function sayHelloSuccess(data){
	alert("OK: " + data);
}

function sayHelloFailure(data){
	alert("FAIL: " + data);
}

greetMe();

Go back to the command line and within your project root folder, run the following command:

cordova plugin add <your_local_phonegap_plugin_repository>
cordova run android

Reference: IBM Worklight

Implement Push Notifications for android and iOS (phonegap) – part 3

This tutorial is the third part of a three-part series on how to do push notifications integration with your app for android and iOS.

Install the PushPlugin phonegap plugin from its github location via the Cordova CLI:

cordova plugin add https://github.com/phonegap-build/PushPlugin
PushPlugin Phonegap Plugin

PushPlugin Phonegap Plugin

Add iOS and android platform using cordova CLI.

cordova platform add ios
cordova platform add android
cordova platform add

cordova platform add

Locate the PushNotification.js file that was installed into your project-root/plugins folder. This file must be copied into your project-root/www/js folder and referenced from the index.html currently.

https://github.com/phonegap-build/PushPlugin/blob/master/www/PushNotification.js

copy from phonegap plugin folder

copy from phonegap plugin folder

copy to www folder

copy to www folder

Write custom script for push notification plugin. Grab project id from Google Developer Console and put it inside this script. After that save as PushCustom.js in www/js.

// JavaScript Document
var pushNotification;

function onDeviceReady() {
		document.addEventListener("backbutton", function(e) {}, false);
		try {
			pushNotification = window.plugins.pushNotification;
			if (device.platform == 'android' || device.platform == 'Android' || device.platform ==
				'amazon-fireos') {
				pushNotification.register(successHandler, errorHandler, {
					"senderID": "xxxxxxxxxxxxx",
					"ecb": "onNotification"
				}); // required!
			} else {
				pushNotification.register(tokenHandler, errorHandler, {
					"badge": "true",
					"sound": "true",
					"alert": "true",
					"ecb": "onNotificationAPN"
				}); // required!
			}
		} catch (err) {
			txt = "There was an error on this page.\n\n";
			txt += "Error description: " + err.message + "\n\n";
			alert(txt);
		}
	}
	// handle APNS notifications for iOS

function onNotificationAPN(e) {
		if (e.alert) {
			// showing an alert also requires the org.apache.cordova.dialogs plugin
			navigator.notification.alert(e.alert);
		}
		if (e.sound) {
			// playing a sound also requires the org.apache.cordova.media plugin
			var snd = new Media(e.sound);
			snd.play();
		}
		if (e.badge) {
			pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
		}
	}
	// handle GCM notifications for Android

function onNotification(e) {
	switch (e.event) {
		case 'registered':
			if (e.regid.length > 0) {
				// Your GCM push server needs to know the regID before it can push to this device
				// here is where you might want to send it the regID for later use.
				alert("regID = " + e.regid);
			}
			break;
		case 'message':
			// if this flag is set, this notification happened while we were in the foreground.
			// you might want to play a sound to get the user's attention, throw up a dialog, etc.
			if (e.foreground) {
				// on Android soundname is outside the payload.
				// On Amazon FireOS all custom attributes are contained within payload
				var soundfile = e.soundname || e.payload.sound;
				// if the notification contains a soundname, play it.
				// playing a sound also requires the org.apache.cordova.media plugin
				var my_media = new Media("/android_asset/www/" + soundfile);
				my_media.play();
			}
			break;
		case 'error':
			break;
		default:
			break;
	}
}

function tokenHandler(result) {
	alert('device token = ' + result);
	// Your iOS push server needs to know the token before it can push to this device
	// here is where you might want to send it the token for later use.
}

function successHandler(result) {}

function errorHandler(error) {}
document.addEventListener('deviceready', onDeviceReady, true);

Add the following script line to your index.html to reference the PushNotification.js and PushCustom.js.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>
    <script type="text/javascript" src="js/PushNotification.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body ng-app="starter">

    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Ionic Blank Starter</h1>
      </ion-header-bar>
      <ion-content>
      </ion-content>
    </ion-pane>
  </body>
</html>

Build and run the application via eclipse (ADT installed) and Xcode6.

cordova build ios
cordova build android

Open your editor and create a file called simplepush.js.

Android setting

Go to your GCM console and locate the Server API key (click the API Access link in the menu on the left to locate they keys). http://blog.revivalx.com/2014/08/29/implement-push-notifications-for-android-and-ios-phonegap-part-1/

Get the registration id returned to our application from the console. I like to use the Android adb tool so I can run logcat to watch the console while my application is running. Assuming you have the android-sdk tools and platform-tools set on your environment path you can simply run adb logcat from the command line to show your device log.

Replacing the Sender key and device registration id with yours in simplepush.php.

IOS setting

Go to your apple developer account and locate iOS / APNs development certificates and provisioning profile then install it into your machine.

Get the token id returned to our Xcode console. Open your editor and replacing the token id and passphrase.

<?php
//enable it
//$deviceType = 'ios';
//$deviceType = 'android';

//operation begin
if($deviceType == 'ios'){

$deviceToken = 'xxxxx';
// Put your device token here (without spaces):

// Put your private key's passphrase here:
$passphrase = 'xxxxx';

// Put your alert message here:
$message = 'Technovault is awesome!!!';

////////////////////////////////////////////////////////////////////////////////

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

// Open a connection to the APNS server
$fp = stream_socket_client(
	'ssl://gateway.sandbox.push.apple.com:2195', $err,
	$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

if (!$fp)
	exit("Failed to connect: $err $errstr" . PHP_EOL);

echo 'Connected to APNS' . PHP_EOL;

// Create the payload body
$body['aps'] = array(
	'alert' => $message,
	'sound' => 'default',
	'badge' => 1
	);

// Encode the payload as JSON
$payload = json_encode($body);

// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));

if (!$result)
	echo 'Message not delivered' . PHP_EOL;
else
	echo 'Message successfully delivered' . PHP_EOL;

// Close the connection to the server
fclose($fp);
}
else if($deviceType == 'android'){

$deviceToken = 'xxxxx';

$registrationIds = array($deviceToken);

// prep the bundle
$msg = array
(
    'message' 		=> 'Technovault is awesome!!!',
	'title'			=> '[Warning]',
	'subtitle'		=> 'This is a subtitle. subtitle',
	'tickerText'	=> 'Ticker text here...Ticker text here...Ticker text here',
	'vibrate'	=> 1,
	'sound'		=> 1
);

$fields = array
(
	'registration_ids' 	=> $registrationIds,
	'data'				=> $msg
);

$headers = array
(
	'Authorization: key=' . 'xxxxx',
	'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;
}
else {
	echo "Error";
}

Now type the following from the command line where the script was created to run the code and send a push notification:
php simplepush.php

You should hear the notification and see it in your status bar like this on your Android and iOS devices.