如何在Android中首次启动应用程序?

时间:2014-01-17 05:04:24

标签: android

我正在开发一个应用程序,其中 第一次时间启动它,我想执行一些操作。现在我考虑使用共享首选项,直到我遇到了我必须在Oncreate上初始化它的困境,每次启动应用程序时,共享首选项都会被覆盖。

所以,我正在考虑检查特定类型变量本身是否存在于共享首选项,但我也被困在那里。现在有一种更简单的方式可以忽略吗?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分: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();
        }

第一次启动应用程序时,此共享首选项仅运行一次。 这对我有用。

答案 1 :(得分: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;
}

如果文件存在,则不是第一次其他第一次...

答案 2 :(得分: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" />