Android Push Notification via PHP in Ionic/Cordova


If you want to send push notification to a android device via PHP the you've to follow below steps :
  • If you are using phonegap then install phonegap push notification plugin via
    
           cordova plugin add phonegap-plugin-push
          
    OR
    If you are working on native coding, You've to install Android Push Notificaion SDK
  • Create a project on Google Developers Console and enable "Cloud Messaging for Android" API for this project
  • This code execute after device ready :
          
           
       var push = PushNotification.init({
         "android" : {
          "senderID" : "9XX5XXX346XX"// This is your project number which you've created on Google Developers Console
         },
         "ios" : {},
         "windows" : {}
        });
    
       push.on('registration', function(data) {
        //data.registrationId
        //send this token on server
    
       });
       push.on('notification', function(data) {
        if (data.sound) {// play specific sound on notification received(When app running)
         var snd = new Media('file:///android_asset/www/sound/' + data.sound);
         snd.play();
        }
        
        if (!data.additionalData.foreground) {
         // app is NOT RUNNING and new notification is RECEIVED
         
        } else {
         // app is RUNNING and new notification is RECEIVED
        }
       });
    
       push.on('error', function(e) {
        //alert(JSON.stringify(data))
        // e.message
       });
          
         
  • PHP Code for send push notification
          
           $api_key = "AXXaSyXXyKXXNZXXf8O27hXX2DcrXXAEeXXuXX0";// your Google Developers Console Project API key
            
           $data =  array(
                          "message" => $message,
                          'title' => $title,
                      );
             
           
           // URL to POST to
           $gcm_url = 'https://android.googleapis.com/gcm/send';
          
           // data to be posted
           $fields = array('registration_ids' => $registration_ids, 'data' => $data, );
          
           // headers for the request
           $headers = array('Authorization: key=' . $api_key, 'Content-Type: application/json');
          
           $curl_handle = curl_init();
          
           //echo 'Notification PhP file';
          
           // set CURL options
           curl_setopt($curl_handle, CURLOPT_URL, $gcm_url);
          
           curl_setopt($curl_handle, CURLOPT_POST, true);
           curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
           curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
          
           curl_setopt($curl_handle, CURLOPT_POSTFIELDS, json_encode($fields));
          
           // send
           $response = curl_exec($curl_handle);
          
           curl_close($curl_handle);
           
          
         

Send Push Notification to specific user instead of device(How to idenifiy, which user is login, if more then one user using same device) in Ionic/Cordova



When you sending push notification then there is a big problem appear that How to identify which user is currently login on the specific device, if more then one user using same device, because a application create same 'device token' for a device, it's not depend that who is login.


Each time when user login: You’ve to maintain a column in the user table, suppose the column name is ‘has_duplicate_id’ by default it’ll be ‘false’.
  • Send the ‘device_id’ on server with ‘user_id’.
  • Check that this ‘device_id’ is already used by some other ‘user_id’ or not.
    • If ‘Yes’(device_id already exist for some other user_id) then update the ‘has_duplicate_id’ column ’true’ for the ‘user_ids’ which has already this ‘device_id’ and for this ‘user_id’ mark ‘has_duplicate_id’ to ‘false’.
    • If ‘No’(device_id not exist in DB) then update this ‘device_id’ for particular ‘user_id’.
  • Check that this ‘device_id’ is already used by some other ‘user_id’ or not.
  • When you’ve to send the push notification on particular user_id then :
     => First you’ve to check ‘has_duplicate_id’
    • If it’s set as ‘false’ then send the push notification on this device_id.
    • If it’s set as ‘true’ then make a ‘push_notification_queue’ table and push the information(save the notification information in table) in this table, whenever any user login then first you’ve to check this table, if any entry exist for this user_id in ‘push_notification_queue’ table then send the push notification and remove the details from ‘push_notification_queue’ table.     

This is a chat application DB design :

$http.post is not working in Ionic in Ionic/Cordova

If you are facing some issue with '$http.post', actually problem with your server side code not JS code. If you are using PHP for server side then you've to use "file_get_contents('php://input')" for get your posted data. Full Code:

JS Code :

var data = {user : 'user',pass:'123456'}
$http.post('http://example.com/page_name',
    {data:JSON.stringify(data)}
)
.success(function(response){
 console.log('Success : '+JSON.stringify(response));
}).error(function(err){
 console.log('Error : '+JSON.stringify(err));
});

PHP Code :

$params = json_decode(file_get_contents('php://input'), true);

$data = json_decode($params['data'], true);
//here is your data which you post


Manage cross domain request in php

If you are making a app and using web services(WS) then don't need to worry because if you requesting throw app then this will work but if you'll run this same app on your desktop browser then there is a 'cross domain' error, you can remove this by writing following code on the top of your PHP file :


    header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');


on the place of '$_SERVER['HTTP_ORIGIN'])', you can write the server name(like : localhost etc.), if you want to allow cross domain request form a specific server.

How to pass more than one param object in state in ionic framework? in Ionic

If you want to add more then one parameters in ionic state then you can defiantly add, you can define parameters and separate them by '/'


url:/dashboard/:userName/:userId'

Full Code :

.state('dashboard', {
 url : '/dashboard/:userName/:userId',
 templateUrl : 'templates/dashboard.html',
 controller : 'dashboardCtrl'
})

If you want to go this state, then you can write :

$state.go('dashboard', {
    userName:'Jassu',
    userId: '08ERD019'
});

Ionic Sqlite database using Service to get data dynamically

If you want to use SQLite for your Ionic app then you can prefer http://ngcordova.com/docs/plugins/sqlite/  and If you want to access data form SQLite DB using the Service or Factory, is a good practice. Here is the sample code for access data form SQLite via factory :


Define Controller(in controller.js) :

controller('dataCtrl', function($scope, factoryData) {
 factoryData.all().then(function(response) {
  $scope.data = response;
 });

})

Define Factory(in services.js) :

.factory('factoryData', function($cordovaSQLite, $timeout, $q) {
 var dataFun = function(deferred) {
  var data = [];
  var query = "SELECT * FROM tbl"
  $cordovaSQLite.execute(db, query).then(function(res) {
   if (res.rows && res.rows.length > 0) {
    for (var i = 0; i < res.rows.length; i++) {
     data.push({
      "id" : res.rows.item(i).id,
      "name" : res.rows.item(i).name
     });
     if (i == res.rows.length - 1) {
      deferred.resolve(data);//send final data to controller
     }
    }
   } else {
    deferred.resolve(data);//send final data to controller
   }

  }, function(err) {
   console.error(err);
  });

 };
 return {
  all : function() {
   var deferred = $q.defer();
   dataFun(deferred);
   return deferred.promise;
  }
 };

});


Here '$cordovaSQLite' is a pre define function in ngCordova, if you don't want to user the ngCordova then you can use 'tx.executeSql' place of '$cordovaSQLite.execute' and for more details visit https://github.com/litehelpers/Cordova-sqlite-storage

Show tabs at bottom on android in Ionic

When you'll create a new project with ionic tabs then the tabs for android will show at top of the page by default, however on IOS these are show at bottom  so if you want tab on bottom on android also then modify you app.js as below:



function($ionicConfigProvider) {

 $ionicConfigProvider.tabs.position('bottom');
//other values: top

}])

Show a confirmation alert before app close


If you want to add a confirmation alert before app close, modify your app.js as below :

Type 1:(show a alert message)

$ionicPlatform.registerBackButtonAction(function(e) {
 e.preventDefault();
 function showConfirm() {
  var confirmPopup = $ionicPopup.show({
   title : 'Exit AppName?',
   template : 'Are you sure you want to exit AppName?',
   buttons : [{
    text : 'Cancel',
    type : 'button-royal button-outline',
   }, {
    text : 'Ok',
    type : 'button-royal',
    onTap : function() {
     ionic.Platform.exitApp();
    }
   }]
  });
 };

 // Is there a page to go back to?
 if ($ionicHistory.backView()) {
  // Go back in history
  $ionicHistory.backView().go();
 } else {
  // This is the last page: Show confirmation popup
  showConfirm();
 }

 return false;
}, 101);


Type 2:(show a toast message 'Press again to exit' before exist the app)
For impliment this, you must have to add 'ng-cordova.js' and have to install ngCordova Toast Plugin


var countTimerForCloseApp = false;
$ionicPlatform.registerBackButtonAction(function(e) {
 e.preventDefault();
 function showConfirm() {
  if (countTimerForCloseApp) {
   ionic.Platform.exitApp();
  } else {
   countTimerForCloseApp = true;
   showToastMsg($cordovaToast, 'Press again to exit.');
   $timeout(function() {
    countTimerForCloseApp = false;
   }, 2000);
  }

 };

 // Is there a page to go back to?
 if ($ionicHistory.backView()) {
  // Go back in history
  $ionicHistory.backView().go();
 } else {
  // This is the last page: Show confirmation popup
  showConfirm();
 }

 return false;
}, 101);
I'll always recommend the second option(the 
toast message method)

How to make some pages with tab and some pages without tabs in ionic?

IF you want some pages with tab and some pages without tab in ionic then

first you've to define the tab state(setup an abstract state for the tabs directive), like :

.state('tab', {
 url : "/tab",
 abstract : true,
 templateUrl : "templates/tabs.html",
})

after this if you want to define a state with tab then you can write like:

.state('tab.home', {
 url : '/home',
 views : {
  'tab-home' : {
   templateUrl : 'templates/tab-home.html',
   controller : 'homeCtrl',
  }
 }
})

if you want to define a state without tab then you can write like:

.state('withouttabs', {
 url : '/withouttabs',
 templateUrl : 'templates/withouttabs.html',
 controller : 'withouttabsCtrl',
})

Fire a event when device is online and offline or internet connect and disconnect

You can easily identify and fire a event or call a function when your device internet connect or disconnect, the function will automatically called. Modify  your app.js as below (write this code into $ionicPlatform.ready function):



document.addEventListener("online", function(){
 // fun(); this will call when device connect to internet
}, false);
document.addEventListener("offline", function(){
 // fun(); this will call when device disconnect to internet
}, false);

What is ionic?

Ionic is a framework of PhoneGap which is based on AngularJS and very popular or we can say most popular framework of mobile development using PhoneGap. So basically we can say that Ionic is a angular based framework for mobile development. Using Ionic you can manage API access very well , manage app designs, create app very fast and many more. If you've good knowledge about ionic then you can make a simple app with in few hours(I'm only talking about simple app).
As I told in first that Ionic is based on the AngularJs, you must have to good knowledge of AngularJS. CSS and HTML is the heart of PhoneGap development, so you must have to great knowledge about these. Ionic also provides you CSS file (which is build on SCSS), If you have knowledge about SCSS the it's great and if not then don't worry, you can manage all things by CSS. Ionic also provides some HTML custom tags like : ion-slide-box, ion-slide, ion-content, ion-view, ion-header-bar, ion-footer bar and many more, you can directly use them, these tags are for special purpose, so you must have to read about that.
As I told you at first that it's most popular framework of PhoneGap so if you are working on PhoneGap or planning to work on PhoneGap then you must have to go with this.On internet this is a lot of content/support available for ionic development and most plugins of PhoneGap are available for ionic(the plugin js file customized for ionic), so you can directly used them or if any plugin not available for ionic, you can directly use PhoneGap plugins but you have to apply some extra efforts for this.