How to execute code at application launch

I have a litle application for Android in which I would like to execute some code when the application starts.

How can i do this? I am new to Android development.

+4
source share
5 answers

you can use this:

protected void onStart() { super.onStart(); Your code here..... } 
+1
source

I was in a similar situation. I needed to execute the method only once, but the onCreate() , onStart() and onResume() methods did not work for me, because these methods are called when the device is rotated and in other situations.

So, I decided to extend Application and run this method in onCreate() my user-defined application class, because it is executed only once when the application starts and because the task does not require a long

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 to say Android, we have our own class of applications. We do this 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 those who can help you!

+2
source

It is probably a good idea to read the Activity Life Cycle before you begin to develop .... http://developer.android.com/guide/topics/fundamentals/activities.html

+1
source

In android, launching, executing, and terminating an application can be thought of as executing a state machine. The onStart () method is executed by the application when the android sends it for execution for the first time. You can override the onStart function and use your own code as follows

 protected void onStart(){ super.onStart(); return_type method1(...); . . . } 
0
source

You can read about Activity: http://developer.android.com/reference/android/app/Activity.html

Android does not have the concept of an application in the traditional sense, but represents a series of actions.

Put all initialization in Activity onCreate()

Put the code you want to run at the beginning of the action in onStart()

0
source

Source: https://habr.com/ru/post/1393279/


All Articles