Tuesday, April 25, 2017

Cordova Push Notification Using Firebase & Onesignal Plugin



What is Push Notification


Push notification is one of the best way to send messages to app user and its simplest way to reach to the app user. Push notification is message that pops out on mobile device. App publisher can send then at any time. Push notification is similar to SMS  text message but they only reach to users who have installed your app. Push notification are mostly using for e.g promoting products and increase sales,improve customer experience and sports scores and news right on their lock screen.

How to setup push notification in cordova with firebase using onesignal plugin. 

Firebase Setup Steps :-

  1.  First you have to create project in firebase so goto this link https://console.firebase.google.com login with your gmail account.
  2. Once login into your dashboard create new project by clicking on Add Project (+) sign.
  3. Then just entered project name and select country and created a project.
  4. After creating project just clicking on setting icon which near to overview menu which is in top-left corner then goto project settings
  5. Once you are in setting option select "Cloud Messaging" tab then go and copy the Legacy server key and below Sender ID
  6.  then stop here and start configuring your one signal for sending push notification for your app
One signal Setup Steps:




  1. login into one signal with gmail or facebook as per your choice.
  2. once login create a new app by clicking add new app (+) sign.
  3.  Once click on it enter app name once created goto to and click on  "All Apps" menu option which is on bottom-left corner .
  4. then you can see your app dashboard click on "Finish App Setup" after your clicking one it one pop will be open in that pop you have to select one platform to configure  so here we are using firebase so will be select "GCM" option.
  5. Once selected click on next then you have to copy and paste your "google server key " and "google project number" that you created in previous in firebase
  6. Once copy and paste proper server key and project number save it.
  7. after saving next pop will open and you have to select SDK so here i am choosing "Phonegap cordova" option.
     
  8. Once selected the sdk and after saving it you will get App ID is copy and paste in somewhere so that you have to used in onesignal plugin code.
Once configured firebase and onesignal open your cordova project and install onesignal plugin by using following command 

C:\Users\sushant\sampleX>cordova plugin add onesignal-cordova-plugin

copy below code into device ready function and copy and paste your App id which you already get singalong configuration previously 

onDeviceReady: function() {

    this.receivedEvent('deviceready');

    var notificationOpenedCallback = function(jsonData) {
        console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
      };

      window.plugins.OneSignal
        .startInit("3990f7d2-7608-4043-b9ad-9e79f299ceb2")
        .handleNotificationOpened(notificationOpenedCallback)
        .endInit();


     var onSuccess = function(position) {
             window.localStorage.setItem('long',position.coords.longitude);
             window.localStorage.setItem('lat',position.coords.latitude);
        };
        function onError(error) {
            alert('code: '    + error.code    + '\n' +
                'message: ' + error.message + '\n');
        }
     navigator.geolocation.getCurrentPosition(onSuccess, onError);
 }

Then run your app and then goto onesingal dashboard to send your push notification message to
your device

1. Select your app in one signal dashboard once clicked you see more option just select "New Push Notification"
2. next there are many option right now i am selecting "send to everyone"; -> next
3. Enter message title and message ->next
4.just click again next
5.then click on confim ->send message

   

Friday, April 7, 2017

Cordova App with Google Places Api Service


  1. In this we learn how to consume google place api service and create nearby place app using cordova. In this app we will fetch nearest Bank ATM List.
  2. In this app i will tell you what you will required which are as follows:- 
    1.  You required Google Place api key which you will get from below link-      https://developers.google.com/places/web-service/intro (Detailed Google Places api documentation) .
    2. Once you will get key just save or copy paste somewhere in txt file
    3. Now create project in cordova 
    4. Once cordova project is created goto project folder and install GeoLocation plugin in cordova project. with this plugin we will get current latitude and longitude Link for downloading plugin - cordova plugin add cordova-plugin-geolocation     
    5. Include jquery-1.11.1.min.js path in index.html
    6. Comment <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 *; img-src 'self' data: content:;"> line in index,html
    7. Open project in android studio.
    8. All above step completed then we will start for coding.
  3. So now open Index.js file in onDeviceReady we will write code for getting current position i.e longitude & latitude code is below
           var onSuccess = function(position) {
window.localStorage.setItem('long',position.coords.longitude);
window.localStorage.setItem('lat',position.coords.latitude);
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
From above code we will get longitude and latitude and we will be store that thing in our Localstore its one of the great feature of HTML5 where we can store value in key->value pair and used it anywhere in our code. for more information on localstore used this link below link https://www.w3schools.com/html/html5_webstorage.asp
4. Now write code for getting nearest bank ATM list in JQuery AJAX.
$(document).ready(function(){
    var lat=window.localStorage.getItem('lat');
    var long=window.localStorage.getItem('long');
    var radius=1;  // location radius which from 1 to 50000 km
    var type='atm'; // this a type which defined in google place service api
     $.ajax({
           type       : "POST",
           url        : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+lat+","+long+"
&radius="+radius+"000&type="+type+"&key=***insert key code here***", crossDomain: true, dataType : 'json', success : function(response) {
            //console.log(response.results) // check your response in console
            $.each( response.results, function(key,value ) {
                        $('.content').append('<li>'+value.name +''+'</li>');
            });
            },
            error: function() {
             alert('Something went wrong :(');
             }
            });
        })

       In above code i will get lat and long from local storage which already get its value using 
       Geolocation Plugin onDeviecReady Function and getting value from response.results obaject 
       we are using $.each function for getting value from object.
5. In Index.html write below code in body
<h4>Nearest ATM Bank List</h4>
         <ul class="content">
         </ul>
     In this li tag is created dynamically and will append that li to ul using jquey append function.

  6. Output of the code  & GitHub link for project folder  are below: 
   
          GitHub Link Click Here :)
         

Sunday, March 19, 2017

What is cordova plugin? & How to add plugin in cordova project.

What is cordova plugin?
  1. Plugin is one of the most important thing in cordova mobile apps.
  2.  Plugin is a package of injected code that allows the cordova webview within which the app renders to communicate with the native platform on which its runs.
  3. Plugin provide access to device and platform functionality that is ordinarily not available to web apps.
  4. Plugin comprise a  single JavaScript interface along with corresponding native code libraries for each supported platform. In essence this hides the various native code implementation behind a common JavaScript interface. 
  5. Main cordova API features are implemented as plugins. through these plugins you can access all native functionality in your cordova mobile app or you can create your own plugin to fully your requirement in app. 
  6. In cordova there are many cordova plugins are available for use or you can create your own plugin and published it to cordova open source community. So any one can use it.
How to add plugin in cordova project
  1. Adding plugin to cordova project is very simple just required to run some following command in CLI.
  2. First you have entered to your cordova project that you already crearted like i have already created sampleX project previously.
  3. So now i am adding cordova splash screen plugin using CLI
  4. So open your cmd and select your project path - C:\Users\sushant>cd sampleX
  5. After entered your project folder run below cmd -
    cordova plugin add cordova-plugin-splashscreen
  6.  Plugin will download from srouce. one download completed it will added to our cordova project Plugin directory . assets/www  folder is our working directory where you will add all your code into this directory. you can also see that i am added plugins which are come under plugin folder where you can see the splash screen folder.
  7. So now build the project and run it. when the mobile app start first time you will see a splash screen with cordova default image on it.
  8.  You can change your splash screen with your own app splash screen. So Goto res folder where you will see many folders in that drawable-XXXX-XXXX folders have splash screen images which have specific dimension as per device type. So just replace your splash screen with default splash screen.

Saturday, March 18, 2017

Cordova Setup In Android Studio


  1. In Cordova you can also build mobile app using with CLI(Command Line interface). but many people using android studio so i think its better practice to build your mobile app in android studio.
  2. Using android studio you can build and test your mobile app in emulator or on your mobile device in faster way.
  3. So before setting up in project in android studio you have to create project in cordova by using following commands.
                                                          First create a project. 

                                  cordova create hello com.example.hello HelloWorld

                                          Once project is created entered into project folder 

  cd hello

After entering into the project folder add platform android

C:\users\sushant\hello> cordova platform add ios  android --save

       4. Once you completed all above steps launch your android studio.
       5. Select option "Open an  existing Android Studio Project".
                   


       6. After that browser your cordova project directory. Goto your project directory for e.g project                directory is  sampleX then select platforms  -> android directory once selected android                       directory press Ok button.


  
      7. Gradle Sync dialoug box will open just click on Ok . wait for to build Gradle completely.


 8. Now Goto Project tab which on left of android studion and select Project option from it

              Once you setup cordova project in android studio. you will get all yours project files in                         assets/www folder and index.html is launching page of your app.
          
    9. Now build and test mobile app on your mobile device.so you are required to follow some steps.
         1. First Goto your mobile device setting option  enable Developer options for enabling this option you must goto About phone -> tap 3 times on build number option once done you will see the toast mesage saying you are developer now.
         2. Goto to Developer option and enable it and also enable USB debugging  
         3. Now connect your mobile device with your pc using USB cable.
         4. After that select Run/Debug configuration option in android studio. steps as follow:-

               1. Select Edit Configuration  option


      2. after clicking Edit configuration option following dialog box will open, in that select                            Deployment Target Options -> USB Device
                 
      3. Then Run the project on clicking Run button in android studio. In bottom android monitor                   option display your mobile device name means your device connected successfully. 
         
    4. In end test your mobile app on your device once your mobile app build successfully.

   
   

Friday, March 10, 2017

Basic Cordova Commands for creating app


Create App

  1. Create directory where you maintain your code and create project. so open command prompt and perform the following commands.
  • cordova create hello com.example.hello HelloWorld
  • This creates the required directory structure for your cordova app. By default, the cordova create script generates a skeletal web-based application whose home page is the project's www/index.html file.

Add Platforms

     2. Once you created project the next step is to add platform to your project. for that you have enter          into project folder with the following command.
  • cd hello 
  • once your entered into your project directory write this command in command prompt
  • C:\users\sushant\hello> cordova platform add ios  android --save
  • C:\users\sushant\hello> cordova platform add android --save  
  • choose platform as per your requirement if you want to create project for android then add android platform & ios for iphone and so on. plus ensure they get saved to config.xml.
  • You can also check your current set of platforms
  • C:\users\sushant\hello>cordova platform ls

Build The App

     3. By default cordova create command create web-based application structure  whose start page is          projects   www/index.html file. Any initialization should be specified as part of the device                  ready event handler defined in www/js/index.js 

  • Run the following command to build the project for all platforms:
  • C:\users\sushant\hello>cordova build 
  • You can build your app using CLI(command line interface) or use Android Studio IDE for building android app.
  • So next blog i will learn you have to setup cordova project in Android Studio and how to build it and test mobile app on your android mobile.





Friday, January 27, 2017

Cordova Installation

Install Cordova

  1. Install Node.js cordova runs on Node.js So download link - http://nodejs.org
  2. Run and installed Node.js exe file.
  3. Test node.js installation open cmd prompt and run this command - node --version (if version is displayed means node installed succesfully)
  4. Install cordova- cordova is installed using  npm (Node Package Manger) here is the cmd   npm install -g cordova
  5. Test cordova installation run this cmd - cordova --version

Install Java


  1. The Android SDK needs the Java Development Kit (JDK) to be installed, version 1.7 or later. Note that the Java Runtime Environment (JRE) is not sufficient, you will need the JDK. To check if you have the JDK installed already, type this on the command line:  javac -version

