Android Activity onInitialize
Question
I would like to do some action only once, when the app starts. Therefore, I tried to place the code within the main acitivity's onCreate, but this is triggered again and again when the user comes back to the main activity and/or when the device orientation changes. Which event fits better for my use-case?
La solution
write the code in application level.
Class MyClass extends Application
{
@Override
public void onCreate() {
//your code. This will be executed only once.i.e. when app is started.
super.onCreate();
}
}
You need to declare this class in androidmanifest.xml also .As shown
<application
android:name=".MyClass"
android:icon="@drawable/logo"
android:label="@string/str_app_name"
android:theme="@android:style/Theme.NoTitleBar"
>
Autres conseils
Create a static boolean, and check if this boolean is already set or not
for e.g
private static boolean flag = false;
// perform this check inside oncreate
if(!flag){
// peform task
flag = true;
}
This will make your code run only once, when the program starts.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow