Lab - 3a - Activity Life Cycle
Lab - 3a - Activity Life Cycle
Lab - 3a - Activity Life Cycle
Sem. I 2019/2020
Lab 3a: Android Activity Lifecycle
Introduction
Method Description
onCreate Called when activity is first created.
onStart Called when activity is becoming visible to the user.
onResume Called when activity will start interacting with the user.
onPause Called when activity is not visible to the user.
onStop Called when activity is no longer visible to the user.
onRestart Called after your activity is stopped, prior to start.
onDestroy Called before the activity is destroyed.
1
PART I
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
package com.example.Lab3a;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Android Lifecycle", "onCreate() invoked");
}
@Override
protected void onStart() {
super.onStart();
2
Log.d("Android Lifecycle", "onStart() invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("Android Lifecycle", "onResume() invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("Android Lifecycle", "onPause() invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("Android Lifecycle", "onStop() invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("Android Lifecycle", "onRestart() invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("Android Lifecycle", "onDestroy() invoked");
}
}
Figure 2: Lab3a
3
See the Logcat window: onCreate(), onStart() and onResume() methods
are invoked.
Now click on the HOME button. Then see onPause() method is invoked. Then, the
onStop() method is invoked.
On the emulator. It is on the home. Now click on the center button to launch the app
again.
4
Click on the Lab3a icon
Click on the back button. See onPause() method is invoked. After a while,
onStop() and onDestroy() methods are invoked.
PART II
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
5
Step 2: Use the Toast widget to show the LifeCycle methods.
Replace the Log class with the Toast class for every method in the MainActivity
file.
Toast.makeText(MainActivity.this,"ON CREATE",
Toast.LENGTH_SHORT).show();