Thursday, 19 November 2015

DeepLink Handler

Hello

Here is a way to handle deeplink if application is not installed in mobile.

Following is the index.html file for handling deeplink-

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
    <script type="text/javascript" src="js/deepLinkHandler.js"></script>
    <link rel="stylesheet" href="css/style.css">
    <script type="text/javascript">
        window.onload = function () {
            document.getElementById("url").click();
        }
    </script>
</head>
<body>
<div class="outer">
    <div class="inner">
        <a id="url" href="myapp://" onclick="clickHandler()"></a>
        <img src="../images/default.gif"/>
        <p>
            Redirecting to my app...<br>
            Please wait...
        </p>
    </div>
</div>
</body>
</html>

Where myapp:// is deep link url of my application

Following is the style.css file for handling deeplink-


img {
    top: 35%;
    right: 0;
    left: 0;
    margin: 0 auto;
    vertical-align: middle;
}
.outer{
    display: table;
    width: 100%;
    height: 100vh;
}
.inner{
    text-align: center;
    display: table-cell;
    right: 0;
    left: 0;
    vertical-align: middle;
    margin: 0 auto;
}

and image for the index.html page-


Following is the deepLinkHandler.js file for handling deeplink-

function clickHandler() {
    var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
    if( isMobile.Android() ) {
alert("Android");
        setTimeout(function(){
            window.location.href = "https://www.google.co.in/";
        }, 5000);
    }
 
    else{
        setTimeout(function(){
            window.location.href = "https://www.google.co.in/";
        }, 5000);
    }
}


Then after deploy your project on heroku.com  and send the project url by email , which is generated by heroku to handle deeplink.



Thanks...

Tuesday, 17 November 2015

Deeplinking in Ionic application

Hello,

Deeplinking is a methodology for launching a native mobile application via a link.
Deeplinking connects a unique url to a defined action in a mobile app, seamlessly linking users to relevant content.


Now, we can also use deeplinking in ionic application.

Following are the commands for deeplinking in blank app-

ionic start myapp blank
cd myapp
ionic platform add android

Then we will add the following plugin for the deeplinking

cordova plugin add https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin.git --variable URL_SCHEME=myapp

Here in URL_SCHEME we will assign that name of app which we want in form of url.
So in our case url will be myapp:// 

Now we will add following lines of code in config.xml

<plugin name="cordova-plugin-customurlscheme" source="npm">
    <param name="URL_SCHEME" value="myapp"/>
  </plugin>
