Determinar si la aplicación de Android es la primera vez que se utiliza

Actualmente estoy desarrollando una aplicación para Android. Tengo que hacer algo cuando la aplicación se inicia por primera vez, es decir, el código sólo se ejecuta en la primera vez que se inicia el programa.

Otra idea es usar una configuración en las Preferencias compartidas. La misma idea general que buscar un archivo vacío, pero luego no tienes un archivo vacío flotando alrededor, no se utiliza para almacenar nada

Puede usar SharedPreferences para identificar si es la primera vez que se inicia la aplicación. Simplemente utilice una variable booleana ("my_first_time") y cambie su valor a false cuando su tarea para "primera vez" haya terminado.

Este es mi código para capturar la primera vez que abra la aplicación:

final String PREFS_NAME = "MyPrefsFile"; SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); if (settings.getBoolean("my_first_time", true)) { //the app is being launched for first time, do something Log.d("Comments", "First time"); // first time task // record the fact that the app has been started at least once settings.edit().putBoolean("my_first_time", false).commit(); } 

Sugiero no sólo almacenar una bandera booleana, sino el código de la versión completa. De esta manera también puede consultar al principio si es el primer inicio en una nueva versión. Puede utilizar esta información para mostrar un cuadro de diálogo "¿Qué es nuevo?", Por ejemplo.

El siguiente código debería funcionar desde cualquier clase de android que sea "un contexto" (actividades, servicios, …). Si prefiere tenerla en una clase separada (POJO), podría considerar el uso de un "contexto estático", como se describe aquí por ejemplo.

 /** * Distinguishes different kinds of app starts: <li> * <ul> * First start ever ({@link #FIRST_TIME}) * </ul> * <ul> * First start in this version ({@link #FIRST_TIME_VERSION}) * </ul> * <ul> * Normal app start ({@link #NORMAL}) * </ul> * * @author schnatterer * */ public enum AppStart { FIRST_TIME, FIRST_TIME_VERSION, NORMAL; } /** * The app version code (not the version name!) that was used on the last * start of the app. */ private static final String LAST_APP_VERSION = "last_app_version"; /** * Finds out started for the first time (ever or in the current version).<br/> * <br/> * Note: This method is <b>not idempotent</b> only the first call will * determine the proper result. Any subsequent calls will only return * {@link AppStart#NORMAL} until the app is started again. So you might want * to consider caching the result! * * @return the type of app start */ public AppStart checkAppStart() { PackageInfo pInfo; SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); AppStart appStart = AppStart.NORMAL; try { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); int lastVersionCode = sharedPreferences .getInt(LAST_APP_VERSION, -1); int currentVersionCode = pInfo.versionCode; appStart = checkAppStart(currentVersionCode, lastVersionCode); // Update version in preferences sharedPreferences.edit() .putInt(LAST_APP_VERSION, currentVersionCode).commit(); } catch (NameNotFoundException e) { Log.w(Constants.LOG, "Unable to determine current app version from pacakge manager. Defenisvely assuming normal app start."); } return appStart; } public AppStart checkAppStart(int currentVersionCode, int lastVersionCode) { if (lastVersionCode == -1) { return AppStart.FIRST_TIME; } else if (lastVersionCode < currentVersionCode) { return AppStart.FIRST_TIME_VERSION; } else if (lastVersionCode > currentVersionCode) { Log.w(Constants.LOG, "Current version code (" + currentVersionCode + ") is less then the one recognized on last startup (" + lastVersionCode + "). Defenisvely assuming normal app start."); return AppStart.NORMAL; } else { return AppStart.NORMAL; } } 

Se podría utilizar de una actividad como esta:

 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); switch (checkAppStart()) { case NORMAL: // We don't want to get on the user's nerves break; case FIRST_TIME_VERSION: // TODO show what's new break; case FIRST_TIME: // TODO show a tutorial break; default: break; } // ... } // ... } 

La lógica básica puede ser verificada usando esta prueba JUnit:

 public void testCheckAppStart() { // First start int oldVersion = -1; int newVersion = 1; assertEquals("Unexpected result", AppStart.FIRST_TIME, service.checkAppStart(newVersion, oldVersion)); // First start this version oldVersion = 1; newVersion = 2; assertEquals("Unexpected result", AppStart.FIRST_TIME_VERSION, service.checkAppStart(newVersion, oldVersion)); // Normal start oldVersion = 2; newVersion = 2; assertEquals("Unexpected result", AppStart.NORMAL, service.checkAppStart(newVersion, oldVersion)); } 

Con un poco más de esfuerzo que probablemente podría probar las cosas relacionadas con Android (PackageManager y SharedPreferences) también. ¿Alguien interesado en escribir la prueba? 🙂

Tenga en cuenta que el código anterior sólo funcionará correctamente si no se ensucia con su android:versionCode en AndroidManifest.xml!

Aquí hay un código para esto –

 String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/myapp/files/myfile.txt"; boolean exists = (new File(path)).exists(); if (!exists) { doSomething(); } else { doSomethingElse(); } 

Usted podría simplemente comprobar la existencia de un archivo vacío, si no existe, a continuación, ejecutar su código y crear el archivo.

p.ej

 if(File.Exists("emptyfile"){ //Your code here File.Create("emptyfile"); } 

Hice una clase simple para comprobar si su código se está ejecutando por primera vez / n veces!

Ejemplo

Crear una preferencia única

 FirstTimePreference prefFirstTime = new FirstTimePreference(getApplicationContext()); 

Utilice runTheFirstTime, elija una clave para comprobar su evento

 if (prefFirstTime.runTheFirstTime("myKey")) { Toast.makeText(this, "Test myKey & coutdown: " + prefFirstTime.getCountDown("myKey"), Toast.LENGTH_LONG).show(); } 

Utilice runTheFirstNTimes, elija una clave y cuántas veces ejecutar

 if(prefFirstTime.runTheFirstNTimes("anotherKey" , 5)) { Toast.makeText(this, "ciccia Test coutdown: "+ prefFirstTime.getCountDown("anotherKey"), Toast.LENGTH_LONG).show(); } 
  • Use getCountDown () para manejar mejor su código

FirstTimePreference.java

He resuelto para determinar si la aplicación es su primera vez o no, dependiendo de si se trata de una actualización.

 private int appGetFirstTimeRun() { //Check if App Start First Time SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0); int appCurrentBuildVersion = BuildConfig.VERSION_CODE; int appLastBuildVersion = appPreferences.getInt("app_first_time", 0); //Log.d("appPreferences", "app_first_time = " + appLastBuildVersion); if (appLastBuildVersion == appCurrentBuildVersion ) { return 1; //ya has iniciado la appp alguna vez } else { appPreferences.edit().putInt("app_first_time", appCurrentBuildVersion).apply(); if (appLastBuildVersion == 0) { return 0; //es la primera vez } else { return 2; //es una versión nueva } } } 

Calcule los resultados:

  • 0: Si es la primera vez.
  • 1: Ha comenzado siempre.
  • 2: Se ha iniciado una vez, pero no esa versión, es decir, es una actualización.

Hay soporte para esto en la revisión de la biblioteca de soporte 23.3.0 (en la v4 que significa compability de nuevo a Android 1.6).

En su actividad de Lanzador, llame primero:

 AppLaunchChecker.onActivityCreate(activity); 

Luego llame:

 AppLaunchChecker.hasStartedFromLauncher(activity); 

Que volverá si esta fue la primera vez que se lanzó la aplicación.

Puedes usar Android SharedPreferences .

Android SharedPreferences nos permite almacenar datos primitivos de aplicaciones privadas en forma de par clave-valor.

CÓDIGO

Crear una clase personalizada SharedPreference

  public class SharedPreference { android.content.SharedPreferences pref; android.content.SharedPreferences.Editor editor; Context _context; private static final String PREF_NAME = "testing"; // All Shared Preferences Keys Declare as #public public static final String KEY_SET_APP_RUN_FIRST_TIME = "KEY_SET_APP_RUN_FIRST_TIME"; public SharedPreference(Context context) // Constructor { this._context = context; pref = _context.getSharedPreferences(PREF_NAME, 0); editor = pref.edit(); } /* * Set Method Generally Store Data; * Get Method Generally Retrieve Data ; * */ public void setApp_runFirst(String App_runFirst) { editor.remove(KEY_SET_APP_RUN_FIRST_TIME); editor.putString(KEY_SET_APP_RUN_FIRST_TIME, App_runFirst); editor.commit(); } public String getApp_runFirst() { String App_runFirst= pref.getString(KEY_SET_APP_RUN_FIRST_TIME, null); return App_runFirst; } } 

Ahora abre tu actividad e inicia .

  private SharedPreference sharedPreferenceObj; // Declare Global 

Ahora llame a esto en la sección OnCreate

  sharedPreferenceObj=new SharedPreference(YourActivity.this); 

Ahora comprobando

 if(sharedPreferenceObj.getApp_runFirst()==null) { // That's mean First Time Launch // After your Work , SET Status NO sharedPreferenceObj.setApp_runFirst("NO"); } else { // App is not First Time Launch } 

¿Por qué no utilizar el Asistente de base de datos? Esto tendrá un bonito onCreate que sólo se llama la primera vez que se inicia la aplicación. Esto ayudará a aquellas personas que quieren seguir esto después de que la aplicación inicial se ha instalado sin seguimiento.

Me gusta tener un "recuento de actualización" en mis preferencias compartidas. Si no está allí (o el valor cero por defecto), este es el primer uso de mi aplicación.

 private static final int UPDATE_COUNT = 1; // Increment this on major change ... if (sp.getInt("updateCount", 0) == 0) { // first use } else if (sp.getInt("updateCount", 0) < UPDATE_COUNT) { // Pop up dialog telling user about new features } ... sp.edit().putInt("updateCount", UPDATE_COUNT); 

Así que ahora, cada vez que hay una actualización de la aplicación que los usuarios deben conocer, incremento UPDATE_COUNT

  /** * @author ALGO */ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.util.UUID; import android.content.Context; public class Util { // =========================================================== // // =========================================================== private static final String INSTALLATION = "INSTALLATION"; public synchronized static boolean isFirstLaunch(Context context) { String sID = null; boolean launchFlag = false; if (sID == null) { File installation = new File(context.getFilesDir(), INSTALLATION); try { if (!installation.exists()) { writeInstallationFile(installation); } sID = readInstallationFile(installation); launchFlag = true; } catch (Exception e) { throw new RuntimeException(e); } } return launchFlag; } private static String readInstallationFile(File installation) throws IOException { RandomAccessFile f = new RandomAccessFile(installation, "r");// read only mode byte[] bytes = new byte[(int) f.length()]; f.readFully(bytes); f.close(); return new String(bytes); } private static void writeInstallationFile(File installation) throws IOException { FileOutputStream out = new FileOutputStream(installation); String id = UUID.randomUUID().toString(); out.write(id.getBytes()); out.close(); } } > Usage (in class extending android.app.Activity) Util.isFirstLaunch(this); 

Hola chicos estoy haciendo algo como esto. Y sus obras para mí

Cree un campo booleano en la preferencia compartida. El valor predeterminado es true {isFirstTime: true} después de establecerlo por primera vez en false. Nada puede ser simple y confiable en el sistema android.

FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.