如何在android(GCM)中发送/接收远程通知

如何在android(GCM)中发送/接收远程通知,android,push-notification,google-cloud-messaging,Android,Push Notification,Google Cloud Messaging,我已成功注册gcm。但未能接收任何通知。 请帮忙。 提前感谢……:) } 主要活动 公共类MainActivity扩展了ActionBarActivity{ TextView lblMessage; Controller aController; // Asyntask AsyncTask<Void, Void, Void> mRegisterTask; public static String name; public static String email; @Overri

我已成功注册gcm。但未能接收任何通知。 请帮忙。 提前感谢……:)

}

主要活动

公共类MainActivity扩展了ActionBarActivity{

TextView lblMessage;
Controller aController;

// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;

public static String name;
public static String email;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

  //Get Global Controller Class object (see application tag in AndroidManifest.xml)
    aController = (Controller) getApplicationContext();


    // Check if Internet present
    if (!aController.isConnectingToInternet()) {

        // Internet Connection is not present
        aController.showAlertDialog(MainActivity.this,
                "Internet Connection Error",
                "Please connect to Internet connection", false);
        // stop executing code by return
        return;
    }

    // Getting name, email from intent
    Intent i = getIntent();

    name = i.getStringExtra("name");
    email = i.getStringExtra("email");      

    // Make sure the device has the proper dependencies.
    GCMRegistrar.checkDevice(this);

    // Make sure the manifest permissions was properly set 
    GCMRegistrar.checkManifest(this);

    lblMessage = (TextView) findViewById(R.id.lblMessage);

    // Register custom Broadcast receiver to show messages on activity
    registerReceiver(mHandleMessageReceiver, new IntentFilter(
            Config.DISPLAY_MESSAGE_ACTION));

    // Get GCM registration id
    final String regId = GCMRegistrar.getRegistrationId(this);

    // Check if regid already presents
    if (regId.equals("")) {

        // Register with GCM            
        GCMRegistrar.register(this, Config.GOOGLE_SENDER_ID);

    } else {

        // Device is already registered on GCM Server
        if (GCMRegistrar.isRegisteredOnServer(this)) {

            // Skips registration.              
            Toast.makeText(getApplicationContext(), 
                          "Already registered with GCM Server", 
                          Toast.LENGTH_LONG).
                          show();

        } else {

            // Try to register again, but not in the UI thread.
            // It's also necessary to cancel the thread onDestroy(),
            // hence the use of AsyncTask instead of a raw thread.

            final Context context = this;
            mRegisterTask = new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void... params) {

                    // Register on our server
                    // On server creates a new user
                    aController.register(context, name, email, regId);

                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    mRegisterTask = null;
                }

            };

            // execute AsyncTask
            mRegisterTask.execute(null, null, null);
        }
    }

}
TextView-lblMessage;
控制器;控制器;
//阿森塔克
异步任务mRegisterTask;
公共静态字符串名;
公共静态字符串电子邮件;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取全局控制器类对象(请参阅AndroidManifest.xml中的应用程序标记)
a控制器=(控制器)getApplicationContext();
//检查互联网是否存在
如果(!aController.isConnectingToInternet()){
//Internet连接不存在
aController.showAlertDialog(MainActivity.this,
“Internet连接错误”,
“请连接到Internet连接”,错误);
//通过返回停止执行代码
返回;
}
//从intent获取姓名、电子邮件
Intent i=getIntent();
名称=i.getStringExtra(“名称”);
email=i.getStringExtra(“电子邮件”);
//确保设备具有正确的依赖项。
GCMRegistar.检查装置(本);
//确保清单权限设置正确
GCMRegistar.检查清单(本);
lblMessage=(TextView)findViewById(R.id.lblMessage);
//注册自定义广播接收器以显示活动中的消息
registerReceiver(mHandleMessageReceiver,新意向过滤器(
配置显示(信息(动作));
//获取GCM注册id
最终字符串regId=gcmregistar.getRegistrationId(this);
//检查regid是否已出现
if(regId.equals(“”){
//向GCM注册
gcmregistar.register(这个,Config.GOOGLE\u SENDER\u ID);
}否则{
//设备已在GCM服务器上注册
if(GCMRegistrar.isRegisteredOnServer(本)){
//跳过注册。
Toast.makeText(getApplicationContext(),
“已向GCM服务器注册”,
吐司。长度(长)。
show();
}否则{
//尝试再次注册,但不要在UI线程中注册。
//还需要取消onDestroy()线程,
//因此,使用AsyncTask而不是原始线程。
最终上下文=此;
mRegisterTask=newasynctask(){
@凌驾
受保护的Void doInBackground(Void…参数){
//在我们的服务器上注册
//在服务器上创建新用户
a控制器。注册(上下文、名称、电子邮件、注册号);
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
mRegisterTask=null;
}
};
//执行异步任务
mRegisterTask.execute(null,null,null);
}
}
}
//创建广播接收器以获取信息并在屏幕上显示 专用最终广播接收器mHandleMessageReceiver=新广播接收器(){

@覆盖
公共void onReceive(上下文、意图){
String newMessage=intent.getExtras().getString(Config.EXTRA_MESSAGE);
//在手机处于睡眠状态时唤醒手机
aController.acquireWakeLock(getApplicationContext());
//在屏幕上显示消息
lblMessage.append(newMessage+“”);
Toast.makeText(getApplicationContext(),
“收到消息:”+newMessage,
Toast.LENGTH_LONG).show();
//释放尾流锁
a控制器。释放WakeLock();
}
};
单文件
send_message.php
遵循以下步骤:

第一步。 在你的主要活动中称之为:

class GCMReg extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {

        try {
            Log.e("testing", "yes i am calling");
            GCMRegistrar.checkDevice(Home.this);
            GCMRegistrar.checkManifest(Home.this);
            GCMRegistrar.register(Home.this, GCMIntentService.SENDER_ID);

        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        super.onPostExecute(result);

    }
}
GCMReg类扩展了异步任务{
@凌驾
受保护的Void doInBackground(Void…参数){
试一试{
Log.e(“测试”,“是的,我在打电话”);
gcmregistar.checkDevice(Home.this);
gcmregistar.checkManifest(Home.this);
gcmregistar.register(Home.this、gcminentservice.SENDER\u ID);
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
super.onPostExecute(结果);
}
}
第二步。 在项目中创建此类并检查它。 gcminentservice.java

public class GCMIntentService extends GCMBaseIntentService {
public static final String SENDER_ID = "GCM ID";
public static String message;
String gcmRecData, status;
ComponentName cn;
int AllTimeLength = 0;
boolean updateList = false;

public GCMIntentService() {
    super(SENDER_ID);
}

@Override
protected void onRegistered(Context context, String registrationId) {
    Log.e("testing", "onRegistered: registrationId=" + registrationId);
    String urlToUpdateId;
    urlToUpdateId = "enter your url for update token";

    new updateId(context).execute(urlToUpdateId);

}

@Override
protected void onUnregistered(Context context, String registrationId) {
}

@Override
protected void onMessage(final Context context, Intent data) {
    // Message from PHP server

    gcmRecData = data.getStringExtra("message");

    Log.e("test", "message :- " + gcmRecData);
    // try {
    // JSONParser jParser = new JSONParser();
    // String json = jParser.getJSONFromUrl(gcmRecData);
    // JSONObject jobject = new JSONObject(gcmRecData);
    message = gcmRecData;
    // BuildNotification(new Intent(context, Home.class), context);
    // } catch (JSONException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    BuildNotification(new Intent(context, Foregound.class), context);

    // try {
    // XMLParser xp = new XMLParser();
    // Document doc = xp.getDomElement(gcmRecData);
    // NodeList nl = doc.getElementsByTagName("response");
    // for (int i = 0; i < nl.getLength(); i++) {
    // Element e = (Element) nl.item(i);
    // message = xp.getValue(e, "message");
    // BuildNotification(new Intent(context, Home.class), context);
    //
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }

}

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public void BuildNotification(Intent it, Context context) {
    Log.i("GCM INtent  ", "" + "Build");
    // if (context.getPackageName()
    // .equalsIgnoreCase(
    // ((ActivityManager) GCMIntentService.this
    // .getSystemService(Context.ACTIVITY_SERVICE))
    // .getRunningTasks(1).get(0).topActivity
    // .getPackageName())) {
    //
    // } else {
    PendingIntent pIntent = PendingIntent.getActivity(context, 0, it,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Uri soundUri = RingtoneManager
            .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    Notification notification = new Notification.Builder(context)
            .setSound(soundUri).setSmallIcon(R.drawable.appicon)
            .setWhen(System.currentTimeMillis())
            .setContentTitle("Byrchall High School")

            .setContentText(message).setContentIntent(pIntent)

            .getNotification();

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(R.string.app_name, notification);
    {
        // Wake Android Device when notification received
        PowerManager pm = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
        @SuppressWarnings("deprecation")
        final PowerManager.WakeLock mWakelock = pm.newWakeLock(
                PowerManager.FULL_WAKE_LOCK
                        | PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
        mWakelock.acquire();

        // Timer before putting Android Device to sleep mode.
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            public void run() {
                mWakelock.release();
            }
        };
        timer.schedule(task, 5000);
        // }
    }
}

@Override
protected void onError(Context arg0, String errorId) {
    Log.e("testing", "onError: errorId=" + errorId);
}
}

class updateId extends AsyncTask<String, Void, Void> {
Context context;

public updateId(Context c) {
    context = c;
}

@Override
protected Void doInBackground(String... params) {
    try {
        JSONParser p = new JSONParser();
        String response = p.getJSONFromUrl(params[0]);
        Log.e("test", "response :- " + response);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService{
    private static final String TAG = "GCMIntentService";

    private Controller aController = null;

    public GCMIntentService() {
        // Call extended class Constructor GCMBaseIntentService
        super(Config.GOOGLE_SENDER_ID);
    }

    @Override
    protected void onError(Context arg0, String arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onMessage(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if(aController == null)
            aController = (Controller) getApplicationContext();

        String message = intent.getExtras().getString("message");
        Log.i(TAG, "Received message");
        aController.displayMessageOnScreen(context, message);
        // notifies user
        generateNotification(context, message);
    }

    @Override
    protected void onRegistered(Context context, String registrationId) {
        // TODO Auto-generated method stub
        //Get Global Controller Class object (see application tag in AndroidManifest.xml)
        if(aController == null)
           aController = (Controller) getApplicationContext();

        Log.i(TAG, "Device registered: regId = " + registrationId);
        System.out.println(registrationId);
        aController.displayMessageOnScreen(context, 
                                           "Your device registred with GCM");
        Log.d("NAME", MainActivity.name);
        aController.register(context, MainActivity.name, 
                               MainActivity.email, registrationId);
    }

    @Override
    protected void onUnregistered(Context arg0, String arg1) {
        // TODO Auto-generated method stub
        if(aController == null)
            aController = (Controller) getApplicationContext();
        Log.i(TAG, "Device unregistered");
        aController.displayMessageOnScreen(arg0, 
                                            getString(R.string.gcm_unregistered));
        aController.unregister(arg0, arg1);
    }

    /**
     * Create a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message) {

        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();

        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notifi = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);

        Intent notificationIntent = new Intent(context, MainActivity.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent =
                PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notifi.setLatestEventInfo(context, title, message, intent);
        notifi.flags |= Notification.FLAG_AUTO_CANCEL;

        // Play default notification sound
        notifi.defaults |= Notification.DEFAULT_SOUND;

        // Vibrate if vibrate is enabled
        notifi.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notifi);      
    }
}
公共类gcminentservice扩展了GCMBaseIntentService{
公共静态最终字符串发送者\u ID=“GCM ID”;
公共静态字符串消息;
字符串gcmRecData,状态;
组件名称cn;
int-AllTimeLength=0;
布尔更新列表=false;
公共GCMinentService(){
超级(发送者身份证);
}
@凌驾
受保护的void onRegistered(上下文、字符串注册ID){
Log.e(“测试”,“onRegistered:registrationId=“+registrationId”);
字符串urlToUpdateId;
urlToUpdateId=“输入更新令牌的url”;
新建updateId(context).execute(urlToUpdateId);
}
@凌驾
未注册受保护的void(上下文、字符串注册ID){
}
@凌驾
受保护的void onMessage(最终上下文、意图数据){
//来自PHP服务器的消息
gcmRecData=data.getStringExtra(“消息”);
Log.e(“测试”,“消息:-”+gcmRecData);
//试一试{
//JSONParser jParser=新的JSONParser();
//字符串json=jParser.getJSONFromUrl(gcmRecData);
//JSONObject jobject=新的JSONObject(gcmRecData);
消息=gcmRecData;
//BuildNotification(新意图(context,Home.class),context);
//}catch(JSONException e){
////TODO自动生成的捕捉块
//e.printStackTrace();
// }
BuildNotification(新意图(context,Foregound.class),context);
//试一试
public class GCMIntentService extends GCMBaseIntentService {
public static final String SENDER_ID = "GCM ID";
public static String message;
String gcmRecData, status;
ComponentName cn;
int AllTimeLength = 0;
boolean updateList = false;

public GCMIntentService() {
    super(SENDER_ID);
}

@Override
protected void onRegistered(Context context, String registrationId) {
    Log.e("testing", "onRegistered: registrationId=" + registrationId);
    String urlToUpdateId;
    urlToUpdateId = "enter your url for update token";

    new updateId(context).execute(urlToUpdateId);

}

@Override
protected void onUnregistered(Context context, String registrationId) {
}

@Override
protected void onMessage(final Context context, Intent data) {
    // Message from PHP server

    gcmRecData = data.getStringExtra("message");

    Log.e("test", "message :- " + gcmRecData);
    // try {
    // JSONParser jParser = new JSONParser();
    // String json = jParser.getJSONFromUrl(gcmRecData);
    // JSONObject jobject = new JSONObject(gcmRecData);
    message = gcmRecData;
    // BuildNotification(new Intent(context, Home.class), context);
    // } catch (JSONException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    BuildNotification(new Intent(context, Foregound.class), context);

    // try {
    // XMLParser xp = new XMLParser();
    // Document doc = xp.getDomElement(gcmRecData);
    // NodeList nl = doc.getElementsByTagName("response");
    // for (int i = 0; i < nl.getLength(); i++) {
    // Element e = (Element) nl.item(i);
    // message = xp.getValue(e, "message");
    // BuildNotification(new Intent(context, Home.class), context);
    //
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }

}

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public void BuildNotification(Intent it, Context context) {
    Log.i("GCM INtent  ", "" + "Build");
    // if (context.getPackageName()
    // .equalsIgnoreCase(
    // ((ActivityManager) GCMIntentService.this
    // .getSystemService(Context.ACTIVITY_SERVICE))
    // .getRunningTasks(1).get(0).topActivity
    // .getPackageName())) {
    //
    // } else {
    PendingIntent pIntent = PendingIntent.getActivity(context, 0, it,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Uri soundUri = RingtoneManager
            .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    Notification notification = new Notification.Builder(context)
            .setSound(soundUri).setSmallIcon(R.drawable.appicon)
            .setWhen(System.currentTimeMillis())
            .setContentTitle("Byrchall High School")

            .setContentText(message).setContentIntent(pIntent)

            .getNotification();

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(R.string.app_name, notification);
    {
        // Wake Android Device when notification received
        PowerManager pm = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
        @SuppressWarnings("deprecation")
        final PowerManager.WakeLock mWakelock = pm.newWakeLock(
                PowerManager.FULL_WAKE_LOCK
                        | PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
        mWakelock.acquire();

        // Timer before putting Android Device to sleep mode.
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            public void run() {
                mWakelock.release();
            }
        };
        timer.schedule(task, 5000);
        // }
    }
}

@Override
protected void onError(Context arg0, String errorId) {
    Log.e("testing", "onError: errorId=" + errorId);
}
}

class updateId extends AsyncTask<String, Void, Void> {
Context context;

public updateId(Context c) {
    context = c;
}

@Override
protected Void doInBackground(String... params) {
    try {
        JSONParser p = new JSONParser();
        String response = p.getJSONFromUrl(params[0]);
        Log.e("test", "response :- " + response);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
public class Controller extends Application{
    private  final int MAX_ATTEMPTS = 5;
    private  final int BACKOFF_MILLI_SECONDS = 2000;
    private  final Random random = new Random();


     // Register this account with the server.
    void register(final Context context, String name, String email, final String regId) {

        Log.i(Config.TAG, "registering device (regId = " + regId + ")");

        String serverUrl = Config.YOUR_SERVER_URL;

        Map<String, String> params = new HashMap<String, String>();
        params.put("regId", regId);
        params.put("name", name);
        params.put("email", email);

        long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);

        // Once GCM returns a registration id, we need to register on our server
        // As the server might be down, we will retry it a couple
        // times.
        for (int i = 1; i <= MAX_ATTEMPTS; i++) {

            Log.d(Config.TAG, "Attempt #" + i + " to register");

            try {
                //Send Broadcast to Show message on screen
                displayMessageOnScreen(context, context.getString(
                        R.string.server_registered, i, MAX_ATTEMPTS));

                // Post registration values to web server
                post(serverUrl, params);

                GCMRegistrar.setRegisteredOnServer(context, true);

                //Send Broadcast to Show message on screen
                String message = context.getString(R.string.server_registered);
                displayMessageOnScreen(context, message);

                return;
            } catch (IOException e) {

                // Here we are simplifying and retrying on any error; in a real
                // application, it should retry only on unrecoverable errors
                // (like HTTP error code 503).

                Log.e(Config.TAG, "Failed to register on attempt " + i + ":" + e);

                if (i == MAX_ATTEMPTS) {
                    break;
                }
                try {

                    Log.d(Config.TAG, "Sleeping for " + backoff + " ms before retry");
                    Thread.sleep(backoff);

                } catch (InterruptedException e1) {
                    // Activity finished before we complete - exit.
                    Log.d(Config.TAG, "Thread interrupted: abort remaining retries!");
                    Thread.currentThread().interrupt();
                    return;
                }

                // increase backoff exponentially
                backoff *= 2;
            }
        }

        String message = context.getString(R.string.server_register_error,
                MAX_ATTEMPTS);

        //Send Broadcast to Show message on screen
        displayMessageOnScreen(context, message);
    }

     // Unregister this account/device pair within the server.
     void unregister(final Context context, final String regId) {

        Log.i(Config.TAG, "unregistering device (regId = " + regId + ")");

        String serverUrl = Config.YOUR_SERVER_URL + "/unregister";
        Map<String, String> params = new HashMap<String, String>();
        params.put("regId", regId);

        try {
            post(serverUrl, params);
            GCMRegistrar.setRegisteredOnServer(context, false);
            String message = context.getString(R.string.server_unregistered);
            displayMessageOnScreen(context, message);
        } catch (IOException e) {

            // At this point the device is unregistered from GCM, but still
            // registered in the our server.
            // We could try to unregister again, but it is not necessary:
            // if the server tries to send a message to the device, it will get
            // a "NotRegistered" error message and should unregister the device.

            String message = context.getString(R.string.server_unregister_error,
                    e.getMessage());
            displayMessageOnScreen(context, message);
        }
    }

    // Issue a POST request to the server.
    private static void post(String endpoint, Map<String, String> params)
            throws IOException {    

        URL url;
        try {

            url = new URL(endpoint);

        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }

        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();

        // constructs the POST body using the parameters
        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                bodyBuilder.append('&');
            }
        }

        String body = bodyBuilder.toString();

        Log.v(Config.TAG, "Posting '" + body + "' to " + url);

        byte[] bytes = body.getBytes();

        HttpURLConnection conn = null;
        try {

            Log.e("URL", "> " + url);

            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();

            // handle the response
            int status = conn.getResponseCode();

            // If response is not success
            if (status != 200) {

              throw new IOException("Post failed with error code " + status);
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
      }

    // Checking for all possible internet providers
    public boolean isConnectingToInternet(){

        ConnectivityManager connectivity = 
                             (ConnectivityManager) getSystemService(
                              Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
          }
          return false;
    }

   // Notifies UI to display a message.
   void displayMessageOnScreen(Context context, String message) {

        Intent intent = new Intent(Config.DISPLAY_MESSAGE_ACTION);
        intent.putExtra(Config.EXTRA_MESSAGE, message);
 // Send Broadcast to Broadcast receiver with message
        context.sendBroadcast(intent);

    }

   //Function to display simple Alert Dialog
   public void showAlertDialog(Context context, String title, String message,
            Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Set Dialog Title
        alertDialog.setTitle(title);

        // Set Dialog Message
        alertDialog.setMessage(message);

        if(status != null)
            // Set alert dialog icon
            alertDialog.setIcon((status) ? R.drawable.ic_launcher : R.id.search_mag_icon);

        // Set OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        // Show Alert Message
        alertDialog.show();
    }

    private PowerManager.WakeLock wakeLock;

    public  void acquireWakeLock(Context context) {
        if (wakeLock != null) wakeLock.release();

        PowerManager pm = (PowerManager) 
                          context.getSystemService(Context.POWER_SERVICE);

        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
                PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.ON_AFTER_RELEASE, "WakeLock");

        wakeLock.acquire();
    }

    public  void releaseWakeLock() {
        if (wakeLock != null) wakeLock.release(); wakeLock = null;
    }
}
import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService{
    private static final String TAG = "GCMIntentService";

    private Controller aController = null;

    public GCMIntentService() {
        // Call extended class Constructor GCMBaseIntentService
        super(Config.GOOGLE_SENDER_ID);
    }

    @Override
    protected void onError(Context arg0, String arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onMessage(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if(aController == null)
            aController = (Controller) getApplicationContext();

        String message = intent.getExtras().getString("message");
        Log.i(TAG, "Received message");
        aController.displayMessageOnScreen(context, message);
        // notifies user
        generateNotification(context, message);
    }

    @Override
    protected void onRegistered(Context context, String registrationId) {
        // TODO Auto-generated method stub
        //Get Global Controller Class object (see application tag in AndroidManifest.xml)
        if(aController == null)
           aController = (Controller) getApplicationContext();

        Log.i(TAG, "Device registered: regId = " + registrationId);
        System.out.println(registrationId);
        aController.displayMessageOnScreen(context, 
                                           "Your device registred with GCM");
        Log.d("NAME", MainActivity.name);
        aController.register(context, MainActivity.name, 
                               MainActivity.email, registrationId);
    }

    @Override
    protected void onUnregistered(Context arg0, String arg1) {
        // TODO Auto-generated method stub
        if(aController == null)
            aController = (Controller) getApplicationContext();
        Log.i(TAG, "Device unregistered");
        aController.displayMessageOnScreen(arg0, 
                                            getString(R.string.gcm_unregistered));
        aController.unregister(arg0, arg1);
    }

    /**
     * Create a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message) {

        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();

        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notifi = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);

        Intent notificationIntent = new Intent(context, MainActivity.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent =
                PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notifi.setLatestEventInfo(context, title, message, intent);
        notifi.flags |= Notification.FLAG_AUTO_CANCEL;

        // Play default notification sound
        notifi.defaults |= Notification.DEFAULT_SOUND;

        // Vibrate if vibrate is enabled
        notifi.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notifi);      
    }
}
public interface Config {
    // CONSTANTS
    static final String YOUR_SERVER_URL =  
                          "https://yourserveraddress/gcm/register.php";

    // Google project id
    static final String GOOGLE_SENDER_ID = "123456789101"; //Your Project Number

    /**
     * Tag used on log messages.
     */
    static final String TAG = "GCM Android Example";

    static final String DISPLAY_MESSAGE_ACTION =
            "com.yourpackagename.DISPLAY_MESSAGE";

    static final String EXTRA_MESSAGE = "message";
}

These are two activity
RegisterActivity.java
public class RegisterActivty extends Activity {
    EditText txtName; 
    EditText txtEmail;

    // Register button
    Button btnRegister;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        //Get Global Controller Class object (see application tag in AndroidManifest.xml)
        final Controller aController = (Controller) getApplicationContext();

        // Check if Internet Connection present
        if (!aController.isConnectingToInternet()) {

            // Internet Connection is not present
            aController.showAlertDialog(RegisterActivty.this,
                    "Internet Connection Error",
                    "Please connect to working Internet connection", false);

            // stop executing code by return
            return;
        }

        // Check if GCM configuration is set
        if (Config.YOUR_SERVER_URL == null
            || Config.GOOGLE_SENDER_ID == null
            || Config.YOUR_SERVER_URL.length() == 0
            || Config.GOOGLE_SENDER_ID.length() == 0) {

            // GCM sernder id / server url is missing
            aController.showAlertDialog(RegisterActivty.this, "Configuration Error!",
                    "Please set your Server URL and GCM Sender ID", false);
            // stop executing code by return
             return;
        }
        txtName = (EditText) findViewById(R.id.txtName);
        txtEmail = (EditText) findViewById(R.id.txtEmail);
        btnRegister = (Button) findViewById(R.id.btnRegister);

        // Click event on Register button
        btnRegister.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {  
                // Get data from EditText 
                String name = txtName.getText().toString(); 
                String email = txtEmail.getText().toString();

                // Check if user filled the form
                if(name.trim().length() > 0 && email.trim().length() > 0){

                    // Launch Main Activity
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);

                    // Registering user on our server                   
                    // Sending registraiton details to MainActivity
                    i.putExtra("name", name);
                    i.putExtra("email", email);
                    startActivity(i);
                    finish();
                }
            }
        });
    }
}


MainActivity.java

import com.google.android.gcm.GCMRegistrar;
public class MainActivity extends ActionBarActivity {

    TextView lblMessage;
    Controller aController;

    // Asyntask
    AsyncTask<Void, Void, Void> mRegisterTask;

    public static String name;
    public static String email;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

      //Get Global Controller Class object (see application tag in AndroidManifest.xml)
        aController = (Controller) getApplicationContext();

        // Check if Internet present
        if (!aController.isConnectingToInternet()) {

            // Internet Connection is not present
            aController.showAlertDialog(MainActivity.this,
                    "Internet Connection Error",
                    "Please connect to Internet connection", false);
            // stop executing code by return
            return;
        }

        // Getting name, email from intent
        Intent i = getIntent();

        name = i.getStringExtra("name");
        email = i.getStringExtra("email");      

        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(this);

        // Make sure the manifest permissions was properly set 
        GCMRegistrar.checkManifest(this);

        lblMessage = (TextView) findViewById(R.id.lblMessage);

        // Register custom Broadcast receiver to show messages on activity
        registerReceiver(mHandleMessageReceiver, new IntentFilter(
                Config.DISPLAY_MESSAGE_ACTION));

        // Get GCM registration id
        final String regId = GCMRegistrar.getRegistrationId(this);

        // Check if regid already presents
        if (regId.equals("")) {

            // Register with GCM            
            GCMRegistrar.register(this, Config.GOOGLE_SENDER_ID);

        } else {

            // Device is already registered on GCM Server
            if (GCMRegistrar.isRegisteredOnServer(this)) {

                // Skips registration.              
                Toast.makeText(getApplicationContext(), 
                              "Already registered with GCM Server", 
                              Toast.LENGTH_LONG).
                              show();

            } else {

                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.

                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {

                        // Register on our server
                        // On server creates a new user
                        aController.register(context, name, email, regId);

                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }
                };
                // execute AsyncTask
                mRegisterTask.execute(null, null, null);
            }
        }
    }

 // Create a broadcast receiver to get message and show on screen 
    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            String newMessage = intent.getExtras().getString(Config.EXTRA_MESSAGE);

            // Waking up mobile if it is sleeping
            aController.acquireWakeLock(getApplicationContext());

            // Display message on the screen
            lblMessage.append(newMessage + "");         

            Toast.makeText(getApplicationContext(), 
                           "Got Message: " + newMessage, 
                           Toast.LENGTH_LONG).show();

            // Releasing wake lock
            aController.releaseWakeLock();
        }
    };
  }

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourpackagename"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    <permission
        android:name="com.example.yourpackagename.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.example.yourpackagename.permission.C2D_MESSAGE" />

    <!-- This app has permission to register and receive data message. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:name="com.example.yourpackagename.Controller"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >

        </activity>
        <activity android:name="RegisterActivty">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.google.android.gcm.GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>

                <!-- Receives the actual messages. -->
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <!-- Receives the registration id. -->
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.example.yourpackagename" />
            </intent-filter>
        </receiver>

        <service android:name="com.yourpackagename.GCMIntentService" />
    </application>

</manifest>