Welcome you all
in the “LIFECYCLE of an Activity” part 3.
In the part2 we have learnt, how to use onCreate(), onStart() and
onResume() system call. We have also seen how the Activity comes into RESUME
(visible) state.
In this part3, we will learn, how to use onPause(), onStop() and
onDestroy() system call. We will also learn how state change from RESUME to
PAUSED, PAUSED to STOP and STOP to DESTROY.
Step1: User Interface
of MainActivity
Add
one more Button into the MainActivity name as “Start Sub Activity”.
Please
add the following code into the activity_main.xml file.
Step2: Create a
New Activity
File à New à Other à Android à
AndroidActivity
Select BlankActivity, click Next.
Project:
LifeCycleDemo
Activity name: SubActivity
Click Finish.
Step3: Implement onPause(), onStop(),
onDestroy() system calls
Define
the onPause(), onStop() and onDestroy() system call into the MainActivity.
Create
a function that handles the “Start Sub Acivity” Button click event.
Please
add the following code into the MainActivity.java file:-
@Override
protected void onPause() {
super.onPause();
mStatusView.append("MainActivity: onPause()\n");
mStatusView.append("MainActivity: In PAUSED state ---\n");
}
@Override
protected void onStop() {
super.onStop();
mStatusView.append("MainActivity: onStop()\n");
mStatusView.append("MainActivity: In STOP state ---\n");
}
@Override
protected void onDestroy() {
super.onDestroy();
mStatusView.append("MainActivity: onDestroy()\n");
}
public void startSubActivity(View v)
{
Intent intent = new Intent(MainActivity.this, SubActivity.class);
startActivity(intent);
}
Step4: Implement all the lifecycle system calls
for SubActivity
Please modify the SubActivity.java file as
follows:-
package com.example.lifecycledemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class SubActivity extends Activity {
private TextView mStatusView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
mStatusView = (TextView) findViewById(R.id.status_current);
mStatusView.setText("SubActivity: onCreate()\n");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_sub, menu);
return true;
}
protected void onStart() {
super.onStart();
mStatusView.append("SubActivity: onStart()\n");
}
protected void onResume() {
super.onResume();
mStatusView.append("SubActivity: onResume()\n");
mStatusView.append("SubActivity: In RESUME state ---\n");
}
@Override
protected void onPause() {
super.onPause();
mStatusView.append("SubActivity: onPause()\n");
mStatusView.append("SubActivity: In PAUSED state ---\n");
}
@Override
protected void onStop() {
super.onStop();
mStatusView.append("SubActivity: onStop()\n");
mStatusView.append("SubActivity: In STOP state ---\n");
}
@Override
protected void onDestroy() {
super.onDestroy();
mStatusView.append("SubActivity: onDestroy()\n");
}
public void destroyActivity(View v) {
SubActivity.this.finish();
}
}
Step 5: Design User Interface for SubActivity
Please
modify the activity_sub.xml file as follows:-
Step 6: Compile and RUN the application.
Visible state of
MainActivity :-
Click the Start Sub_Activity Button, Now the State of MainActivity and State of SubActivity are as
follows:-
Today we are going to learn about the very important component of
android application “ACTIVTY” and it’s LIFECYCLE.
Like any other programming language like C, C++ or Java where the
execution of the code starts from the main() function.
In android same thing can be achieved by the ACTIVITY. In android application
main activity is behave like main() function.
What is an Activity?
An Activity provides a user
interface, from where the user can interact with our android application.
Each activity is a single
screen. An android application can have multiple activities.
Main activity is
same like any other activity but main activity is the one who interacts with the user first time when they
start the application.
An activity can start another
activity also in order to perform different actions.
Lifecycle of an Activity:-
The following
diagram shows the Lifecycle of an Activity:-
The key parts of the lifecycle
are the “system calls”.
With the help of these system
calls, activity changes his state from one to another.
There are only three main
states of the Lifecycle, which can be static.
They are:-
1)Resumed
2)Paused
3)Stopped
Resumed:-
In this state an activity is
visible to the user. User can interact with the activity at this time. We can
also refer this state as a “Running” state.
Paused:-
Suppose activity A is in
Resumed/Running state. At this time another activity B came up in the Running
state. Activity B has not covered the entire screen or we can say activity B is
semi-transparent.
This time activity A moved into the Paused state.
In Paused State, activity A
does not interact with the user and cannot execute any code.
Stopped:-
In this state activity is completely hidden or not
visible to the user.
We can say activity is running in the background.
In this state activity instance
and its state information like member variables are retained.
In this state also activity
cannot execute any code.
When user first time launches
the application, the system create the new instance of the Activity by calling
onCreate() method.
Once onCreate() finishes execution,
the system calls the onStart() and onResume() method and the Activity moved into the
Resumed/Running State.
onCreate() is the very first
lifecycle callback and onDestroy() is the very last.
It is not necessary to implement
all the lifecycle methods. It’s all depend on the requirement of the
application what we develop.
In the next part of ACTIVITY
LIFECYCLE, we will be writing some code and trying to understand how to start
an Activity and how to move from one state to another.
In today’s topic we will
create another activity which displays the First_Name and Last_Name on the
screen, send by the MainActivity of the GUI application.
Let’s start:-
Step 1: Define a function
that handles the onClick event of the Button
In MainActvity.java
add the following line :-
/* sendData handles the onClick event*/
public void sendData(View view) {
}
Must have
condition for the function that handles the onClick event are :-
·It must be public
·It must have a void return type
·It must have a View as the only parameter.
Step 2: Add the onClick attribute to the Button
android:onClick=”sendData”
sendData is the function which responds to the onClick event. Add onClick attribute on <BUTTON> element in activity_main.xml file.
Step 3: Binding of two Activities
Binding of separate
components can be achieved by the Intent object.
“Intent” provides the run-time
binding between separate components (for example between two activities).
Syntax:-
Intent intent = new Intent (this,
DisplayActivity.class);
Intent
constructor here takes two parameter.
·A Context as the first
parameter. We are passing this because Activity class is a subclass of Context.
·The Class of the application component
to which the system should deliver the Intent.
We should deliver the Intent to
the another activity named as DisplayActivity. We are going to create this
activity later.
Step 4: Create a message what you want to pass it to another
activity
We have designed
two Text-Fields in our GUI app.
We will fetch
those data and send it to another activity.
findViewById() we
are using to find the EditText according to id.
Our modified
MainActivity.java code will look like as follows:-
package com.example.firstgui;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "Message from MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/** Called when the user clicks the Send button */
public void sendData(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayActivity.class);
EditText editText = (EditText) findViewById(R.id.first_name);
String message = editText.getText().toString();
editText = (EditText) findViewById(R.id.last_name);
message += "__"+editText.getText().toString();
message ="Welcome , "+message;
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
In EXTRA_MESSAGE we are keeping
some constant message. Our modified activity_main.xml file will look like as follows:-
Step 5: Create the Second Activity
Steps to follow :-
a) File à New à Other à Android à
AndroidActivity
b) Select
BlankActivity, click Next.
c) Select the GUI
Project, “FirstGUI”
d) Activity name “DisplayActivity”
e) Hierarchical
Parent , select the MainActivity of the FirsrGUI app
f) Click Finish.
Step 6: Receive the Intent
We can get the
Intent by calling getIntent() function. We can also retrieve the data contained
within it.
Step 7: Display Message
We are using a
TextView widget to show the received message on the Screen.
Modify the
onCreate() of the DisplayActivity.java , as follow :-
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
Clean and Build your Project. Test it with Emulator or Android
Device.
Please give your valuable suggestions / comments. Do not forgot to share :)
This single bundle gives everything you need for developing apps.
1)Eclipse + ADT plugin
2)Android SDK Tools
3)Android Platform-tools
4)Simulator
Setting up the Developer Tool:-
1)Unzip the zip file named adt-bunlde-<os-platform>.zip and save it to some location where you want to save.
2)Move to adt-bundle-<os-platform>/eclipse/ directory and run the eclipse exe.
Create our first Android Project:-
The steps for creating a new Android Application are as follows:-
1)Go to File à New and click on Android Application Project.
2)Write your application name in the Application Name.
a.Project Name: is the name of your project directory.
b.Package Name: is the name package namespace.
c.Minimum Required SDK: is the lowest version of Android that your app support.
d.Target SDK: is the highest version of Android what your app support.
e.Compile With: is the platform version against which your app will compile.
f.Theme specifies: the Android UI style apply for your app.
3)Click on the next button.
4)Leave the next screen default and click on the next button.
5)Next screen is the launcher icon screen. You can customize also. Leave this screen as default , click on the next button.
6)Next screen belongs to the activity template. For this project select BlankActivity and click next button.
7)Leave the next screen default and do Finish.
Now your first android application is ready with some default files.
How to Run on the Emulator:-
First of all before running our application on the Emulator, we need to create an Android Virtual Device (AVD).
1)Click on the Android Virtual Device Manager.
The following image shows how AVD manager look like.
2)Click on New Button. Type AVD name. I have given Galaxy Nexus. Select Device, choose Galaxy Nexus device. We will try to run our application on Galaxy Nexus emulator.
3)Click on the OK button.
4)Select your AVD device and click on the start button.
5)Click on the Launch Button.
6)You might get some error like the following image.
7)To fix this error, select your AVD device and click on the edit button, change the ram size to 512.
8)Start your AVD once again. This will take some long time.
9)Then unlock your emulator screen.
10)Click Run Button from the toolbar.
This will run your first application on the Emulator.
Your application on the Emulator will look like this.
Porting of the application on an Android Device:-
1)Plug in your device to the development machine with a USB cable.
2)Enable USB DEBUGGING on your device.
a.On device Android 3.2 or older, you can find this option under Settings à Applications à Development.
b.On Android 4.0 and newer, it’s in Settings à Developer options.
On Android 4.2 and newer versions, Developer options is hidden by default. To make it available go to Setting à About phone and tap Build number seven times.
Return to previous screen to find the Developer option.
If you are developing on Windows then you might need to install a proper USB drive for you device.
If you are connected with net windows 7 will automatically install the proper driver.
The following link helps to install driver related things.