Android questions for Computer Science and MCA students
Define Android activity and its life cycle with example.
An activity is a screen that contains the user interface. User can interact with these activities to perform some task such as send an email, send messages or taking the photo. The main purpose of an activity is to interact with the user.
When you run your android application, Activity goes through different states and the following callback methods are called by system.
- onCreate(): Called when the activity is first created. You can write the code for initializing the control/view.
- onStart(): This method is called when the activity becomes visible to the user.
- onResume(): It is called when the activity starts interacting with the user.
- onPause(): It is called when the current activity is being paused and the previous activity is being resumed. Activity is not destroyed, but it is invisible.
- onStop(): It is called when the activity is stopped and not visible to the user.
- onDestroy(): It is called before the activity is destroyed by the system call.
- onRestart(): It is called when the activity has been stopped and is restarting again.
Example:
Following is the content of the modified MainActivity.java file
publicclassMainActivityextends Activity
{
@Override
protectedvoidonCreate (Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
Toast.makeText (this,"ON CREATE", Toast.LENGTH_SHORT).show();
}
@Override
protectedvoidonStart()
{
// TODO Auto-generated method stub
super.onStart();
Toast.makeText (this,"ON START", Toast.LENGTH_SHORT).show();
}
@Override
protectedvoidonResume()
{
// TODO Auto-generated method stub
super.onResume();
Toast.makeText (this,"ON RESUME", Toast.LENGTH_SHORT).show();
}
@Override
protectedvoidonPause()
{
// TODO Auto-generated method stub
super.onPause();
Toast.makeText (this,"ON PAUSE", Toast.LENGTH_SHORT).show();
}
@Override
protectedvoidonRestart()
{
// TODO Auto-generated method stub
super.onRestart();
Toast.makeText (this,"ON RESTART", Toast.LENGTH_SHORT).show();
}
@Override
protectedvoidonStop()
{
// TODO Auto-generated method stub
super.onStop();
Toast.makeText (this,"ON STOP", Toast.LENGTH_SHORT).show();
}
@Override
protectedvoidonDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText (this,"ON DESTROY", Toast.LENGTH_SHORT).show();
}
}
When you run the above code, you will see the output as follows:
- It will show you three toast messages that come after one another. First is ON CREATE, second is ON START and third is ON RESUME.
- When you press the home button from the android virtual device, ON PAUSE and ON STOP methods call.
- When you open the application again Toast message displays ON RESTART, ON START and ON RESUME.
- When you press the back button from android virtual device, ON PAUSE, ON STOP and ON DESTROY message displays.