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

}])