Here in value you will assign name as in URL_SCHEME.
So, now your config.xml  looklike-


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="com.ionicframework.wgldeep641489" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  <name>myapp</name>
  <description>
        An Ionic Framework and Cordova project.
    </description>
  <author email="hi@ionicframework" href="http://ionicframework.com/">
      Ionic Framework Team
    </author>
  <feature name="StatusBar">
    <param name="ios-package" value="CDVStatusBar" onload="true"/>
  </feature>
  <content src="index.html"/>
  <access origin="*"/>
  <preference name="webviewbounce" value="false"/>
  <preference name="UIWebViewBounce" value="false"/>
  <preference name="DisallowOverscroll" value="true"/>
  <preference name="android-minSdkVersion" value="16"/>
  <preference name="BackupWebStorage" value="none"/>
  <preference name="SplashScreen" value="screen"/>
  <preference name="SplashScreenDelay" value="3000"/>
  <plugin name="cordova-plugin-customurlscheme" source="npm">
    <param name="URL_SCHEME" value="myapp"/>
  </plugin>
  <platform name="android">
    <icon src="resources/android/icon/drawable-ldpi-icon.png" density="ldpi"/>
    <icon src="resources/android/icon/drawable-mdpi-icon.png" density="mdpi"/>
    <icon src="resources/android/icon/drawable-hdpi-icon.png" density="hdpi"/>
    <icon src="resources/android/icon/drawable-xhdpi-icon.png" density="xhdpi"/>
    <icon src="resources/android/icon/drawable-xxhdpi-icon.png" density="xxhdpi"/>
    <icon src="resources/android/icon/drawable-xxxhdpi-icon.png" density="xxxhdpi"/>
    <splash src="resources/android/splash/drawable-land-ldpi-screen.png" density="land-ldpi"/>
    <splash src="resources/android/splash/drawable-land-mdpi-screen.png" density="land-mdpi"/>
    <splash src="resources/android/splash/drawable-land-hdpi-screen.png" density="land-hdpi"/>
    <splash src="resources/android/splash/drawable-land-xhdpi-screen.png" density="land-xhdpi"/>
    <splash src="resources/android/splash/drawable-land-xxhdpi-screen.png" density="land-xxhdpi"/>
    <splash src="resources/android/splash/drawable-land-xxxhdpi-screen.png" density="land-xxxhdpi"/>
    <splash src="resources/android/splash/drawable-port-ldpi-screen.png" density="port-ldpi"/>
    <splash src="resources/android/splash/drawable-port-mdpi-screen.png" density="port-mdpi"/>
    <splash src="resources/android/splash/drawable-port-hdpi-screen.png" density="port-hdpi"/>
    <splash src="resources/android/splash/drawable-port-xhdpi-screen.png" density="port-xhdpi"/>
    <splash src="resources/android/splash/drawable-port-xxhdpi-screen.png" density="port-xxhdpi"/>
    <splash src="resources/android/splash/drawable-port-xxxhdpi-screen.png" density="port-xxxhdpi"/>
  </platform>
</widget>


So, now your app will work with the url myapp://




Thanks......

Friday, 13 November 2015

$http service in Angularjs

The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.


The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise.


Example-

$http({ 
method: 'GET', 
url: '/demoUrl' 
}) 
.then(function successCallback(response) { 
// this callback will be called asynchronously 
// when the response is available 
}, 
function errorCallback(response) { 
// called asynchronously if an error occurs 
// or server returns response with an error status. 
});

The response object has following properties:
  1. data{string|Object} – The response body transformed with the transform functions.
  2. status{number} – HTTP status code of the response.
  3. headers{function([headerName])} – Header getter function.
  4. config{Object} – The configuration object that was used to generate the request.
  5. statusText{string} – HTTP status text of the response.
A response status code between 200 and 299 is considered a success status and will result in the success callback being called.
If the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the error callback will not be called for such responses.

Example-

post method in $http-

 $http.post(url, data, config)    
        .success(function (data, status, headers, config)
{         // result in case of success
    })        
     .error(function (data, status, header, config) {   
// result in case of error
         });


Friday, 6 November 2015

Using promises and $q to handle asynchronous calls in angularjs

Hello,

Here i am introducing how to handle asynchronous calls in angularjs , take a look here-

$q-




  1. - service in module ng

A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

This is an implementation of promises/deferred objects inspired by Kris Kowal's Q.

The CommonJS Promise proposal describes a promise as an interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.
From the perspective of dealing with error handling, deferred and promise APIs are to asynchronous programming what try, catch and throw keywords are to synchronous programming.


Example-
For the purpose of this example let's assume that variables `$q` and `GetValue`
are available in the current lexical scope (they could have been injected or passed in).

function GetName(name)
var deferred = $q.defer(); 
setTimeout(function() { 
deferred.notify('About to greet ' + name + '.'); 
if (GetValue(name)) { 
 deferred.resolve('Hello, ' + name + '!'); } 

else { 

deferred.reject('Greeting ' + name + ' is not allowed.');  } 

}, 
1000):

return deferred.promise;}var promise = GetName('Robin Hood');

promise.then(function(greeting) {

  alert('Success: ' + greeting);},

function(reason) { 

alert('Failed: ' + reason);},

function(update) { 

 alert('Got notification: ' + update);});





At first it might not be obvious why this extra complexity is worth the trouble. The payoff comes in the way of guarantees that promise and deferred APIs make.

