0% found this document useful (0 votes)
0 views20 pages

Chapter Three

Chapter Three discusses the structure and lifecycle of activities in Android applications, emphasizing the importance of managing activity states and interactions with the user interface. It outlines the Activity Stack, the various lifecycle methods such as onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(), and how to save and restore the activity state. Proper handling of these lifecycle methods is crucial to optimize resource usage and maintain user progress during app usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views20 pages

Chapter Three

Chapter Three discusses the structure and lifecycle of activities in Android applications, emphasizing the importance of managing activity states and interactions with the user interface. It outlines the Activity Stack, the various lifecycle methods such as onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(), and how to save and restore the activity state. Proper handling of these lifecycle methods is crucial to optimize resource usage and maintain user progress during app usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

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()

onStop() When the activity is no longer visible onRestart() or


onDestroy()
onDestroy() When your activity is about to be destroyed or None
because the activity is finishing.

Fig Visual Representation of the Activity lifecycle


 This are some examples that shows when call backs methods will be
called
 On Pause:
 Some event interrupts app execution, like receiving a phone
call, the user’s navigating to another activity, or the device
screen’s turning off.
 InAndroid 7.0 (API level 24) or higher, multiple apps run in
multi-window mode. Because only one of the apps (windows)
has focus at any time, the system pauses all of the other apps.
A new, semi-transparent activity (such as a dialog) opens. As
long as the activity is still partially visible but not in focus, it
remains paused.
Cont’d
 On Stop
 when a newly launched activity covers the entire screen
 The user navigates to the device’s home screen

 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

Save the values of the Restore the state in onCreate.


seconds and running protected void onCreate(Bundle
variables to the Bundle. savedInstanceState) {
@Override super.onCreate(savedInstanceState);
public void setContentView(R.layout.activity_stopwatch);
onSaveInstanceState(Bundle if (savedInstanceState != null) {
savedInstanceState) { seconds =
savedInstanceState.putInt("seconds", savedInstanceState.getInt("seconds");
seconds); running =
savedInstanceState.putBoolean("runni savedInstanceState.getBoolean("running");
ng", running); }
} runTimer();
}
Cont’d
 There are additional lifecycle methods which deal with activity’s
visibility. onStart(), onStop(), and onRestart()
 We inherit from Android Activity class like onCreate() and
onDestroy().
 onStart() gets called when your activity becomes visible to the user.
 onStop() gets called when your activity has stopped being visible to
the user. This might be because it’s completely hidden by another
activity that’s appeared on top of it
 onRestart() gets called after your activity has been made invisible,
before it gets made visible again.
Implement onStop() to stop the
timer
 We have to add a new variable to record whether the stopwatch
was running before the onStop() method was called so that we
know whether to set it running again when the activity becomes
visible again.
@Override
@Override
protected void onStart() {
protected void onStop() {
super.onStart();
super.onStop();
if (wasRunning) {
wasRunning = running;
running = true;
running = false;
}
}
}

 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.

You might also like