Android Open Source - base_app G C M Manager






From Project

Back to project page base_app.

License

The source code is released under:

GNU General Public License

If you think the Android project base_app listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.bengui.baseapp.gcm;
// ww  w. j av a  2s  .c  o  m
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;

import com.bengui.baseapp.utils.Utils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GCMManager {

  public static final String EXTRA_MESSAGE = "message";
  public static final String PROPERTY_REG_ID = "registration_id";
  private static final String PROPERTY_APP_VERSION = "appVersion";
  private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
  private static final String SERVER_URL = "http://ecloud-testapp.aws.af.cm/";
  private static final String TAG = "GCMManager";
  private Activity activity;
  private GoogleCloudMessaging gcm;
  private String regid;
  
  /**
   * Substitute you own sender ID here. This is the project number you got
   * from the API Console, as described in "Getting Started."
   */
  private String SENDER_ID = "524654233573";
  
  public GCMManager(Activity activity) {
    this.activity = activity;
  }

  public void initGCM() {
    // Check device for Play Services APK. If check succeeds, proceed with
    // GCM registration.
    if (checkPlayServices()) {
      gcm = GoogleCloudMessaging.getInstance(activity);
      regid = getRegistrationId(activity);

      if (regid.isEmpty()) {
        registerInBackground();
      }else{
        Log.d(TAG, "Registration ID: " + regid);
      }
    } else {
      Log.i(TAG, "No valid Google Play Services APK found.");
    }
  }

  /**
   * Check the device to make sure it has the Google Play Services APK. If it
   * doesn't, display a dialog that allows users to download the APK from the
   * Google Play Store or enable it in the device's system settings.
   */
  private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity);
    if (resultCode != ConnectionResult.SUCCESS) {
      if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
        GooglePlayServicesUtil.getErrorDialog(resultCode, activity, PLAY_SERVICES_RESOLUTION_REQUEST).show();
      } else {
        Log.i(TAG, "This device is not supported.");
      }
      return false;
    }
    return true;
  }

  /**
   * Stores the registration ID and the app versionCode in the application's
   * {@code SharedPreferences}.
   * 
   * @param context
   *            application's context.
   * @param regId
   *            registration ID
   */
  private void storeRegistrationId(Context context, String regId) {
    final SharedPreferences prefs = getGcmPreferences(context);
    int appVersion = getAppVersion(context);
    Log.i(TAG, "Saving regId on app version " + appVersion);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(PROPERTY_REG_ID, regId);
    editor.putInt(PROPERTY_APP_VERSION, appVersion);
    editor.commit();
  }

  /**
   * Gets the current registration ID for application on GCM service, if there
   * is one.
   * <p>
   * If result is empty, the app needs to register.
   * 
   * @return registration ID, or empty string if there is no existing
   *         registration ID.
   */
  private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGcmPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
      Log.i(TAG, "Registration not found.");
      return "";
    }
    // Check if app was updated; if so, it must clear the registration ID
    // since the existing regID is not guaranteed to work with the new
    // app version.
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
      Log.i(TAG, "App version changed.");
      return "";
    }

    // FIXME Remove this methods when the application works properly
    // mDisplay.setText(registrationId);
    // sendRegistrationIDinBackground();

    return registrationId;
  }

  /**
   * Registers the application with GCM servers asynchronously.
   * <p>
   * Stores the registration ID and the app versionCode in the application's
   * shared preferences.
   */
  private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {
      @Override
      protected String doInBackground(Void... params) {
        String msg = "";
        try {
          if (gcm == null) {
            gcm = GoogleCloudMessaging.getInstance(activity);
          }
          regid = gcm.register(SENDER_ID);
          msg = "Device registered, registration ID=" + regid;
          
          Log.d(TAG, "Registration ID: " + regid);

          // You should send the registration ID to your server over
          // HTTP, so it
          // can use GCM/HTTP or CCS to send messages to your app.
          sendRegistrationIdToBackend();

          // For this demo: we don't need to send it because the
          // device will send
          // upstream messages to a server that echo back the message
          // using the
          // 'from' address in the message.

          // Persist the regID - no need to register again.
          storeRegistrationId(activity, regid);
        } catch (IOException ex) {
          msg = "Error :" + ex.getMessage();
          // If there is an error, don't just keep trying to register.
          // Require the user to click a button again, or perform
          // exponential back-off.
        }
        return msg;
      }

      @Override
      protected void onPostExecute(String msg) {
        //DO something with the message
      }
    }.execute(null, null, null);
  }

  /**
   * @return Application's version code from the {@code PackageManager}.
   */
  private static int getAppVersion(Context context) {
    try {
      PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
      return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
      // should never happen
      throw new RuntimeException("Could not get package name: " + e);
    }
  }

  /**
   * @return Application's {@code SharedPreferences}.
   */
  private SharedPreferences getGcmPreferences(Context context) {
    // This sample app persists the registration ID in shared preferences,
    // but
    // how you store the regID in your app is up to you.
    return activity.getSharedPreferences(GCMManager.class.getName(), Context.MODE_PRIVATE);
  }

  /**
   * Sends the registration ID to your server over HTTP, so it can use
   * GCM/HTTP or CCS to send messages to your app. Not needed for this demo
   * since the device sends upstream messages to a server that echoes back the
   * message using the 'from' address in the message.
   */
  private void sendRegistrationIdToBackend() {
    // Making HTTP request
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(SERVER_URL + "/gcm/register");

    try {

      StringEntity entity = new StringEntity("{ \"regId\" : \"" + regid + "\"}");
      entity.setContentType("application/json;charset=UTF-8");// text/plain;charset=UTF-8
      entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
      httpPost.setEntity(entity);

      HttpResponse httpResponse = httpClient.execute(httpPost);
      HttpEntity httpEntity = httpResponse.getEntity();
      String response = Utils.inputStreamToString(httpEntity.getContent());

      Log.d(TAG, "Server response: " + response);

    } catch (UnsupportedEncodingException e) {
      Log.e(TAG, e.getMessage());
    } catch (ClientProtocolException e) {
      Log.e(TAG, e.getMessage());
    } catch (IOException e) {
      Log.e(TAG, e.getMessage());
    }
  }

}




Java Source Code List

com.bengui.baseapp.MainActivity.java
com.bengui.baseapp.gcm.GCMManager.java
com.bengui.baseapp.gcm.GcmBroadcastReceiver.java
com.bengui.baseapp.gcm.GcmIntentService.java
com.bengui.baseapp.models.Contact.java
com.bengui.baseapp.services.HttpClient.java
com.bengui.baseapp.services.ServerException.java
com.bengui.baseapp.services.ServiceException.java
com.bengui.baseapp.utils.Constants.java
com.bengui.baseapp.utils.JSONParcelableObject.java
com.bengui.baseapp.utils.JSONUtils.java
com.bengui.baseapp.utils.Utils.java