2014년 8월 10일 일요일

[추천1]Android push notification using GCM, google cloud messaging, google play service library PHP

This tutorial is about new android push notification using GCM. Android Push notification is the service provided by GCM. Old  c2dm and “google cloud messaging for android library” is depreciated as of now.Now it is recommended to implement google cloud messaging(GCM) using google play services library.
Note : – In the end of the tutorial you can find a download link for this GCM project (server side as well as android application) , a video tutorial for GCM theory and second part of push notification using GCM tutorial.
Setting up GCM
google-console-api-cloud-messaging-GCM
  •  open the google api console page and click on create project.
  • Go to Google Cloud Messaging for Android and set its status as ON.
  • Get the Project Number, which will be used as sender id.
  • Go to API access and get the API key.
Installing Play service
In eclipse go to Window and then Android SDK Manager. Scroll down and install Google Play Services.
android-play-service-sdk-for-GCM
After downloading google play service, new folder will be created inside your android sdk folder and you need to import .
Adding google play library project into eclipse workspace
After sucessfull installation, go to the location where Android SDK is installed on your computer.
sdk\extras\google\google_play_services\libproject
Now copy the google-play-services_lib folder to desktop.
google-play-service-sdk-path
Now we will import this library into eclipse workspace. Again go back to eclipse.
File -> Import -> Android -> Existing Android Code into workspace
choose the project -> Select copy projects into working sets ->
click next or finish

Creating a new Android push notification using GCM application project

For using android push notifications in your project u need to add the play service library. So, create a new project and right click on it. Go to properties, then go to Android. Select “Add”  which is inside library form and select “google-play-services_lib” and click “ok ” and then “apply”. Now all stuff is set up, I know setting up the project is annoying part, but we have to do this if we want to implement our code. Now lets get going towards implementation.
Connecting android device to GCM and receiving registration id.
 Explanation
  • EXTRA_MASSAGE is used for debugging.
  • registration_id will be storing the id with which android device gets register with GCM.
  • SENDER_ID is the project number, which you get from google code website.

public static final String EXTRA_MESSAGE = "message"; 
public static final String PROPERTY_REG_ID = "registration_id"; 
String SENDER_ID = "538459826415";
  • gcm is an instance of GoogleCloudMessaging, which provides access to google cloud.
  • TextView will display register id of device in user interface and “regid” is a string holding device registation id.
  • Context tells about the current state of the application. We call it to get information about our application, for example when we are working with background thread we use context.
static final String TAG = "GCMDemo";
    GoogleCloudMessaging gcm;
    TextView mDisplay;
    String regid;
    Context context;
//onCreate method starts
    context = getApplicationContext();
Now we will get instance from GoogleCloudMessaging and assign it to gcm. And we will call RegisterBackground, which is our AsyncTask,helps to connect to google cloud using background thread.
gcm = GoogleCloudMessaging.getInstance(this);
new RegisterBackground().execute();
But why we want another thread.
Each android application runs in its own process and in one single thread which is called Main thread or UI thread. Any operation which is heavy or which will block our main thread, should be implemented in a separate thread. For example Networking is a blocking operation. Here we are receiving data from internet that’s why we are implementing in background thread. I hope things are getting much clear now. Is it ?
AsynchTask helps us to implement a background thread.  It has few methods,which you can override. “doInBackground” is the method which will be having the main code. “onPostExecute” will contain stuff to update the data on TextView, which we have received from internet.
@Override
protected String doInBackground(String... arg0){
}
@Override
protected void onPostExecute(String msg) {
}
  •  context represents our application.
  • register method is used to register the device.
  • Log class is used for debugging.
String msg = "";
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Dvice registered, registration ID=" + regid;
Log.d("111", msg);
Device will be registered and GCM server will be having the register id of device. Now we will send this registration id to our web server.
Here is the code which displays “device registration id”.
Registration with GCM using google play services
package com.techlovejump.gcm;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;

