-1

How do I make something happen just at the very first time the app is launched, and then make something else happen during all the other time?

I need to save an Int, but at the very first time it needs to be 0, after that I'll have to find it back on my savedInstanceState bundle.

eleven
  • 6,779
  • 2
  • 32
  • 52
FET
  • 942
  • 4
  • 13
  • 35

2 Answers2

1

To check the first run of application you can refer following code and implemt accordingly

public class MyActivity extends Activity {

SharedPreferences prefs = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Perhaps set content view here

    prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
}

@Override
protected void onResume() {
    super.onResume();

    if (prefs.getBoolean("firstrun", true)) {
        // Do first run stuff here then set 'firstrun' as false
        // using the following line to edit/commit prefs
        prefs.edit().putBoolean("firstrun", false).commit();
    }
}

}

iamdeowanshi
  • 1,039
  • 11
  • 19
0

You can simply save a value in your SharedPreferences like below,

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    SharedPreferences mDefaultPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    if (mDefaultPreferences.getBoolean("first_launch", true))
    {
       mDefaultPreferences.edit().putBoolean("first_launch", false).commit();
       //Put the code here of your first launch
    }
    else
    {
       //Not the first launch

    }

}
Arsal Imam
  • 2,882
  • 2
  • 24
  • 35