How can I execute something just once per application start?

前端 未结 10 1399
感情败类
感情败类 2020-11-28 06:45

I\'d like to implement an update checker in an application, and I obviously only need this to show up once when you start the application. If I do the call in the onCr

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 07:30

    I just solved doing this myself, I reopen my main activity multiple times throughout the application's execution. While the constructor is a valid approach for some things it doesn't let you access the current Application context to write toasts among other things.

    My solution was to create a simple 'firstRun' boolean set to true in the class of my MainActivity, from there I run the contents of the if statement then set it to true. Example:

    public class MainActivity extends AppCompatActivity
    {
         private static boolean firstRun = true;
    
         @Override
         protected void onCreate(Bundle savedInstanceState)
         {
             if(firstRun)
             {
                  Toast.makeText(getApplicationContext(), "FIRST RUN", Toast.LENGTH_SHORT).show();
                  //YOUR FIRST RUN CODE HERE
             }
             firstRun = false;
    
             super.onCreate(savedInstanceState);
             //THE REST OF YOUR CODE
    }
    

提交回复
热议问题