0% found this document useful (0 votes)
422 views35 pages

5.2 Activity Life Cycle, Broadcast Life Cycle

Uploaded by

Pranita Badale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
422 views35 pages

5.2 Activity Life Cycle, Broadcast Life Cycle

Uploaded by

Pranita Badale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Android Activity Lifecycle-

Activity class is one of the very important parts of the Android component. Any app, don’t matter how much small it
is (in terms of code and scalability), it has at least one Activity class.
-An activity provides the window in which the app draws its UI. This window typically fills the screen, but may be
smaller than the screen and float on top of other windows.
-Every activity contains the layout, which has a user interface to interact with the user.
- Layout for a particular activity is set with the help of setContentView()
Android Activity Lifecycle
Android Activity Lifecycle methods

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.
Logcat command-line tool -
The Logcat window in Android Studio displays system messages, such as when a garbage collection occurs, and
messages that you added to your app with the Log class. It displays messages in real time and keeps a history so you can view
older messages.
Logcat Window is the place where various messages can be printed when an application runs. Suppose, you are
running your application and the program crashes, unfortunately. Then, Logcat Window is going to help you to debug the
output by collecting and viewing all the messages that your emulator throws. So, this is a very useful component for the app
development because this Logcat dumps a lot of system messages and these messages are actually thrown by the emulator.
This means, that when you run your app in your emulator, then you will see a lot of messages which include all
the information, all the verbose messages, all the errors that you are getting in your application. Suppose, an application of
about 10000 lines of code gets an error. So, in that 10000 line codes, to detect the error Logcat helps by displaying the error
messages.
Errors in different modules and methods can be easily detected with the help of Logcat window.
Write log messages
The Log class allows you to create log messages that appear in logcat. Generally, you should use the following
log methods, listed in order from the highest to lowest priority (or, least to most verbose):

Log.e(String, String) (error)


Log.w(String, String) (warning)
Log.i(String, String) (information)
Log.d(String, String) (debug)
Log.v(String, String) (verbose)

Logcat example-
Broadcast receiver lifecycle-
In android, Broadcast Receiver is a component that will allow an android system or other apps to deliver events to
the app like sending a low battery message or screen turned off the message to the app. The apps can also initiate broadcasts
to let other apps know that required data available in a device to use it.

Some Android broadcast receiver examples – low battery notification in the notification bar by the system,
notification to other applications when something downloads, so they can use it when required.
Broadcast receiver lifecycle-
A broadcast receiver has single callback method:
void onReceive(Context curContext, Intent broadcastMsg)
When a broadcast message arrives for the receiver, Android calls its onReceive() method and passes it the Intent
object containing the message. The broadcast receiver is considered to be active only while it is executing this method. When
onReceive() returns, it is inactive.
A process with an active broadcast receiver is protected from being killed. But a process with only inactive
components can be killed by the system at any time, when the memory it consumes is needed by other processes.
 There are two types of broadcasts:
1. System broadcasts are delivered by the system.
2. Custom broadcasts are delivered by your app.
1. System broadcasts-
A system broadcast is a message that the Android system sends when a system event occurs. System broadcasts are
sent to all apps that are subscribed to receive the event.
some system-generated Intents which are important and are generally used:
1. android.intent.action.BATTERY_CHANGED – This keeps track of the battery’s charging state, percentage, and other
information about the battery.
2. android.intent.action.BATTERY_LOW – It indicates the low battery condition.
3. android.intent.action.POWER_CONNECTED – It indicates that the power is connected to the device.
4. android.intent.action.POWER_DISCONNECTED – The power is disconnected from the device.
5. android.intent.action.BOOT_COMPLETED – This broadcast is shown only once when the device boots for the first time.
6. android.intent.action.CALL – This intent is to perform a call to some specific person, according to data.
7. android.intent.action.DATE_CHANGED – This means the date of the device has changed.
8. android.intent.action.REBOOT – This means that the device has rebooted.
9. android.intent.action.CONNECTIVITY_CHANGE – This shows the network connectivity of the device has changed.
10. android.intent.action.BUG_REPORT – This reports the bugs if there is any.
11. android.intent.action.CALL_BUTTON – The user pressed the call button to make a call, which takes them to an
appropriate user interface.

