title: Timing problems when accessing a GCM message
body: <p>I'm developing a multi-player quiz application. I'm using GCM to send messages from my server to the devices. The registration is done by this code</p>
  
  <pre><code>//skeletonactivity.java   
  protected void onStart() {
      super.onStart();
      Log.d(TAG, "onStart(): Connecting to Google APIs");
      mGoogleApiClient.connect();
      regId = registerGCM();
      appUtil=new ShareExternalServer();
      shareRegidTask = new AsyncTask&lt;Void, Void, String&gt;() {
          @Override
          protected String doInBackground(Void... params) {
              String result = appUtil.shareRegIdWithAppServer(context, regId);
              return result;
          }
  
          @Override
          protected void onPostExecute(String result) {
              shareRegidTask = null;
              Toast.makeText(getApplicationContext(), result,
                      Toast.LENGTH_LONG).show();
          }
  
      };
      shareRegidTask.execute(null, null, null);
  
      Log.d("RegisterActivity", "GCM RegId: " + regId);
      Handler handler = new Handler();
      handler.postDelayed(new Runnable() {
          public void run() {
              Intent intent=new Intent(SkeletonActivity.this,Quizform.class);
              startActivity(intent);
              finish();
          }
      }, 1000);
  </code></pre>
  
  <p>// i have tried making the activity launch after sometime, so that the GCM message will be recieved. but there's no change.</p>
  
  <pre><code>}
  public String registerGCM() {
  
      gcm = GoogleCloudMessaging.getInstance(this);
      regId = getRegistrationId(context);
  
      if (TextUtils.isEmpty(regId)) {
  
          registerInBackground();
  
          Log.d("RegisterActivity",
                  "registerGCM - successfully registered with GCM server - regId: "
                          + regId);
      }
      return regId;
  }
  
  private String getRegistrationId(Context context) {
      final SharedPreferences prefs = getSharedPreferences(
              SkeletonActivity.class.getSimpleName(), Context.MODE_PRIVATE);
      String registrationId = prefs.getString(REG_ID, "");
      if (registrationId.isEmpty()) {
          Log.i(TAG, "Registration not found.");
          return "";
      }
  
      return registrationId;
  }
  private void registerInBackground() {
      new AsyncTask&lt;Void,Void,String&gt;() {
          @Override
          protected String doInBackground(Void...Params) {
              String msg = "";
              try {
                  if (gcm == null) {
                      gcm = GoogleCloudMessaging.getInstance(context);
                  }
                  regId = gcm.register(GOOGLE_PROJECT_ID);
                  Log.d("RegisterActivity", "registerInBackground - regId: "
                          + regId);
                  msg = "Device registered, registration ID=" + regId;
                  storeRegistrationId(context, regId);
              } catch (IOException ex) {
                  msg = "Error :" + ex.getMessage();
                  Log.d("RegisterActivity", "Error: " + msg);
              }
              Log.d("RegisterActivity", "AsyncTask completed: " + msg);
              return msg;
          }
         @Override
          protected void onPostExecute(String msg) {
              Toast.makeText(getApplicationContext(),
                      "Registered with GCM Server." + msg, Toast.LENGTH_LONG)
                      .show();
          }
      }.execute(null, null, null);
  }
  
  private void storeRegistrationId(Context context, String regId) {
      final SharedPreferences prefs = getSharedPreferences(
              SkeletonActivity.class.getSimpleName(), Context.MODE_PRIVATE);
      Log.i(TAG, "Saving regId on app version" );
      SharedPreferences.Editor editor = prefs.edit();
      editor.putString(REG_ID, regId);
      editor.commit();
  }
  </code></pre>
  
  <p>The code for sharing with external activity is 
  shareExternalServer</p>
  
  <pre><code>public class ShareExternalServer {
  
  public String shareRegIdWithAppServer(final Context context,
                                        final String regId) {
  
      String result = "";
      Map paramsMap = new HashMap();
      paramsMap.put("regId", regId);
      try {
          URL serverUrl = null;
          try {
              serverUrl = new URL(Config.APP_SERVER_URL);
          } catch (MalformedURLException e) {
              Log.e("AppUtil", "URL Connection Error: "
                      + Config.APP_SERVER_URL, e);
              result = "Invalid URL: " + Config.APP_SERVER_URL;
          }
  
          StringBuilder postBody = new StringBuilder();
          Iterator&lt;Entry&gt; iterator = paramsMap.entrySet()
                  .iterator();
  
          while (iterator.hasNext()) {
              Entry param = iterator.next();
              postBody.append(param.getKey()).append('=')
                      .append(param.getValue());
              if (iterator.hasNext()) {
                  postBody.append('&amp;');
              }
          }
          String body = postBody.toString();
          byte[] bytes = body.getBytes();
          HttpURLConnection httpCon = null;
          try {
              httpCon = (HttpURLConnection) serverUrl.openConnection();
              httpCon.setDoOutput(true);
              httpCon.setUseCaches(false);
              httpCon.setFixedLengthStreamingMode(bytes.length);
              httpCon.setRequestMethod("POST");
              httpCon.setRequestProperty("Content-Type",
                      "application/x-www-form-urlencoded;charset=UTF-8");
              OutputStream out = httpCon.getOutputStream();
              out.write(bytes);
              out.close();
  
              int status = httpCon.getResponseCode();
              if (status == 200) {
                  result = "RegId shared with Application Server. RegId: "
                          + regId;
              } else {
                  result = "Post Failure." + " Status: " + status;
              }
          } finally {
              if (httpCon != null) {
                  httpCon.disconnect();
              }
          }
  
      } catch (IOException e) {
          result = "Post Failure. Error in sharing with App Server.";
          Log.e("AppUtil", "Error in sharing with App Server: " + e);
      }
      return result;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>the code for GCMIntentService.java </p>
  
  <pre><code>public class GcmIntentService extends IntentService {
  
  public GcmIntentService() {
      super("GcmIntentService");
  }
  public SharedPreferences sharedPreferences;
  public static SharedPreferences getSharedPreferences (Context ctxt) {
      return ctxt.getSharedPreferences("message",0);
  }
  public static boolean flag;
  public static final String TAG = "GCM Demo";
  public String mess=" ";
  @Override
  protected void onHandleIntent(Intent intent) {
      Bundle extras = intent.getExtras();
      sharedPreferences=  getSharedPreferences(this);
      SharedPreferences.Editor editor=sharedPreferences.edit();
  
      GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
      String messageType=gcm.getMessageType(intent);
      if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
          if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
              Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
              mess= extras.getString("message");
              editor.putString("mess",mess);
              editor.commit();
              Log.i(TAG, "Received: " + mess);
          }
      }
      GcmBroadcastReceiver.completeWakefulIntent(intent);
  
  }
  }
  </code></pre>
  
  <p>The above code gets the value from the broadcast receiver and stores it the string msg.
  i try to access it as below in quizform.java</p>
  
  <pre><code>protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);                 sharedPreferences=getApplicationContext().getSharedPreferences("messages",0);
      setContentView(R.layout.activity_quizform);
          txt = sharedPreferences.getString("mess","empty");
          Toast.makeText(this, txt, Toast.LENGTH_LONG).show();
  }
  </code></pre>
  
  <p>The value of txt is empty, and so i get only a blank toast. 
  The server sends the message as soon as it gets the regID. the code is: </p>
  
  <pre><code>&lt;?php
  //generic php function to send GCM push notification
  function sendPushNotificationToGCM($registatoin_ids, $message) {
     //Google cloud messaging GCM-API url
     $url = 'https://android.googleapis.com/gcm/send';
     $fields = array(
         'registration_ids' =&gt; $registatoin_ids,
         'data' =&gt; $message,
     );
     // Google Cloud Messaging GCM API Key
     define("GOOGLE_API_KEY", "apikey");        
     $headers = array(
         'Authorization: key=' . GOOGLE_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_SSL_VERIFYHOST, 0);   
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
     $result = curl_exec($ch);               
     if ($result === FALSE) {
         die('Curl failed: ' . curl_error($ch));
     }
     curl_close($ch);
     return $result;
  }
  
  
   function sendquestions()
  {
  $servername = " ";
  $username = "  ";
  $password = " ";
  $dbname="  ";
  $conn = mysqli_connect($servername, $username, $password,$dbname);
  $pushStatus = "";   
  $result= mysqli_query($conn,"SELECT id FROM regid");
  while($row = $result-&gt;fetch_assoc()){ 
  $gcmRegID=$row['id'];}
  $pushMessage = "hello";
  if (isset($gcmRegID) &amp;&amp; isset($pushMessage)) {      
  $gcmRegIds = array($gcmRegID);
  $message = array("message" =&gt; $pushMessage);  
  $pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
  }       
  } 
  //this block is to receive the GCM regId from external (mobile apps)
  if(!empty($_GET["shareRegId"]))
  {
  $gcmRegID  = $_POST["regId"]; 
  mysqli_query($conn,"INSERT INTO regid (id) VALUES('$gcmRegID')");
  $retval = mysql_query( $mysqli, $conn );
  mysqli_close($conn);
  sendquestions();
  exit;
  } 
  ?&gt;
  </code></pre>
  
  <p>Please do suggest ways to get over the delay . thanks </p>