Execute code every time the application begins

瘦欲@ 提交于 2019-12-12 02:58:05

问题


I would like to execute code every time the application begins (not only the very first time the application begins so getSharedPreferences doesn't help).

I've tried to write the code in onStart() of the main Activity, but that code was executed everytime I entered the activity including times I back to this activity from other activities (so onStart() doesn't help).

If someone can direct me with this, I'll appreciate that. Thanks.


回答1:


Create an Application class - everytime an application opens it will execute the onCreate Method.

//Note extends Application and not Activity.
public class MyApplication extends Application {


@Override
public void onCreate() {
    super.onCreate();
   //Put your code here.
}

Make sure you register this in your manifest -

   <application
    android:name=".MyApplication"

Any code you put in onCreate will execute when the app is opened.




回答2:


You can use a flag,and that flag should be a public.

For example:

public boolean isFirstTime;

And your MainActivity's Oncreate()

if(!isFirsTime)
{ 
isFirstTime=true;
}else{
//do your stuff
}


来源:https://stackoverflow.com/questions/30533679/execute-code-every-time-the-application-begins

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!