Reputation: 20223
I have a litle android application where i would like to execute some code on the application launching.
How can I do this? I am a newbie on the Android developpement.
Upvotes: 3
Views: 1857
Reputation: 5142
I was in a similar situation. I needed to execute a method only once but onCreate()
, onStart()
and onResume()
methods didn't work for me because those methods are called when the device is rotated and in another situations.
So I decided to extend Application
and run that method in the onCreate()
of my custom application class because this is only run once per application start-up and because the tasks don't require long-running
Here is an example:
public class CustomApp extends Application {
public CustomApp() {
// This method fires only once per application start.
}
@Override
public void onCreate() {
super.onCreate();
// This method fires once as well as constructor
// & here we have application context
//Method calls
StaticClass.oneMethod(); // static method
Foo f = new Foo();
f.fooMethod(); // instance method
}
}
The next step is tell Android we have a custom Application class. We do it by referencing the custom application class in the 'android:name' attribute of the applcation tag. Like this:
<manifest ...
<application
android:name="com.package.example.CustomApp">
<activity>
<!-- activity configuration-->
</activity>
...
<activity>
<!-- activity configuration-->
</activity>
</application>
</manifest>
... For anyone to whom this may help you!
Upvotes: 3
Reputation: 1516
You may want to read about Activity: http://developer.android.com/reference/android/app/Activity.html
Android doesn't have a concept of application in the traditional sense, but a series of activities.
Put all initialization in Activity's onCreate()
Put code that you want to be run at the start of Activity in onStart()
Upvotes: 0
Reputation: 1271
Probably it is a good idea to read the Activity life-cycle before you start to develop.... http://developer.android.com/guide/topics/fundamentals/activities.html
Upvotes: 1
Reputation: 3215
In android, start, execution and termination of an application can be thought of as an execution of a state machine. onStart() method is executed by the application the moment android dispatches it for execution for the first time. You can override the onStart function and use your own code in there as follows
protected void onStart(){
super.onStart();
return_type method1(...);
.
.
.
}
Upvotes: 0
Reputation: 20223
you can use this:
protected void onStart()
{
super.onStart();
Your code here.....
}
Upvotes: 0