Java tutorial
//package com.java2s; //License from project: Apache License import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.text.TextUtils; import android.util.Log; public class Main { public static final String TAG = "GcmUtils"; private static SharedPreferences sPrefs; private static final String GCM_PREFS_NAME = "gcm_prefs"; public static final String KEY_GCM_REGISTRATION_ID = "gcm_registration_id"; public static final String KEY_GCM_SERVER_EXPIRATION_TIME = "gcm_server_expiration_time"; public static final String KEY_GCM_APP_VERSION = "gcm_app_version"; /** * Retrieves the GCM registration Id. Will require a new one if the app is * updated or if the regId is expired. * * @param context * @return */ public static String getRegistrationId(Context context) { String regId = getGcmRegistrationIdFromPreferences(context); if (TextUtils.isEmpty(regId)) { Log.v(TAG, "No GCM Registration Id found."); return ""; } // Check if app was updated. if so, it must clear registration id to // avoid a race condition if GCM sends a message int registeredVersion = getGcmAppVersion(context); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion || isRegistrationExpired(context)) { // TODO - Add isRegistrationExpired? Log.v(TAG, "App version changed."); return ""; } return regId; } public static String getGcmRegistrationIdFromPreferences(Context context) { buildSharedPreferences(context); return sPrefs.getString(KEY_GCM_REGISTRATION_ID, null); } public static int getGcmAppVersion(Context context) { buildSharedPreferences(context); return sPrefs.getInt(KEY_GCM_APP_VERSION, -1); } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { Log.e(TAG, "Could not get package name.", e); } return 0; } /** * Determines if the current registration with GCM is expired or not. */ private static boolean isRegistrationExpired(Context context) { long expirationTime = getGcmExpiredLong(context); return System.currentTimeMillis() > expirationTime; } private static void buildSharedPreferences(Context context) { if (sPrefs == null) { sPrefs = context.getSharedPreferences(GCM_PREFS_NAME, Context.MODE_PRIVATE); } } public static long getGcmExpiredLong(Context context) { buildSharedPreferences(context); return sPrefs.getLong(KEY_GCM_SERVER_EXPIRATION_TIME, -1); } }