import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

 public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "registration_id";

    String SENDER_ID = "538459826415";

    static final String TAG = "GCMDemo";
    GoogleCloudMessaging gcm;

    TextView mDisplay;
    Context context;
    String regid;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  mDisplay = (TextView) findViewById(R.id.display);
  context = getApplicationContext();

   gcm = GoogleCloudMessaging.getInstance(this);

    new RegisterBackground().execute();   
  }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
 @Override
 protected void onResume(){
  super.onResume();

 }
 class RegisterBackground extends AsyncTask<String,String,String>{

  @Override
  protected String doInBackground(String... arg0) {
   // TODO Auto-generated method stub
   String msg = "";
   try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                msg = "Dvice registered, registration ID=" + regid;
                Log.d("111", msg);
                sendRegistrationIdToBackend(regid);

            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return msg;
        }

  @Override
        protected void onPostExecute(String msg) {
            mDisplay.append(msg + "\n");

        }
  private void sendRegistrationIdToBackend(String regid) {
                  // this code will send registration id of a device to our own server.
}}
}
Make sure to add following entry in Android manifest file. To see the complete manifest file, kindly go to second part of Android push notification using GCM tutorial.
<meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
Now let us Implement sendRegistrationIdToBackend() method.
Sending android device registration Id to our server
Explanation
In this method we will use HTTP to send our data to our server. If you want to learn about HTTP and JSON parsing ,then please go to android HTTP and json parsing tutorial.
 private void sendRegistrationIdToBackend(String regid) {

   String url = "http://www.yourwebsitename.com/getregistrationid.php";
   List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("regid", regid));
           DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            try {
    httpPost.setEntity(new UrlEncodedFormEntity(params));
   } catch (UnsupportedEncodingException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }

            try {
    HttpResponse httpResponse = httpClient.execute(httpPost);
   } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }         

}
Receiving the android device registeration id  on server
getdevice.php - is a php script to receive the id from device so  that we can save it in our mysql database.
<?php
 $id = $_POST["regid"];
 $con = mysql_connect("localhost","username","password");
 mysql_select_db("database_name",$con);
 // change the query depending on your table
 mysql_query("INSERT INTO gcmreguser VALUES('".$id."')");

?>
Implementing Server side using php
Next in this android gcm tutorial we need to create a php script , which will be used to send the data from our server to GCM using CURL. Then we will implement a broadcast receiver and intent-service to receive the data from GCM. After that we will display our data as a notification. Then we will create one more activity to display data using json parser.
If you need to buy web hosting and domain name for your android GCM application to host php  you can check list of best web hosting india providers.

Explanation

  • api_key  holds the key which we have got from google console api.
  • registrationIDs is an array which will be storing the registration id of android devices on which you want to send the message.
  • message variable stores the string which we want to send.
  • fields is an associative array which will be storing the registration id’s and the data which is to be send.
  • headers will store the api key which we have got from google console api. It will also tell that our php script is sending json data.
Now, the communication between GCM and our server will be done using curl. curl is a command line tool for transferring data with URL syntax. Now let us see, Steps for setting up curl.
  1. create a new curl resource using curl_init().
  2. We will set the URL.
  3. CURL_POST means that the packet will be sent via HTTP POST.
  4. CURLOPT_RETURNTRANSFER helps us to get the result back to our server.
  5. CURLOPT_POSTFIELDS sets the data which we are sending through HTTP POST.

<?php
 $api_key = "AIzBpx4XbXwKd8P-v2d1Jk";
 $registrationIDs = array("APA91b3Rjlo8T_URx15NqvxY2mRyQ");
 $message = "congratulations";
 $url = 'https://android.googleapis.com/gcm/send';
 $fields = array(
                'registration_ids'  => $registrationIDs,
                'data'              => array( "message" => $message ),
                );

 $headers = array(
     'Authorization: key=' . $api_key,
     'Content-Type: application/json');

 $ch = curl_init();
 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_POSTFIELDS, json_encode( $fields ) );
 $result = curl_exec($ch);
 curl_close($ch);

echo $result;
?>

Now let us see how to process the notification received from GCM on android device.
Second Part – implementing broadcast receiver and intent-service to receive json from GCM

Download Android push notification using GCM and server side in php

How GCM works (theory)

Feel free to post, if you have any errors or suggestions.




댓글 없음:

댓글 쓰기