title: Not receiving push notifications in android
body: <p>Hi In My Application I used this site for sending push notification using gcm concept androidhive.info . I am testing in localhost to server that one its working fine and no of devices also it showing after detecting the emulator registration id and then sending notification.Now that details also stored in local database.</p>
  
  <p>Now My problem I am receiving any push notifications from server.</p>
  
  <p>can anyone please help me and reslove it</p>
  
  <p>AlertDialogManager.java:</p>
  
  <pre><code>public class AlertDialogManager {
  
      public void showAlertDialog(Context context, String title, String message,
              Boolean status) {
          AlertDialog alertDialog = new AlertDialog.Builder(context).create();
  
          // Setting Dialog Title
          alertDialog.setTitle(title);
  
          // Setting Dialog Message
          alertDialog.setMessage(message);
  
          if(status != null)
              // Setting alert dialog icon
              alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
  
          // Setting OK Button
          alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
              }
          });
  
          // Showing Alert Message
          alertDialog.show();
      }
  }
  </code></pre>
  
  <p>CommonUtilities.java</p>
  
  <pre><code>public final class CommonUtilities {
  
      // give your server registration url here
      static final String SERVER_URL = "http://10.0.2.2/gcm_server_php/register.php"; 
  
      // Google project id
      static final String SENDER_ID = "907381889394"; 
  
      static final String TAG = "AndroidHive GCM";
  
      static final String DISPLAY_MESSAGE_ACTION =
              "com.androidhive.pushnotifications.DISPLAY_MESSAGE";
  
      static final String EXTRA_MESSAGE = "message";
  
      static void displayMessage(Context context, String message) {
          Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
          intent.putExtra(EXTRA_MESSAGE, message);
          context.sendBroadcast(intent);
      }
  }
  </code></pre>
  
  <p>ConnectionDetector.java:</p>
  
  <pre><code>public class ConnectionDetector {
  
      private Context _context;
  
      public ConnectionDetector(Context context){
          this._context = context;
      }
  
      public boolean isConnectingToInternet(){
          ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null)
            {
                NetworkInfo[] info = connectivity.getAllNetworkInfo();
                if (info != null)
                    for (int i = 0; i &lt; info.length; i++)
                        if (info[i].getState() == NetworkInfo.State.CONNECTED)
                        {
                            return true;
                        }
  
            }
            return false;
      }
  }
  </code></pre>
  
  <p>GCMIntentService.java:</p>
  
  <pre><code>public class GCMIntentService extends GCMBaseIntentService {
  
      private static final String TAG = "GCMIntentService";
  
      public GCMIntentService() {
          super(SENDER_ID);
      }
  
      @Override
      protected void onRegistered(Context context, String registrationId) {
          Log.i(TAG, "Device registered: regId = " + registrationId);
          displayMessage(context, "Your device registred with GCM");
          Log.d("NAME", MainActivity.name);
          ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId);
      }
  
  
      @Override
      protected void onUnregistered(Context context, String registrationId) {
          Log.i(TAG, "Device unregistered");
          displayMessage(context, getString(R.string.gcm_unregistered));
          ServerUtilities.unregister(context, registrationId);
      }
  
  
      @Override
      protected void onMessage(Context context, Intent intent) {
          Log.i(TAG, "Received message");
          String message = intent.getExtras().getString("price");
  
          displayMessage(context, message);
          // notifies user
          generateNotification(context, message);
      }
  
  
      @Override
      protected void onDeletedMessages(Context context, int total) {
          Log.i(TAG, "Received deleted messages notification");
          String message = getString(R.string.gcm_deleted, total);
          displayMessage(context, message);
          // notifies user
          generateNotification(context, message);
      }
  
  
      @Override
      public void onError(Context context, String errorId) {
          Log.i(TAG, "Received error: " + errorId);
          displayMessage(context, getString(R.string.gcm_error, errorId));
      }
  
      @Override
      protected boolean onRecoverableError(Context context, String errorId) {
          // log message
          Log.i(TAG, "Received recoverable error: " + errorId);
          displayMessage(context, getString(R.string.gcm_recoverable_error,
                  errorId));
          return super.onRecoverableError(context, errorId);
      }
  
  
      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 notification = 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);
          notification.setLatestEventInfo(context, title, message, intent);
          notification.flags |= Notification.FLAG_AUTO_CANCEL;
  
          // Play default notification sound
          notification.defaults |= Notification.DEFAULT_SOUND;
  
          //notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
  
          // Vibrate if vibrate is enabled
          notification.defaults |= Notification.DEFAULT_VIBRATE;
          notificationManager.notify(0, notification);      
  
      }
  
  }
  </code></pre>
  
  <p>MainActivity.java:</p>
  
  <pre><code>public class MainActivity extends Activity {
      // label to display gcm messages
      TextView lblMessage;
  
      // Asyntask
      AsyncTask&lt;Void, Void, Void&gt; mRegisterTask;
  
      // Alert dialog manager
      AlertDialogManager alert = new AlertDialogManager();
  
      // Connection detector
      ConnectionDetector cd;
  
      public static String name;
      public static String email;
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          cd = new ConnectionDetector(getApplicationContext());
  
          // Check if Internet present
          if (!cd.isConnectingToInternet()) {
              // Internet Connection is not present
              alert.showAlertDialog(MainActivity.this,
                      "Internet Connection Error",
                      "Please connect to working 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 was properly set - comment out this line
          // while developing the app, then uncomment it when it's ready.
          GCMRegistrar.checkManifest(this);
  
          lblMessage = (TextView) findViewById(R.id.lblMessage);
  
          registerReceiver(mHandleMessageReceiver, new IntentFilter(
                  DISPLAY_MESSAGE_ACTION));
  
          // Get GCM registration id
          final String regId = GCMRegistrar.getRegistrationId(this);
  
          // Check if regid already presents
          if (regId.equals("")) {
              // Registration is not present, register now with GCM           
              GCMRegistrar.register(this, SENDER_ID);
          } else {
              // Device is already registered on GCM
              if (GCMRegistrar.isRegisteredOnServer(this)) {
                  // Skips registration.              
                  Toast.makeText(getApplicationContext(), "Already registered with GCM", 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&lt;Void, Void, Void&gt;() {
  
                      @Override
                      protected Void doInBackground(Void... params) {
                          // Register on our server
                          // On server creates a new user
                          ServerUtilities.register(context, name, email, regId);
                          return null;
                      }
  
                      @Override
                      protected void onPostExecute(Void result) {
                          mRegisterTask = null;
                      }
  
                  };
                  mRegisterTask.execute(null, null, null);
              }
          }
      }       
  
      private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
              String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
              // Waking up mobile if it is sleeping
              WakeLocker.acquire(getApplicationContext());
  
              /**
               * Take appropriate action on this message
               * depending upon your app requirement
               * For now i am just displaying it on the screen
               * */
  
              // Showing received message
              lblMessage.append(newMessage + "\n");           
              Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
  
              // Releasing wake lock
              WakeLocker.release();
          }
      };
  
      @Override
      protected void onDestroy() {
          if (mRegisterTask != null) {
              mRegisterTask.cancel(true);
          }
          try {
              unregisterReceiver(mHandleMessageReceiver);
              GCMRegistrar.onDestroy(this);
          } catch (Exception e) {
              Log.e("UnRegister Receiver Error", "&gt; " + e.getMessage());
          }
          super.onDestroy();
      }
  
  }
  </code></pre>
  
  <p>RegisterActivity.java:</p>
  
  <pre><code>public class RegisterActivity extends Activity {
      // alert dialog manager
      AlertDialogManager alert = new AlertDialogManager();
  
      // Internet detector
      ConnectionDetector cd;
  
      // UI elements
      EditText txtName;
      EditText txtEmail;
  
      // Register button
      Button btnRegister;
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_register);
  
          cd = new ConnectionDetector(getApplicationContext());
  
          // Check if Internet present
          if (!cd.isConnectingToInternet()) {
              // Internet Connection is not present
              alert.showAlertDialog(RegisterActivity.this,
                      "Internet Connection Error",
                      "Please connect to working Internet connection", false);
              // stop executing code by return
              return;
          }
  
          // Check if GCM configuration is set
          if (SERVER_URL == null || SENDER_ID == null || SERVER_URL.length() == 0
                  || SENDER_ID.length() == 0) {
              // GCM sernder id / server url is missing
              alert.showAlertDialog(RegisterActivity.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);
  
          btnRegister.setOnClickListener(new View.OnClickListener() {
  
              @Override
              public void onClick(View arg0) {
                  // Read EditText dat
                  String name = txtName.getText().toString();
                  String email = txtEmail.getText().toString();
  
                  // Check if user filled the form
                  if(name.trim().length() &gt; 0 &amp;&amp; email.trim().length() &gt; 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();
                  }else{
                      // user doen't filled that data
                      // ask him to fill the form
                      alert.showAlertDialog(RegisterActivity.this, "Registration Error!", "Please enter your details", false);
                  }
              }
          });
      }
  
  }
  public final class ServerUtilities {
      private static final int MAX_ATTEMPTS = 5;
      private static final int BACKOFF_MILLI_SECONDS = 2000;
      private static final Random random = new Random();
  
      static void register(final Context context, String name, String email, final String regId) {
          Log.i(TAG, "registering device (regId = " + regId + ")");
          String serverUrl = SERVER_URL;
          Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;();
          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 &lt;= MAX_ATTEMPTS; i++) {
              Log.d(TAG, "Attempt #" + i + " to register");
              try {
                  displayMessage(context, context.getString(
                          R.string.server_registering, i, MAX_ATTEMPTS));
                  post(serverUrl, params);
                  GCMRegistrar.setRegisteredOnServer(context, true);
                  String message = context.getString(R.string.server_registered);
                  CommonUtilities.displayMessage(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(TAG, "Failed to register on attempt " + i + ":" + e);
                  if (i == MAX_ATTEMPTS) {
                      break;
                  }
                  try {
                      Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
                      Thread.sleep(backoff);
                  } catch (InterruptedException e1) {
                      // Activity finished before we complete - exit.
                      Log.d(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);
          CommonUtilities.displayMessage(context, message);
      }
  
      static void unregister(final Context context, final String regId) {
          Log.i(TAG, "unregistering device (regId = " + regId + ")");
          String serverUrl = SERVER_URL + "/unregister";
          Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;();
          params.put("regId", regId);
          try {
              post(serverUrl, params);
              GCMRegistrar.setRegisteredOnServer(context, false);
              String message = context.getString(R.string.server_unregistered);
              CommonUtilities.displayMessage(context, message);
          } catch (IOException e) {
              // At this point the device is unregistered from GCM, but still
              // registered in the 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());
              CommonUtilities.displayMessage(context, message);
          }
      }
  
  
      private static void post(String endpoint, Map&lt;String, String&gt; params)
              throws IOException {    
  
          URL url;
          try {
              url = new URL(endpoint);
          } catch (MalformedURLException e) {
              throw new IllegalArgumentException("invalid url: " + endpoint);
          }
          StringBuilder bodyBuilder = new StringBuilder();
          Iterator&lt;Entry&lt;String, String&gt;&gt; iterator = params.entrySet().iterator();
          // constructs the POST body using the parameters
          while (iterator.hasNext()) {
              Entry&lt;String, String&gt; param = iterator.next();
              bodyBuilder.append(param.getKey()).append('=')
                      .append(param.getValue());
              if (iterator.hasNext()) {
                  bodyBuilder.append('&amp;');
              }
          }
          String body = bodyBuilder.toString();
          Log.v(TAG, "Posting '" + body + "' to " + url);
          byte[] bytes = body.getBytes();
          HttpURLConnection conn = null;
          try {
              Log.e("URL", "&gt; " + 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 (status != 200) {
                throw new IOException("Post failed with error code " + status);
              }
          } finally {
              if (conn != null) {
                  conn.disconnect();
              }
          }
        }
  }
  </code></pre>
  
  <p>WakeLocker.java:</p>
  
  <pre><code>public abstract class WakeLocker {
      private static PowerManager.WakeLock wakeLock;
  
      public static void acquire(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 static void release() {
          if (wakeLock != null) wakeLock.release(); wakeLock = null;
      }
  }
  </code></pre>
  
  <p>manifest:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.androidhive.pushnotifications"
      android:versionCode="1"
      android:versionName="1.0" &gt;
  
      &lt;!-- GCM requires Android SDK version 2.2 (API level 8) or above. --&gt;
      &lt;uses-sdk
          android:minSdkVersion="8"
          android:targetSdkVersion="16" /&gt;
  
      &lt;!-- GCM connects to Internet Services. --&gt;
      &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
  &lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/&gt;
      &lt;!-- GCM requires a Google account. --&gt;
      &lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt;
  
      &lt;!-- Keeps the processor from sleeping when a message is received. --&gt;
      &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;
  
      &lt;!-- Creates a custom permission so only this app can receive its messages. --&gt;
      &lt;permission
          android:name="com.androidhive.pushnotifications.permission.C2D_MESSAGE"
          android:protectionLevel="signature" /&gt;
  
      &lt;uses-permission android:name="com.androidhive.pushnotifications.permission.C2D_MESSAGE" /&gt;
  
      &lt;!-- This app has permission to register and receive data message. --&gt;
      &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /&gt;
  
      &lt;!-- Network State Permissions to detect Internet status --&gt;
      &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;
  
      &lt;!-- Permission to vibrate --&gt;
      &lt;uses-permission android:name="android.permission.VIBRATE" /&gt;
  
      &lt;!-- Main activity. --&gt;
      &lt;application
          android:icon="@drawable/ic_launcher"
          android:label="@string/app_name" &gt;
          &lt;!-- Register Activity --&gt;
          &lt;activity
              android:name=".RegisterActivity"
              android:label="@string/app_name" &gt;
              &lt;intent-filter&gt;
                  &lt;action android:name="android.intent.action.MAIN" /&gt;
  
                  &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
              &lt;/intent-filter&gt;
          &lt;/activity&gt;
  
          &lt;!-- Main Activity --&gt;
          &lt;activity
              android:name=".MainActivity"
              android:configChanges="orientation|keyboardHidden"
              android:label="@string/app_name" &gt;
          &lt;/activity&gt;
  
          &lt;receiver
              android:name="com.google.android.gcm.GCMBroadcastReceiver"
              android:permission="com.google.android.c2dm.permission.SEND" &gt;
              &lt;intent-filter&gt;
  
                  &lt;!-- Receives the actual messages. --&gt;
                  &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt;
                  &lt;!-- Receives the registration id. --&gt;
                  &lt;action android:name="com.google.android.c2dm.intent.REGISTRATION" /&gt;
  
                  &lt;category android:name="com.androidhive.pushnotifications" /&gt;
              &lt;/intent-filter&gt;
          &lt;/receiver&gt;
  
          &lt;service android:name=".GCMIntentService" /&gt;
      &lt;/application&gt;
  
  &lt;/manifest&gt;
  </code></pre>