2. Custom broadcasts-
Custom broadcasts are broadcasts that your app sends out. To create a custom broadcast, define a
custom Intent action.
For example, use a custom broadcast when you want to let other apps know that data has been downloaded to the device
and is available for them to use.
 BroadcastReceiver-
Broadcast receivers are app components that listen for the events that have been broadcast from apps or from the
Android system and respond accordingly.
For instance, if you are implementing a media app and you’re interested in knowing when the user connects or disconnects a
headset, register for the ACTION_HEADSET_PLUG intent action.

Follow the two steps to make BroadcastReceiver works for your application:
1. Creating the Broadcast Receiver
2. Registering a BroadcastReceiver / Receiving Broadcasts
1. Creating the Broadcast Receiver.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the onReceive()
method where each message is received as a Intent object parameter.
Example-
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
2. Registering Broadcast Receiver-
There are two ways that we can register a broadcast receiver:
1. Statically receivers using <receiver> a tag in the manifest file.
2. Dynamically receivers at the class level by calling registerReciever(receiverClassInstance).
1. Statically
These types of Receivers are declared in the manifest file and works even if the app is closed. One way is by
registering broadcasts using an android application manifest file (AndroidManifest.xml). We need to
specify <receiver> element in apps manifest file like as shown below.

Example- To register a manifest-declared receiver, include the following attributes inside the <receiver> element in your
AndroidManifest.xml file:
<receiver android:name=".MyReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.BATTERY_LOW" />
</intent-filter>
</receiver>

android: name: name of the BroadcastReceiver subclass.


android: exported (optional): If this boolean value is set to false, other apps cannot send broadcasts to your receiver.
<intent-filter>: specify the broadcast Intent actions that your broadcast receiver component is listening for.
 Sending Broadcasts-
In android, we can send a broadcasts in apps using three different ways, those are

Method Description
sendOrderedBroadcast(Intent, String) This method is used to send broadcasts to one
receiver at a time.

sendBroadcast(Intent) This method is used to send broadcasts to all


receivers in an undefined order.

LoadBroadcastManager.sendBroadcast This method is used to send broadcasts to


