Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2014
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.57 KB | None | 0 0
  1. private BroadcastReceiver registrationStatusReceiver = new BroadcastReceiver() {
  2. @Override
  3. public void onReceive(Context context, Intent intent) {
  4. int caseInt = intent.getIntExtra(Common.EXTRA_STATUS, 100);
  5.  
  6.  
  7. if (intent != null && Common.ACTION_REGISTER.equals(intent.getAction())) {
  8. switch (caseInt) {
  9.  
  10. case Common.STATUS_SUCCESS:
  11. Log.e(TAG,"setting online");
  12. getSupportActionBar().setSubtitle("online");
  13. sendBtn.setEnabled(true);
  14. break;
  15.  
  16. case Common.STATUS_FAILED:
  17. Log.e(TAG,"setting offline");
  18. getSupportActionBar().setSubtitle("offline");
  19. break; }
  20. }
  21. };
  22.  
  23. public class GcmUtil {
  24.  
  25. private static final String TAG = "GcmUtil";
  26.  
  27. public static final String PROPERTY_REG_ID = "registration_id";
  28. private static final String PROPERTY_APP_VERSION = "appVersion";
  29. private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME = "onServerExpirationTimeMs";
  30.  
  31. /**
  32. * Default lifespan (7 days) of a reservation until it is considered expired.
  33. */
  34. public static final long REGISTRATION_EXPIRY_TIME_MS = 1000 * 3600 * 24 * 7;
  35.  
  36. private static final int MAX_ATTEMPTS = 5;
  37. private static final int BACKOFF_MILLI_SECONDS = 2000;
  38. private static final Random random = new Random();
  39.  
  40. private Context ctx;
  41. private SharedPreferences prefs;
  42. private GoogleCloudMessaging gcm;
  43. private AsyncTask registrationTask;
  44.  
  45. public GcmUtil(Context applicationContext) {
  46. super();
  47. ctx = applicationContext;
  48. prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
  49.  
  50. String regid = getRegistrationId();
  51. if (regid.length() == 0) {
  52. registerBackground();
  53. } else {
  54. broadcastStatus(true);
  55. }
  56.  
  57.  
  58. gcm = GoogleCloudMessaging.getInstance(ctx);
  59.  
  60. }
  61.  
  62. /**
  63. * Gets the current registration id for application on GCM service.
  64. * <p>
  65. * If result is empty, the registration has failed.
  66. *
  67. * @return registration id, or empty string if the registration is not
  68. * complete.
  69. */
  70. private String getRegistrationId() {
  71. String registrationId = prefs.getString(PROPERTY_REG_ID, "");
  72. if (registrationId.length() == 0) {
  73. Log.e(TAG, "Registration not found");
  74. return "";
  75. }
  76. // check if app was updated; if so, it must clear registration id to
  77. // avoid a race condition if GCM sends a message
  78. int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
  79. int currentVersion = getAppVersion();
  80. if (registeredVersion != currentVersion || isRegistrationExpired()) {
  81. Log.v(TAG, "App version changed or registration expired.");
  82. return "";
  83. }
  84.  
  85. // Log.e(TAG, "registration ID is " + registrationId.toString());
  86.  
  87. return registrationId;
  88. }
  89.  
  90. /**
  91. * Stores the registration id, app versionCode, and expiration time in the
  92. * application's {@code SharedPreferences}.
  93. *
  94. * @param regId registration id
  95. */
  96. private void setRegistrationId(String regId) {
  97. int appVersion = getAppVersion();
  98. Log.v(TAG, "Saving regId on app version " + appVersion);
  99. SharedPreferences.Editor editor = prefs.edit();
  100. editor.putString(PROPERTY_REG_ID, regId);
  101. editor.putInt(PROPERTY_APP_VERSION, appVersion);
  102. long expirationTime = System.currentTimeMillis() + REGISTRATION_EXPIRY_TIME_MS;
  103.  
  104. Log.v(TAG, "Setting registration expiry time to " + new Timestamp(expirationTime));
  105. editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime);
  106. editor.commit();
  107. }
  108.  
  109. /**
  110. * @return Application's version code from the {@code PackageManager}.
  111. */
  112. private int getAppVersion() {
  113. try {
  114. PackageInfo packageInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
  115. return packageInfo.versionCode;
  116. } catch (NameNotFoundException e) {
  117. // should never happen
  118. throw new RuntimeException("Could not get package name: " + e);
  119. }
  120. }
  121.  
  122. /**
  123. * Checks if the registration has expired.
  124. *
  125. * <p>To avoid the scenario where the device sends the registration to the
  126. * server but the server loses it, the app developer may choose to re-register
  127. * after REGISTRATION_EXPIRY_TIME_MS.
  128. *
  129. * @return true if the registration has expired.
  130. */
  131. private boolean isRegistrationExpired() {
  132. // checks if the information is not stale
  133. long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
  134. return System.currentTimeMillis() > expirationTime;
  135. }
  136.  
  137. /**
  138. * Registers the application with GCM servers asynchronously.
  139. * <p>
  140. * Stores the registration id, app versionCode, and expiration time in the
  141. * application's shared preferences.
  142. */
  143. private void registerBackground() {
  144. registrationTask = new AsyncTask<Void, Void, Boolean>() {
  145. @Override
  146. protected Boolean doInBackground(Void... params) {
  147. long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
  148. for (int i = 1; i <= MAX_ATTEMPTS; i++) {
  149. Log.w(TAG, "Attempt #" + i + " to register");
  150. try {
  151. if (gcm == null) {
  152. gcm = GoogleCloudMessaging.getInstance(ctx);
  153. }
  154. String regid = gcm.register(Common.getSenderId());
  155.  
  156. // You should send the registration ID to your server over HTTP,
  157. // so it can use GCM/HTTP or CCS to send messages to your app.
  158. ServerUtilities.register(Common.getPreferredEmail(), regid);
  159.  
  160. // Save the regid - no need to register again.
  161. setRegistrationId(regid);
  162. return Boolean.TRUE;
  163.  
  164. } catch (IOException ex) {
  165. //Log.e(TAG, "Failed to register on attempt " + i + ":" + ex);
  166. if (i == MAX_ATTEMPTS) {
  167. break;
  168. }
  169. try {
  170. Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
  171. Thread.sleep(backoff);
  172. } catch (InterruptedException e1) {
  173. // Activity finished before we complete - exit.
  174. Log.d(TAG, "Thread interrupted: abort remaining retries!");
  175. Thread.currentThread().interrupt();
  176. }
  177. // increase backoff exponentially
  178. backoff *= 2;
  179. }
  180. }
  181. return Boolean.FALSE;
  182. }
  183.  
  184. @Override
  185. protected void onPostExecute(Boolean status) {
  186. broadcastStatus(status);
  187. }
  188. }.execute(null, null, null);
  189. }
  190.  
  191. private void broadcastStatus(boolean status) {
  192. Intent intent = new Intent(Common.ACTION_REGISTER);
  193. intent.putExtra(Common.EXTRA_STATUS, status ? Common.STATUS_SUCCESS : Common.STATUS_FAILED);
  194. ctx.sendBroadcast(intent);
  195. }
  196.  
  197. public void cleanup() {
  198. if (registrationTask != null) {
  199. registrationTask.cancel(true);
  200. }
  201. if (gcm != null) {
  202. gcm.close();
  203. }
  204. }
  205.  
  206. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement