2014-01-17 2 views
1

Я разрабатываю приложение, в котором для толькосначала время запуска, я хочу выполнить некоторые действия. Теперь я рассмотрел использование общих настроек, пока я не столкнулся с дилеммой, которую я должен был бы инициализировать на самой Oncreate, и каждый раз, когда я запускаю приложение, общие настройки будут перезаписаны.Как отслеживать, запускается ли приложение в первый раз в Android?

Итак, я рассматриваю возможность проверки того, существует ли конкретная переменная типа на Общие настройки или нет, но я тоже там застрял. Теперь есть более простой способ, с которым я не обращаю внимания? Любая помощь будет принята с благодарностью.

+0

поместить код инициализации вашего общего предпочтения в если еще блоке, проверить, что значение общего предпочтения есть! – Skynet

+0

Вы имели в виду, что вы не хотите этого, если (! Prefs.getBoolean («firstTime», false)) {// Первый запуск кода} –

ответ

5

Используйте этот первый раз SharePrefrences код:

SharedPreferences prefs = PreferenceManager 
       .getDefaultSharedPreferences(this); 
     if (!prefs.getBoolean("Time", false)) { 

          // run your one time code 

      SharedPreferences.Editor editor = prefs.edit(); 
      editor.putBoolean("Time", true); 
      editor.commit(); 
     } 

Этот sharedpreference запускается только один раз при первом запуске приложения. Это работа для меня.

1

Для этого нужно проверить, как это ..

/** 
* checks for the whether the Application is opened first time or not 
* 
* @return true if the the Application is opened first time 
*/ 
public boolean isFirstTime() { 
    File file = getDatabasePath("your file"); 
    if (file.exists()) { 
     return false; 
    } 
    return true; 
} 

, если файл существует его не в первый раз, другой мудрый его в первый раз ..

+0

Это тоже неплохой путь! – Skynet

+0

Еще одна вещь, которую нужно добавить, если файл не существует, то создайте новый, иначе этот код будет каждый раз возвращать true. – Hulk

0

SharePreferences - хороший выбор.

public class ShortCutDemoActivity extends Activity { 

// Create Preference to check if application is going to be called first 
// time. 
SharedPreferences appPref; 
boolean isFirstTime = true; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    // Get preference value to know that is it first time application is 
    // being called. 
    appPref = getSharedPreferences("isFirstTime", 0); 
    isFirstTime = appPref.getBoolean("isFirstTime", true); 

    if (isFirstTime) { 
     // Create explicit intent which will be used to call Our application 
     // when some one clicked on short cut 
     Intent shortcutIntent = new Intent(getApplicationContext(), 
       ShortCutDemoActivity.class); 
     shortcutIntent.setAction(Intent.ACTION_MAIN); 
     Intent intent = new Intent(); 

     // Create Implicit intent and assign Shortcut Application Name, Icon 
     intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); 
     intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Shortcut Demo"); 
     intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, 
       Intent.ShortcutIconResource.fromContext(
         getApplicationContext(), R.drawable.logo)); 
     intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); 
     getApplicationContext().sendBroadcast(intent); 

     // Set preference to inform that we have created shortcut on 
     // Homescreen 
     SharedPreferences.Editor editor = appPref.edit(); 
     editor.putBoolean("isFirstTime", false); 
     editor.commit(); 

    } 
} 

}

и изменить AndroidManifest.xml

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /> 
Смежные вопросы