Monday, 6 July 2015

Android push notification - Send notification to google when message received


Android push notification api in PHP


Question: What is Push Notification in Android?
Push notifications let your application notify a user of new messages or events even when the user is Offline.


Question: How to get to know Push Notification in Android?
In Android devices, when a device receives a push notification, your application's icon and a message appear in the status bar.


Question: What are basic steps to implements push notifiction in Android Application?
  1. Registering for the Push Service
  2. Application must have the permissions to receive pushes and show notifications.
  3. Choose Your Push Icon
  4. Add your Parse API keys Parse.initialize(this, "YOUR_APP_ID", "YOUR_CLIENT_KEY");
  5. Enable Push Notifications in Mobile


PHP script for send notification to google services when event/message received so that notification start showing on user device.
 // Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$registrationIDs = array('Mobile Device Id1','Mobile Device Id3','Mobile Device Id3');
$message='message_received';
$apiKey='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$fields = array(
    'registration_ids' => $registrationIDs,
    'data' => array( "message" => $message ),
);
$headers = array(
    'Authorization: key=' . $apiKey,
    'Content-Type: application/json'
);

// Open connection
$ch = curl_init();

// Set the URL, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url);
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));
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);