Activity in Android application is vital element which provides a screen to user to interact, for example taking a photo, reading message or dial pad. An application is merger of many activities or can be a single activity.
When an application starts, the main activity gets called and it gets visible to the user. Afterwards the main activity can call other activity and can pass some data to the other activity. While calling the other activity, when the new activity is called the previous activity gets stopped however the system preserves the activity in the stack.
When the activity gets stopped or created it follows the life cycle. So you can control the flow of data through the lifecycle throughout the application.
Creating an Activity:
While creating activity, extend Activity class. In the subclass all the call back methods can be included. The two most important methods are onCreate() and onPause(). In Android Studio, when you create an activity onCreate() method got created by default and this is the method where you define the view or UI. onPause() method is called when user is leaving your activity, so in this method you should commit any changes to database or for session.
You must have to declare your activity in manifest.xml file, so that Android can access your activity. In manifest.xml file you also define the activity to be launched when application is opened.
<manifest ... > <application ... > <activity android:name=".TestActivity" /> ... </application ... > ... </manifest >
Starting an Activity:
You can start another activity by startActivity() method and using intent. Intent is a messaging object you can use to request an action from another app component. You can use this method on button click or in the lifecycle of the app. One thing to consider while calling another activity is to finish the previous activity or else it’ll be there in the background. To finish the current activity use finish() method.
Intent i = new Intent(this, NextActivity.class); finish(); //Kill the activity from which you will go to next activity startActivity(i);