Additionally the promise api allows for composition that is very hard to do with the traditional callback (CPS) approach.

The Deferred API-

A new instance of deferred is constructed by calling $q.defer(). The purpose of the deferred object is to expose the associated Promise instance as well as APIs that can be used for signaling the successful or unsuccessful completion, as well as the status of the task. Methods-
  • resolve(value) – resolves the derived promise with the value. If the value is a rejection constructed via $q.reject, the promise will be rejected instead.
  • reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.
  • notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected.
Properties-
  • promise – {Promise} – promise object associated with this deferred.

The Promise API-

A new promise instance is created when a deferred instance is created and can be retrieved by calling deferred.promise.
The purpose of the promise object is to allow for interested parties to get access to the result of the deferred task when it completes.
Methods-
  • then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining). It also notifies via the return value of the notifyCallback method. The promise cannot be resolved or rejected from the notifyCallback method.
  • catch(errorCallback) – shorthand for promise.then(null, errorCallback)
  • finally(callback, notifyCallback) – allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved.
Thanks.........

Friday, 30 October 2015

Install Ionic Framework and dependencies

Hello,

Here i am sharing the requirements and there command for the setup of Ionic Framework and android on Ubuntu.

Following are the requirements-

Requirements-

1) Java JDK 

commands-

sudo apt-get update
java -version

If it returns "The program java can be found in the following packages", Java hasn't been installed yet, so execute the following command:

sudo apt-get install default-jre


This will install the Java Runtime Environment (JRE). If you instead 
need the Java Development Kit (JDK), which is usually needed to compile 
Java applications execute the following command:

sudo apt-get install default-jdk

2) Apache Ant-

Commands-

sudo apt-get update
sudo apt-get install ant

3) Android SDK-

Commands-

sudo add-apt-repository ppa:ubuntu-desktop/ubuntu-make
sudo apt-get update
sudo apt-get install ubuntu-make

Once you have installed Ubuntu Make, use the command below to install Android Studio in Ubuntu:

umake android



4) Nodejs-

Commands-

sudo apt-get install curl
curl -sL https://deb.nodesource.com/setup_0.12 | sudo bash -
sudo apt-get install nodejs


5) NPM-

Commands-

sudo apt-get update
sudo apt-get install npm


6) Apache Cordova-

Commands-

sudo apt-get update
sudo npm install -g cordova


7) Ionic Framework-
Commands-
npm install -g ionic ionic lib update





Thanks....

Friday, 23 October 2015

Example of SQLite in Ionic Framework

Hello,

Here i am sharing an example of SQLite in Ionic Framework.

So, following are the commands to start a project in Ionic Framework-

 ionic start IonicSqliteProject blank
cd IonicSqliteProject
ionic platform add android

The next thing we want to do is add the SQLite plugin.  This can be done by running the following command:

cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin.git 



Download the latest release and copy ng-cordova.min.js into your www/js directory.


Then include that  ng-cordova.min.js file in your index.html file , your index.html file look like-

<!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">     
    <script src="lib/ionic/js/ionic.bundle.js"></script>     
    <script src="js/ng-cordova.min.js"></script>      
   <script src="cordova.js"></script>        
 <script src="js/app.js"></script>  
   </head>


Here i am only showing the head section of index.html file, rest will same.


One more thing must be added before we can start using ngCordova.  We need to inject it into our angular.module, that is in app.js, like the following:


angular.module('starter' , ['ionic','ngCordova'])


It’s time to start using this library.  For simplicity, we are going to do the following:
  1. Create a new table called demo
  2. Insert two people into this new table
  3. Select all the people found in our table with my last name

Before we start coding, it is very important to note that database activity can only be done when the onDeviceReady() method has fired.  With this in mind, I’m going to open the database in the modules .run() method like so:


var db = null;
var example = angular.module('starter', ['ionic', 'ngCordova'])  
  .run(function($ionicPlatform, $cordovaSQLite)  
{    
    $ionicPlatform.ready(function()  
{        
    if(window.cordova && window.cordova.plugins.Keyboard) 
{            
    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);        
    }   
          if(window.StatusBar) 
{          
 StatusBar.styleDefault();        
    }       
      db = $cordovaSQLite.openDB("my.db");         
    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS demo (id integer primary key, firstname text, lastname text)");     
    });   
  });


 We want to have access to the database globally so I created a variable outside of any method or controller.  To use the ngCordova functions we need to include $cordovaSQLite in the .run() method.  Finally, you can see that I’ve created a new database called my.db and a fresh table called demo.
This leaves us with a usable database ready for activity in our controllers.  Take the following for example:


example.controller("ExampleController", function($scope, $cordovaSQLite)
{    $scope.insert = function(firstname, lastname)
{       
 var query = "INSERT INTO demo (firstname, lastname) VALUES (?,?)";     
   $cordovaSQLite.execute(db, query, [firstname, lastname]).then(function(res)
{       
   console.log("INSERT ID -> " + res.insertId);     
   },
function (err)
{            console.error(err);        });  
  }    $scope.select = function(lastname)
{       
 var query = "SELECT firstname, lastname FROM demo WHERE lastname = ?";     
   $cordovaSQLite.execute(db, query, [lastname]).then(function(res) {          
  if(res.rows.length > 0)
{           
     console.log("SELECTED -> " + res.rows.item(0).firstname + " " + res.rows.item(0).lastname);         
   }
else
{                console.log("No results found");            }    
    }, function (err)
{            console.error(err);        });   
 }
});



Here i have created two very basic functions.  The insert function will add a first and last name record into the database while the select function will find records by last name.


Something to note about my controller though.  I am not doing these database calls from inside an onDeviceReady() function.  Had these functions been fired when the controller loads, they probably would have failed.  Since I am basing the database activity off button clicks, it is probably safe to assume the device and database is ready for use.



Thanks...

Monday, 28 September 2015

Implement Google Maps Using Ionic Framework

Hi,

Here is a way by which we can implement Google Maps in Ionic framework

Run the following command for a blank Ionic project-

ionic start Map blank
cd Map
ionic platform add android

Since we are using maps, it is probably a good idea to add geolocation functionality to your application.  You can add the Apache Cordova Geolocation API by running the following command:

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git


We are going to be using the Google Maps JavaScript SDK, which requires us to have an API key for use in our application.  Go into your Google API Console and register a new Google Maps application.

When you have Google API key, crack open your www/index.html file because we need to add the JavaScript library to our project.

<!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="lib/ngCordova/dist/ng-cordova.js"></script>
    <script src="cordova.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>
  <script src="http://maps.googleapis.com/maps/api/js?key=Your_API_key&sensor=true"></script>
  </body>
</html>

Please note that the Google Maps JavaScript library cannot be downloaded, so there will always be a small delay during the initial setup when you launch your application.



Now that the SDK is included we need to add some CSS for displaying it on the screen.  Open your www/css/style.css file and add the following code:

.scroll {
    height: 100%;
}
#map {
    width: 100%;
    height: 100%;
}

Open your www/app.js file because we want to add a controller that handles the Google Map.

var Map = angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})
Map.controller('MapController', function($scope, $ionicLoading) {
    google.maps.event.addDomListener(window, 'load', function() {
        var myLatlng = new google.maps.LatLng(37.3000, -120.4833);
        var mapOptions = {
            center: myLatlng,
            zoom: 16,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"), mapOptions);
        navigator.geolocation.getCurrentPosition(function(pos) {
            map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
            var myLocation = new google.maps.Marker({
                position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
                map: map,
                title: "My Location"
            });
        });
        $scope.map = map;
    });
});


  We need to add some code to our www/index.html file for containing the map.


 <ion-content ng-controller="MapController">
          <div id="map" data-tap-disabled="true"></div>
      </ion-content>

Thanks.