How can I execute something just once per application start?

前端 未结 10 1402
感情败类
感情败类 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:06

    SharedPreferences seems like ugly solution to me. It's much more neat when you use application constructor for such purposes.

    All you need is to use your own Application class, not default one.

    public class MyApp extends Application {
    
        public MyApp() {
            // this method fires only once per application start. 
            // getApplicationContext returns null here
    
            Log.i("main", "Constructor fired");
        }
    
        @Override
        public void onCreate() {
            super.onCreate();    
    
            // this method fires once as well as constructor 
            // but also application has context here
    
            Log.i("main", "onCreate fired"); 
        }
    }
    

    Then you should register this class as your application class inside AndroidManifest.xml

     <------- here
        
            
                
                
            
        
    
    

    You even can press Back button, so application go to background, and will not waste your processor resources, only memory resource, and then you can launch it again and constructor still not fire since application was not finished yet.

    You can clear memory in Task Manager, so all applications will be closed and then relaunch your application to make sure that your initialization code fire again.

提交回复
热议问题