If you do not have the JDK installed, proceed as follows:

  1. Download the recent version of Java SE JDK (SE = Standard Edition) from Oracle: www.oracle.com/technetwork/java/javase/downloads/.
  2. Go along and run the downloaded installer file. Using the default selections should be fine, but take a note of the directory in which you install the JDK. 
  3. Next, update your path to include the JDK. Open the Control Panel, click System and Security, click System, click Change settings, which will open the System Properties window. Select the Advanced tab, then click the Environment Variables button.
  4. In the list User variables select PATH and click the Edit button. (If there is no PATH entry in the list, click the New button to create one.)
  5. At the end of the field Variable value, add a semicolon followed by the path to the bin directory of the JDK install. Here is an example (note that this must be the actual path used for the install on your machine):
    C:\Program Files\Java\jdk1.8.0_11\bin
    • An easy way to do this is to prepare the path to add in a text editor, then paste it at the end of the input field. When done click the OK button.
  6. Next add the JAVA_HOME variable if it is not present (and if it is in the list, you may need to update its value using the Edit button). Click the New button. In the field Variable name type:
    JAVA_HOME
    In the field Variable value enter the path to the directory where the JDK is installed, without the semicolon and the /bin subdirectory, for example:
    C:\Program Files\Java\jdk1.8.0_11
    Click the OK button.
  7. Click the OK button again to close the Environment Variables window.
  8. Now you are ready to test the install. Close any open command windows, and open a new command window and type:
    javac -version
  9. If you see a version number you are done with the JDK install!

Install the Android Tools

To install the tools needed to build Android app using Cordova you need the Android SDK Tools. The easiesy way to install these tools is to install Android Studio. 
  1. Go to the Android Studio download page and download and install Android Studio for your platform. 
  2. Find the path of the Android SDK tools by consulting the sdkmanager documentation page. Check in your system that the files are actually there.
  3. Add the path of the SDK Tools (directories tools and platform-tools to the system PATH variable. Open the Control Panel, click System and Security, click System, click Change settings, click the Advanced tab, then click the Environment Variables button.
  4. In the list User variables select PATH and click the Edit button.
  5. At the end of the field Variable value, add a semicolon followed by the path to the tools and platform-tools directores of the Android SDK install. Here is an example of what to add (note that there are two paths in one line, separated by a semicolon):

    C:\Users\miki\AppData\Local\Android\android-sdk\tools;
    C:\Users\miki\AppData\Local\Android\android-sdk\platform-tool
  6. Next add the ANDROID_HOME environment variable in system settings in the same way that the JAVA_HOME variable was added above when installing Java. Set ANDROID_HOME to point to the root of the Android SDK folder, for example:
    C:\Users\miki\AppData\Local\Android\android-sdk
    adb version
    1. This should display the version of the Android Debug Bridge.
  7. Click the OK button again to close the Environment Variables window.
  8. Now test the install. Close any open command windows, open a new command window and type: adb version
  9. As the final step, you may need to get the specific Android SDK version used by Cordova. This can be done using the sdkmanager command or by using the tools in Android Studio.

Brief introduction to apache cordova

  • Cordova is an open source mobile app development framework that is primarily intended for web developers.
  • Its allow web developers to create mobile app using standard web technologies like HTML5, CSS3 and JavaScript. 
  • Even  you can used JQuery and JavaScript framework like Angularjs.
  • Using cordova you can  extend an  application across more than one platform like android,ios,windows and Blacberry.

Cordova has its pros and cons which as follows


  • Pros
    • Easy to learn - if you are web developer or you know basic HTML5,CSS3 and JavaScript you can learn easily and quickly. but you must familiarize yourself with the Command Line Interface (CLI) in order to running cordova.
    • Easy access to native functionality  - you can easily access device native capabilities such as Contacts,Camera,Media,Network and  Geolocation and many more. using cordova API's.
    • Free and Open source - Cordova is free framework for that you don't required to pay plus its open source so you can also used another developers custom plugin in your app. Or you can build your own plugin and share it with others.
    • Deploy Everywhere - Cordova compile your app into packages file,which supported by most app store. For deploying to android,cordova creates an APK file ,In IOS cordova complies IPA  and windows its APPX.
  • Cons
    • Slower in nature than native -  Apps built in cordova  basically web apps that are contained in a web view, they don’t perform as well as their native counterparts.
    • UI Frameworks - Cordova is wrapper for web application it doesn't come with user interface components,controls and animation that we found in native application. So that why many web developer are using Ionic and Onsen UI for  building UI for their applications.
    • Plugins - In cordova to interact with native functionality we are using plugins sometimes its work like charm but sometimes some device doesn't support same plugins.  


Cordova Push Notification Using Firebase & Onesignal Plugin

What is Push Notification Push notification is one of the best way to send messages to app user and its simplest way to reach to the a...