Introduction
An Activity is a sub-container within an application container that describes all the UI controls.
Every Container has a life cycle (methods) that determine the phase's Activity.
To create an Activity in Android we have to extend the Activity class.
How to work with an Activity?
An Image view of an Activity's life cycle:
The following is the source code.
MainActivity.java
- package com.Saving.savingactivity;
- import android.os.Bundle;
- import android.app.Activity;
-
- import android.widget.Toast;
- public class MainActivity extends Activity {
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
- Toast.makeText(getBaseContext(), "Restored ", Toast.LENGTH_LONG).show();
- };
- @Override
- protected void onStart() {
-
- super.onStart();
- Toast.makeText(getBaseContext(), "Started ", Toast.LENGTH_LONG).show();
- }
- @Override
- protected void onResume() {
-
- super.onResume();
- Toast.makeText(getBaseContext(), "Resumed ", Toast.LENGTH_LONG).show();
- }
- @Override
- protected void onPause() {
-
- super.onPause();
- Toast.makeText(getApplicationContext(), "Paused ", Toast.LENGTH_LONG).show();
- }
- @Override
- protected void onSaveInstanceState(Bundle outState) {
-
- super.onSaveInstanceState(outState);
- Toast.makeText(getApplicationContext(), "Saved ", Toast.LENGTH_LONG).show();
- }
- @Override
- protected void onStop() {
-
- super.onStop();
- Toast.makeText(getApplicationContext(), "Stoped ", Toast.LENGTH_LONG).show();
- }
- @Override
- protected void onDestroy() {
-
- super.onDestroy();
- Toast.makeText(getApplicationContext(),"Destroy ", Toast.LENGTH_LONG).show();
- }
- }
Activity_main.xml
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity"
- android:layout_centerHorizontal="true"
- android:layout_centerVertical="true">
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/hello_world" />
- </LinearLayout>
Step 1
First of all, an Activity is creates on a pre-defined Layout by the "onCreate" method.
Step 2
After that, the Activity will start in the "onStart" method.
Step 3
After starting the "onResume" method displays your current UI.
Step 4
After "onResume" if we kill or auto kills the UI then the UI calls the "onPause" method.
Step 5
After "onPause" for the current UI, the UI call goes to the "onSave" method.
Step 6
The "onSave" method may be called after "onPause" or "onStop"; it depends on the condition in which the UI is killed.
Step 7
If we kill the process or active UI then that goes directly to destroy (without saving the current UI ) by the "onDestroy" method.
Otherwise, it goes to "onStop" (step 4).