Skip to content

Instantly share code, notes, and snippets.

@kaiinui
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save kaiinui/720f654402f88708276e to your computer and use it in GitHub Desktop.

Select an option

Save kaiinui/720f654402f88708276e to your computer and use it in GitHub Desktop.
雑に gcmHelper.onCreate 呼ぶだけでよしなにやってくれるやつ。
package co.kotori.grumbler.utils;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
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 java.io.IOException;
/**
* Created by kaiinui on 2015/04/13.
*/
public class GcmHelper {
public final int PLAY_SERVICES_RESOLUTION_REQUEST = 8773;
public final String SHARED_PREFS_NAME = "co.kotori.utils.sharef_prefs";
public final String PROPERTY_REG_ID = "co.kotori.utils.shared_prefs.reg_id";
public final String PROPERTY_APP_VERSION = "co.kotori.utils.shared_prefs.app_version";
private final String TAG = GcmHelper.class.getSimpleName();
final Activity context;
final String senderId;
final RegistrationIdSender sender;
GoogleCloudMessaging gcm;
String regid;
public GcmHelper(Activity context, String senderId, RegistrationIdSender sender) {
this.context = context;
this.senderId = senderId;
this.sender = sender;
}
public interface RegistrationIdSender {
boolean sendRegistrationIdToBackend(String registrationId);
}
public void onCreate() {
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(context);
regid = getRegistrationId();
if (regid.isEmpty()) {
registerInBackground();
} else {
Log.i(TAG, "registrationID = " + regid);
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
// Private Helpers
private boolean checkPlayServices() {
try {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, context, PLAY_SERVICES_RESOLUTION_REQUEST).show();
}
return false;
}
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return true;
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(senderId);
msg = "Device registered, registration ID=" + regid;
// 失敗したら保存しない。もう一度登録し直す。
if (sender.sendRegistrationIdToBackend(regid)) {
storeRegistrationId(regid);
} else {
Log.i(TAG, "Skipped saving regid due to send to backend failed.");
}
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
} catch (Throwable e) {
msg = "Error :" + e.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
Log.i(TAG, msg + "\n");
}
}.execute(null, null, null);
}
// Shared Preferences
/**
* 現在のバージョンの regid を返します。もしバージョンが変わっていたり、前に登録されていなかったりすると "" が返ります。
*
* @return Current version's registration id. If not found, "" will be returned.
*/
private String getRegistrationId() {
final SharedPreferences prefs = getGCMPreferences();
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();
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
private void storeRegistrationId(String regId) {
final SharedPreferences prefs = getGCMPreferences();
int appVersion = getAppVersion();
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();
}
private SharedPreferences getGCMPreferences() {
return context.getSharedPreferences(SHARED_PREFS_NAME,
Context.MODE_PRIVATE);
}
private int getAppVersion() {
try {
final PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException("Could not get package name: " + e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment