Chapter Three
Chapter Three
ACTIVITY
Activity
An App is a collection of activities, layouts, and other resources.
One of the activities is the main activity for the app.
By default, each app runs within its own process.
This helps keep your apps safe and secure. If the system identifies that
resources on the device are reaching capacity it will take steps to
terminate processes to free up memory.
When an activity needs to start, Android checks whether there’s already
a process for that app.
If one exists, Android runs the activity in that process. If one doesn’t exist,
Android creates one.
When Android starts an activity, it calls its onCreate() method.
onCreate() is always run whenever an activity gets created.
Cont’d
An activity will interact with the UI component (User Interface) by
using setContentView(View)
An activity provides the window in which the app draws its UI.
Generally one activity implements one(single) screen in an app.
To use activities in your app, you must register information about
them in the app’s manifest, and you must manage activity lifecycles
appropriately.
The life cycle states (and callbacks) are per activity not per
application, so we can implement different behavior at different
points in the lifecycle of each Activity.
Next, the Activity Stack and life cycle will be discussed
Activity Stack
For each application that is running on an Android device, the runtime
system maintains an Activity Stack.
When an application is launched, the first of the application’s activities
to be started is placed onto the stack.
When a second activity is started, it is placed on the top of the
stack and the previous activity is pushed down.
Life Cycle of Android Activity
Method When it is called NextMethod
onCreate() When the activity is first created. It also gives you a Bundle onStart()
that contains the previously saved state of the activity.
onRestart() When your activity has been stopped but just before it gets onStart()
started again.
onStart() When your activity is becoming visible. onResume() or
onStop()
onResume() When your activity is in the foreground. onPause()
onPause() When your activity is no longer in the foreground because onResume() or
another activity is resuming onStop()
On Destroy
theactivity is finishing (due to the user completely dismissing
the activity)
the
system is temporarily destroying the activity due to a
configuration change (such as device rotation, language)
Stop Watch Activity
Layout
Cont’d
Use
Linear Layout
Relative Layout or
Constraint Layout
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
Activity code public class StopwatchActivity extends Activity {
private int seconds = 0;
private boolean running;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
}
//Start the stopwatch running when the Start button is clicked.
public void onClickStart(View view) {
running = true;
}
//Stop the stopwatch running when the Stop button is clicked.
public void onClickStop(View view) {
running = false;
}
//Reset the stopwatch when the Reset button is clicked.
public void onClickReset(View view) {
running = false;
seconds = 0;
}
}
A Handler is an Android class you can use to schedule code that should
be run at some point in the future private void runTimer() {
To use the Handler, you wrap the code you wish to final TextView timeView =
(TextView)findViewById(R.id.time_view
schedule in a Runnable object, and then use the );
Handler post() and postDelayed() methods to specify final Handler handler = new Handler();
handler.post(new Runnable() {
when you want the code to run. @Override
The post() method posts code that needs to be run as public void run() {
int hours = seconds/3600;
soon as possible (which is usually almost immediately). int minutes = (seconds%3600)/60;
This method takes one parameter, an object of type int secs = seconds%60;
String time =
Runnable. String.format(Locale.getDefault(),
The postDelayed() method works in a similar way to the "%d:%02d:%02d", hours, minutes, secs);
timeView.setText(time);
post() method except that you use it to post code that
if (running) {
should be run in the future seconds++;
}
Two parameters: A Runnable and a long
handler.postDelayed(this, 1000);
}
});
Cont’d
Your Activity inherits the lifecycle methods
Context: An interface to global information
about the application environment allows access
to application resources, classes, and operations.
Activity: The Activity class implements default
versions of the lifecycle methods. It also defines
methods such as findViewById(Int) and
setContentView(View).
States of an Activity
The main state of an activity is when it’s running or active. An activity is running
when it’s in the foreground of the screen, it has the focus, and the
user can interact with it. Activity
Launched
The onCreate() method gets called immediately after your
activity is launched. This method is where you do all your normal
activity setup such as calling setContentView()
The onDestroy() method is the final call you get before the
Activity
activity is destroyed. There are a number of situations in which
Running
an activity can get destroyed
—for example, if it’s been told to finish, if the activity is being recreated due to a
change in device configuration, or if Android has decided to destroy the activity in
order to save space.
Activity
Destroyed
Save the current state (onCreate/
onDestroy)
When we change device configuration, like orientation the app will loss
local variables used by the activity.
How we restore the value?
We need to implement the onSaveInstanceState() method. This
method gets called before the activity gets destroyed, which means
you get an opportunity to save any values you want to retain before
they get lost.
onSaveInstanceState() method takes one parameter, a Bundle. A
Bundle allows you to gather together different types of data into a
single object.
public void onSaveInstanceState(Bundle savedInstanceState) {
}
Cont’d
Add this two codes in the activity
savedInstanceState.putBoolean("wasRunning", wasRunning);
wasRunning = savedInstanceState.getBoolean("wasRunning");
Implement onPause() to stop the
timer
When an activity is visible but doesn’t have the focus, the activity is
Paused. This can happen if another activity appears on top of your
activity that isn’t full-size or that’s transparent.
@Override
@Override
protected void onResume() {
protected void onPause() {
super.onResume();
super.onPause();
if (wasRunning) {
wasRunning = running;
running = true;
running = false;
}
}
}
Conclusion
Properly use the Activity Life cycle can help ensure that your app
avoids:
Consuming valuable system resources when the user is not
actively using it.
Losing the user’s progress if they leave your app and return to it
at a later time.
Crashing or losing the user’s progress when the screen rotates
between landscape and portrait orientation or switches to
another app while using your app.