All Downloads are FREE. Search and download functionalities are using the official Maven repository.

eu.easypush.pushlibrary.utils.PushRegistrar Maven / Gradle / Ivy

There is a newer version: 0.8
Show newest version
package eu.easypush.pushlibrary.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import eu.easypush.pushlibrary.events.OnNotificationRegistrationListener;
import eu.easypush.pushlibrary.requests.EasyPushRequest;

public class PushRegistrar implements PushConstants {

	public static final String EXTRA_MESSAGE = "message";
	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

	private static final int MAX_ATTEMPTS = 5;
	private static final int BACKOFF_MILLI_SECONDS = 2000;
	private static final Random random = new Random();

    private static final ArrayList onNotificationRegistrationListeners = new ArrayList();

    public static void addOnNotificationRegistrationListeners(OnNotificationRegistrationListener listener) {
        if (!onNotificationRegistrationListeners.contains(listener)) {
            onNotificationRegistrationListeners.add(listener);
        }
    }

    public static void removeOnNotificationRegistrationListeners(OnNotificationRegistrationListener listener) {
        onNotificationRegistrationListeners.remove(listener);
    }

    private static void preventAllOnNotificationRegistrationIdReceivedListeners(String registrationId) {
        for (OnNotificationRegistrationListener listener : onNotificationRegistrationListeners) {
            try {
                listener.notificationRegistrationIdReceived(registrationId);
            } catch (Throwable t) {
            }

        }

    }
    private static void preventAllOnNotificationRegistrationErrorListeners(String error) {
        for (OnNotificationRegistrationListener listener : onNotificationRegistrationListeners) {
            try {
                listener.notificationRegistrationInError(error);
            } catch (Throwable t) {
            }

        }

    }


    public static void checkDevice(final Context c) {
		final SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(c);
		boolean notificationPreferenceSet = sp.getBoolean(
				"Easypush_Notification_Preference_set", false);
		if (!notificationPreferenceSet) {
			PushUtils.askUserForPush(c);
		}
		if (PushRegistrar.checkPlayServices(c)) {
			// checkManifest(c);
			// remove account if needed
			removeAccountIfNeeded(c);
		}
	}

	public static void register(final Context c, final String... senderIds) {
		String regid = PushUtils.getRegistrationId(c);
		if (TextUtils.isEmpty(regid)) {
			new AsyncTask() {
				@Override
				protected String doInBackground(Void... params) {
					String msg = "";
					try {
						GoogleCloudMessaging gcm = GoogleCloudMessaging
								.getInstance(c);
						String regid = gcm.register(senderIds);
						msg = "Device registered, 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.
						// The request to your server should be authenticated if
						// your app
						// is using accounts.
                        sendRegistrationIdToBackend(c, regid);

						// 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(c, regid);

                        preventAllOnNotificationRegistrationIdReceivedListeners(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.
                        preventAllOnNotificationRegistrationErrorListeners(ex.getMessage());
					}
					return msg;
				}

			}.execute(null, null, null);
		}
	}

	public static void checkAndRegister(Context c, String... senderIds) {
		Log.d(TAG, "check And Register start");
		if (senderIds != null) {
			Editor editor = PreferenceManager.getDefaultSharedPreferences(c)
					.edit();
			editor.putString("easypush_senderId",
					TextUtils.join(",", senderIds));
			editor.commit();
		}
		Log.d(TAG, "Check device");
		checkDevice(c);
		Log.d(TAG, "Register to easypush server");
		register(c, senderIds);
	}

	/**
	 * 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.
	 */
	public static boolean checkPlayServices(Context c) {

		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(c);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, (Activity) c,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Log.i(TAG, "This device is not supported.");
			}
			return false;
		}
		return true;
	}

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

	/**
	 * 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 static void sendRegistrationIdToBackend(Context c,
			String registrationId) {
		// Your implementation here.
		long backoff = PushRegistrar.BACKOFF_MILLI_SECONDS
				+ PushRegistrar.random.nextInt(1000);
		String deviceId = PushUtils.getDeviceId(c);
		// On teste plusieurs fois si jms le 1er essai echoue
		for (int i = 1; i <= PushRegistrar.MAX_ATTEMPTS; i++) {
			Log.d(PushRegistrar.TAG, "Attempt #" + i + " to register");

			if (EasyPushRequest.addDeviceProject(c,
					PushUtils.getProjectToken(c), deviceId, registrationId,
					PushUtils.getApplicationName(c),
					PushUtils.isProductionMode(c))) {
				return;
			} else {
				// Pour une raison X ou Y, l'enregistrement a echoué, on
				// retente si on est pas au nombre max d'essais
				if (i == PushRegistrar.MAX_ATTEMPTS) {
					break;
				}
				try {
					Log.d(PushRegistrar.TAG, "Sleeping for " + backoff
							+ " ms before retry");
					Thread.sleep(backoff);
				} catch (InterruptedException e1) {
					// Activity finished before we complete - exit.
					Log.d(PushRegistrar.TAG,
							"Thread interrupted: abort remaining retries!");
					Thread.currentThread().interrupt();
				}
				// increase backoff exponentially
				backoff *= 2;
			}
		}
	}

	private static void removeAccountIfNeeded(Context c) {
		try {
			AccountManager accMgr = AccountManager.get(c);
			Account[] accounts = accMgr.getAccountsByType("EasyPush.eu");
			for (Account accountTmp : accounts) {
				accMgr.removeAccount(accountTmp, null, null);
			}
		} catch (Throwable t) {
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy