10 Ocak 2017 Salı

ilk kez çalıştırma

SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
if (isFirstRun)
{
    // Code to run once
    SharedPreferences.Editor editor = wmbPreference.edit();
    editor.putBoolean("FIRSTRUN", false);
    editor.commit();
}


SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false)) {
    // run your one time code here
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("firstTime", true);
    editor.commit();
}


public void onCreate(Bundle savedInstanceState) {
  // don't forget to call super method.
  super.onCreate(savedInstanceState);

  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
  if (!prefs.getBoolean("firstTime", false)) {
    // <---- run your one time code here
    databaseSetup();

    // mark first time has runned.
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("firstTime", true);
    editor.commit();
  }
}
Don't forget to put activity declaration in manifest, as well as it's intentfilters (action = MAIN, category = LAUNCHER).
If you have more than one activity and you don't want to duplicate your startup logic you can just put your initialization logic in Application instance, that is created before all activities (and other components, such as services, broadcast recievers, content providers).
Just create class like that:
public class App extends Application {

  @Override
  public void onCreate() {
    super.onCreate();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (!prefs.getBoolean("firstTime", false)) {
      // <---- run your one time code here
      databaseSetup();

      // mark first time has runned.
      SharedPreferences.Editor editor = prefs.edit();
      editor.putBoolean("firstTime", true);
      editor.commit();
    }
}

Hiç yorum yok:

Yorum Gönder