Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

java - Detect First Run

I am trying to detect if my app has been run before, by using this code:

(This is in my default Android activity)

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        Log.w("activity", "first time");
        setContentView(R.layout.activity_clean_weather);
    } else {

        Log.w("activity", "second time");
        setContentView(R.layout.activity_clean_weather);
    }


 }

When I first run the app it says first time, when I run it a second time, first time, and a third, first time....

I am using an actual Android device and I am not using the run button each time. I run the app once with the Eclipse run button, then I close the app and press on its icon on my phone.

Is there something wrong with my code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

savedInstanceState is more for switching between states, like pausing/resuming, that kind of thing. It must always be created by you, also.

What you want in this case is SharedPreferences.

Something like this:

public static final String PREFS_NAME = "MyPrefsFile"; // Name of prefs file; don't change this after it's saved something

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
    boolean firstRun = settings.getBoolean("firstRun", true); // Is it first run? If not specified, use "true"

    if (firstRun) {
        Log.w("activity", "first time");
        setContentView(R.layout.activity_clean_weather);

        SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
        editor.putBoolean("firstRun", false); // It is no longer the first run
        editor.commit(); // Save all changed settings
    } else {
        Log.w("activity", "second time");
        setContentView(R.layout.activity_clean_weather);
    }

}

I basically took this code directly from the documentation for Storage Options and applied it to your situation. It's a good concept to learn early.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...