receivers that are in the same app as the sender.
Example- 1
Example- 2
public void onReceive(Context context, Intent intent) {
if(intent.getAction()==Intent.ACTION_DATE_CHANGED)
{
Toast.makeText(context,"Date Changed...",Toast.LENGTH_LONG).show();
}
if(intent.getAction()==Intent.ACTION_TIMEZONE_CHANGED)
{
Toast.makeText(context,"Time Zone Changed...",Toast.LENGTH_LONG).show();
}
if(intent.getAction()==Intent.ACTION_TIME_CHANGED)
{
Toast.makeText(context,"Time Changed...",Toast.LENGTH_LONG).show();
}
Example- 3

public void onReceive(Context context, Intent intent)


{

if (isAirplaneModeOn(context.getApplicationContext()))
{
Toast.makeText(context, "AirPlane mode is on", Toast.LENGTH_SHORT).show();
}
Else
{
Toast.makeText(context, "AirPlane mode is off", Toast.LENGTH_SHORT).show();
}
}
2. Dynamically-
These types of receivers work only if the app is active or minimized. The dynamic receivers will run if the
application is running
For creating a dynamic receiver we don't need to add the receiver in the manifest file. We need to create this
through the java code.
For register Receiver dynamically registerReceiver(Action Type) method is used.
For unregister receiver unregisterReceiver(Object of Receiver);
Syntax-
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
public abstract Intent registerReceiver (BroadcastReceiver receiver, IntentFilter filter);

Example-
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(airplaneModeChangeReceiver, filter);
Example- broadcastextra
Example- dynamic broadcast Receiver-
2. Custom broadcasts-
In addition to responding to system events , your app can respond to Custom events also.For Custom Broadcast
we need to define our own actions in Intent object and broadcast it to receiver.
For example, use a custom broadcast when you want to let other apps know that data has been downloaded to
the device and is available for them to use.
custom broadcast example
Service
In android, Service is a component which keep an app running in the background to perform long-running
operations based on our requirements. For Service, we don’t have any user interface and it will run the apps in the
background like playing the music in the background or handle network operations when the user in a different app.
The service runs in the background indefinitely even if application is destroyed
 Features of Service
• Service is an Android Component without an UI
• It is used to perform long running operations in background.
• Services run indefinitly unless they are explicitly stopped or destroyed
• It can be started by any other application component. Components can even infact bind to a service to perform
Interprocess- Comminication
• It can still be running even if the application is killed unless it stops itself by calling stopself() or is stopped by a Android
component by calling stopService().
• If not stopped it goes on running unless is terminated by Android due to resource shortage
• The android.app.Service is subclass of ContextWrapper class.
Types of services-
1. Foreground Services:
Foreground services are those services that are visible to the users. The users can interact with them at ease and
track what’s happening. These services continue to run even when users are using other applications.
The perfect example of this is Music Player and Downloading.

2. Background Services:
These services run in the background, such that the user can’t see or access them. These are the tasks that don’t
need the user to know them. These services do not notify the user about ongoing background tasks and users also cannot
access them.
Syncing and Storing data can be the best example.

3. Bound Services:
Bound service runs as long as some other application component is bound to it. Many components can bind to one
service at a time, but once they all unbind, the service will destroy.
Life Cycle of Android Service
There can be two forms of a service. The lifecycle of service can follow two different paths:
started or bound.
1) Started Service
A service becomes started only when an application component calls startService(). It performs a single operation
and doesn’t return any result to the caller. Once this service starts, it runs in the background even if the component that
created it destroys. This service can be stopped only in one of the two cases:
By using the stopService() method.
By stopping itself using the stopSelf() method.
2) Bound Service
A service is bound only if an application component binds to it using bindService(). It gives a client-server relation
that lets the components interact with the service. The components can send requests to services and get results.
This service runs in the background as long as another application is bound to it. Or it can be unbound according
to our requirement by using the unbindService() method.
Life Cycle of Android Service
 Methods of Service life cycle-
1. onStartCommand()-
The system calls this method whenever a component, say an activity requests ‘start’ to a service, by
calling startService(). Once we use this method it’s our duty to stop the service using stopService() or stopSelf().

2. onBind()-
This is invoked when a component wants to bind with the service by calling bindService(). In this, we must provide
an interface for clients to communicate with the service. For interprocess communication, we use the IBinder object.
It is a must to implement this method. If in case binding is not required, we should return null as implementation is
mandatory.

3. onUnbind()-
The system invokes this when all the clients disconnect from the interface published by the service.
4. onRebind()-
The system calls this method when new clients connect to the service. The system calls it after the onBind() method.

5. onCreate()-
This is the first callback method that the system calls when a new component starts the service. We need this
method for a one-time set-up.

6. onDestroy()-
This method is the final clean up call for the system. The system invokes it just before the service destroys. It cleans
up resources like threads, receivers, registered listeners, etc.
Create a Service-
Generally, in android to create a service we must create a subclass of Service or use one of existing subclass. In
android the application component such as an activity can start the service by calling startService() which results in calling the
service’s onStartCommand() method.
Following is the simple example of creating a service in android application.
public class SampleService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO write your own code
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
Register a Service in Manifest File-
Once we create a service, we need to register that in android manifest file using <service> element like as shown below.
<manifest ... >
...
<application ... >
<service android:name=".SampleService" />
</application>
...
</manifest>
 Start a Service-
In android, the component such as an activity, service or receiver can start the service using startService() method.
Following is the sample code snippet of starting a service using the startService method.
Intent intent = new Intent(this, MyService.class);
startService(intent);
The onStartCommand() method will return a value from one of the following constants.-

1. START_STICKY - tells the OS to recreate the service after it has enough memory and call onStartCommand()
again with a null intent.

2. START_NOT_STICKY - tells the OS to not bother recreating the service again.

3. START_REDELIVER_INTENT - tells the OS to recreate the service and redeliver the same intent to
onStartCommand().
Example 1- The following skeleton service demonstrates each of the life cycle methods −
Example- 2
Example- 3

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy