Skip to content

Instantly share code, notes, and snippets.

@patrickhammond
Created June 19, 2014 15:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save patrickhammond/88249c493206809ed5cb to your computer and use it in GitHub Desktop.
Save patrickhammond/88249c493206809ed5cb to your computer and use it in GitHub Desktop.
package com.atomicrobot.app;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
public class ActivityFirstRunHelper {
private static final String PREFERENCES_NAME_FIRST_RUN = "first_run";
private static final String PREFERENCES_KEY_FIRST_RUN_BOOL = "first_run";
private static final String PREFERENCES_NAME_VERSION = "version";
private static final String PREFERENCES_KEY_LAST_VERSION_CODE_INT = "last_version_code";
public static interface FirstRunBehavior {
public void onFirstRun(Activity activity);
public void onAfterFirstRun(Activity activity);
}
public static interface VersionChangedBehavior {
public void onVersionChanged(int oldVersion, int newVersion);
public void onVersionUnchanged();
public void onNewInstall();
}
public static void handleFirstRunIfNeeded(Activity activity, FirstRunBehavior responder) {
SharedPreferences preferences = activity.getSharedPreferences(PREFERENCES_NAME_FIRST_RUN, Context.MODE_PRIVATE);
boolean isFirstRun = preferences.getBoolean(PREFERENCES_KEY_FIRST_RUN_BOOL, true);
if (isFirstRun) {
responder.onFirstRun(activity);
preferences.edit().putBoolean(PREFERENCES_KEY_FIRST_RUN_BOOL, false).commit();
} else {
responder.onAfterFirstRun(activity);
}
}
public static void handleVersionChanged(Activity activity, VersionChangedBehavior responder) {
SharedPreferences preferences = activity.getSharedPreferences(PREFERENCES_NAME_VERSION, Context.MODE_PRIVATE);
int lastVersionCode = preferences.getInt(PREFERENCES_KEY_LAST_VERSION_CODE_INT, -1);
if (lastVersionCode == -1) {
responder.onNewInstall();
}
String packageName = activity.getPackageName();
PackageManager packageManager = activity.getPackageManager();
int thisVersionCode = -1;
try {
PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
thisVersionCode = packageInfo.versionCode;
} catch (NameNotFoundException ex) {
// This should never happen...
}
if (lastVersionCode != thisVersionCode) {
responder.onVersionChanged(lastVersionCode, thisVersionCode);
preferences.edit().putInt(PREFERENCES_KEY_LAST_VERSION_CODE_INT, thisVersionCode).commit();
} else {
responder.onVersionUnchanged();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment