0% found this document useful (0 votes)
4 views62 pages

Understanding Android Intents and Lifecycle

Chapter 5 covers the Android Activity Lifecycle, detailing the role of intents in communication between app components, including implicit and explicit intents. It explains how to create and manage broadcast receivers for system events, as well as the use of content providers for data sharing among applications. Additionally, the chapter introduces fragments as UI components within activities, outlining their lifecycle and implementation in Android applications.

Uploaded by

waghvrushali28
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)
4 views62 pages

Understanding Android Intents and Lifecycle

Chapter 5 covers the Android Activity Lifecycle, detailing the role of intents in communication between app components, including implicit and explicit intents. It explains how to create and manage broadcast receivers for system events, as well as the use of content providers for data sharing among applications. Additionally, the chapter introduces fragments as UI components within activities, outlining their lifecycle and implementation in Android applications.

Uploaded by

waghvrushali28
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

Chapter – 5

 Android Activity Lifecycle is controlled by 7 methods of


[Link] class.
 The android Activity is the subclass of ContextThemeWrapper class.
 An activity is the single screen in android. It is like window or frame of
Java.
 By the help of activity, you can place all your UI components or
widgets in a single screen.
Intent

 Intent is a messaging object which is used to request an action from


another app component such as activities, services,
broadcast receivers and content providers.

 Generally in android, Intents will help us to maintain the


communication between app components from the same application as
well as with the components of other applications.

 In android, Intents are the objects of [Link] type


and intents are mainly useful to perform following things.
Implicit Intent

 The implicit intent is the intent where instead of defining the exact
components, you define the action that you want to perform for different
activities.
 An Implicit intent specifies an action that can invoke any app on the
device to be able to perform an action.
 Using an Implicit Intent is useful when your app cannot perform the
action but other apps probably can and you’d like the user to pick which
app to use.
 Syntax:
Intent i=new Intent();
[Link](Intent.ACTION_SEND);
 Create an Implicit Intent

 You need to make an Intent object. The constructor of the Implicit Intent's
object needs a type of action you want to perform.

 An action is a string that specifies the generic action to be performed. The


action largely determines how the rest of the intent is structured,
particularly the information that is contained as data and extras in the
intent object. For example,

 ACTION_VIEW: This action is used when you have some information that an
activity can show to the user, such as a photo to view in a Gallery app, or
an address to view in a Map app.
 ACTION_SEND: This action is used when you have some data that the user
can share through another app, such as an Email app or some Social
Networking app.
 ACTION_DIAL: Display the phone dialer with the given number filled in.

 Intent i = new Intent(Intent.ACTION_VIEW);


 You need to provide some data for the action to be performed. Data is
typically expressed as a URI(Uniform Resource Identifier) which provides
data to the other app so that any other app which is capable of handling the
URI data can perform the desired action. For example, if you want to open a
website through your app, you can pass the Uri data
using setData() method as follows:

[Link]([Link]("[Link]

 Call startActivity() method in the end with the intent object as the
parameter.

startActivity(i);
Explicit Intent

 When you explicitly define which Android component should be opened


on some user action, then you use explicit intents.
 You generally use an explicit intent to start a new component in your
own app, because you know which exact activity or service you want
to start.
 For example, you can start a new activity in response to a user action
or start a service to download a file in the background.
 Create an Explicit Intent
 You need to make an Intent object. The constructor of the Explicit Intent's
object needs two parameters as follows:
 Context c: This represents the object of the Activity from where you are calling the
intent.
 Java file name: This represents the name of the java file of the Activity you want
to open.
 Note: You need to mention the java file name with .class extension

Intent i = new Intent(this, [Link]);


 Call startActivity() method and pass the intent's object as the parameter.
This method navigates to the java file mentioned in the Intent's object.
startActivity(i);
 If you need to pass some information or data to the new Activity you are
calling, you can do this by calling putExtra() method before the
startActivity() method. This method accepts key-value pair as its parameter.
[Link]("key1", "I am value1");
[Link]("key2", "I am value2");
startActivity(i);
o Note: To receive the data in the new Activity and use it accordingly, you
need to call the getIntent() method and then getStringExtra() method in the
java class of the Activity you want to open through explicit intent.
getStringExtra() method takes the key as the parameter
String a = getIntent().getStringExtra("key1");
o Doing this, stores the value stored at key1 into the string variable a.
Intent Filter

 Intent Filter is an expression in app’s manifest file


([Link]) and it is used to specify the type of intents
that the component would like to receive. In case if we create Intent
Filter for an activity, there is a possibility for other apps to start our
activity by sending a certain type of intent otherwise the activity can
be started only by an explicit intent.

 Generally, the Intent Filters (<intent-filter>) whatever we define in


manifest file can be nested in the corresponding app components and
we can specify the type of intents to accept using these three
elements.
<action>

It defines the name of an intent action to be accepted and it must be a literal


string value of an action, not the class constant.

<category>

It defines the name of an intent category to be accepted and it must be the literal
string value of an action, not the class constant.

<data>

It defines the type of data to be accepted and by using one or more attributes we
can specify various aspects of the data URI (scheme, host, port, path) and MIME
type.
Broadcast Intent

 Android apps can send or receive broadcast messages from the


Android system and other Android apps.
 For example, the Android system sends broadcasts when various
system events occur, such as when the system boots up or the device
starts charging.
System Broadcast
Broadcast Receiver

 Broadcast Receivers simply respond to broadcast messages from other applications or


from the system itself. These messages are sometime called events or intents.

 There are following two important steps to make BroadcastReceiver works for the system
broadcasted intents −
 Creating the Broadcast Receiver.
 Registering Broadcast Receiver
 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.

public class MyReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
[Link](context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
 Registering Broadcast Receiver
 A BroadcastReceiver can be registered in two ways.
 By defining it in the [Link] file as shown below.
<receiver android:name=".ConnectionReceiver" >
<intent-filter> <action android:name="[Link].CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
 By defining it programmatically
Following snippet shows a sample example to register broadcast receiver
programmatically.
IntentFilter filter = new IntentFilter();
[Link](getPackageName() +
"[Link].CONNECTIVITY_CHANGE");
MyReceiver myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);
 To unregister a broadcast receiver in onStop() or onPause() of the activity the following
snippet can be used.
@Override
protected void onPause()
{
unregisterReceiver(myReceiver);
[Link]();
}
 The following table lists a few important system events.
[Link].BATTERY_CHANGED

[Link].BATTERY_LOW

[Link].BATTERY_OKAY

[Link].BOOT_COMPLETED

[Link].BUG_REPORT

[Link]

[Link].CALL_BUTTON

[Link].DATE_CHANGED

[Link]
 Broadcasting Custom Intents
 If you want your application itself should generate and send custom intents
then you will have to create and send those intents by using
the sendBroadcast() method inside your activity class.
 If you use the sendStickyBroadcast(Intent) method, the Intent is sticky,
meaning the Intent you are sending stays around after the broadcast is
complete.

 The following snippet is used to send an intent to all the related


BroadcastReceivers.

Intent intent = new Intent();


[Link]("[Link].CUSTOM_INTENT");
sendBroadcast(intent);

 Don’t forget to add the above action in the intent filter tag of the manifest
or programmatically.
Content Provider

 Content Provider will act as a central repository to store the


applications data in one place and make that data available for
different applications to access whenever it’s required.
 In android, we can configure Content Providers to allow other
applications securely access and modify our app data based on our
requirements.
 In android, we can use content provider whenever we want to share
our app data with other apps and it allow us to make a modifications to
our application data without effecting other applications which
depends on our app.
 In android, content provider is having different ways to store app data.
 The app data can be stored in a SQLite database or in files or even over a
network based on our requirements.
 By using content providers we can manage data such as audio, video,
images and personal contact information.

 Access Data from Content Provider

 To access a data from content provider, we need to use ContentResolver


object in our application to communicate with the provider as a client.
 The ContentResolver object will communicate with the provider object
(ContentProvider) which is implemented by instance of class.
 Generally, in android to send a request from UI to ContentResolver we have
another object called CursorLoader which is used to run the query
asynchronously in background.
 In android application the UI components such as Activity or Fragment will
call a CursorLoader to query and get a required data from ContentProvider
using ContentResolver.
 The ContentProvider object will receive a data requests from client, performs
the requested actions (create, update, delete, retrieve) and return the result.
 Following is the pictorial representation of requesting an operation from UI
using Activity or Fragment to get the data from ContentProvider object.
 Content URIs
 Content URI is an URI which is used to query a content provider to get the
required data. The Content URIs will contain the name of entire provider
(authority) and the name that points to a table (path).
 Generally the format of URI in android applications will be like as shown
below
content://authority/path
 content:// - The string content:// is always present in the URI and it is used to
represent the given URI is a content URI.
 authority - It represents the name of content provider, for example phone,
contacts, etc. and we need to use fully qualified name for third party content
providers like [Link]
 path - It represents the table’s path.
 The ContentResolver object use the URI’s authority to find the appropriate
provider and send the query objects to the correct provider. After that
ContentProvider uses the path of content URI to choose the right table to
access.
 Creating a Content Provider

 We need to create a content provider class that extends the ContentProvider


base class.
 We need to define our content provider URI to access the content.
 The ContentProvider class defines a six abstract methods (insert(), update(),
delete(), query(), getType()) which we need to implement all these methods
as a part of our subclass.
 We need to register our content provider in [Link] using
<provider> tag.
 Following are the list of methods which need to implement as a part of
ContentProvider class.
 query() - It receives a request from the client. By using arguments it will get
a data from requested table and return the data as a Cursor object.

 insert() - This method will insert a new row into our content provider and it
will return the content URI for newly inserted row.

 update() - This method will update an existing rows in our content provider
and it return the number of rows updated.

 delete() - This method will delete the rows in our content provider and it
return the number of rows deleted.

 getType() - This method will return the MIME type of data to given content
URI.

 onCreate() - This method will initialize our provider. The android system will
call this method immediately after it creates our provider.
Fragment

 A Fragment represents a portion of a user interface or an operation


that runs within an Activity.
 Android Fragment Classes
 Fragments were added to the Android API in Honeycomb(API 11).
 [Link] : The base class for all fragment definitions
 [Link] : The class for interacting with fragment
objects inside an activity
 [Link] : The class for performing an atomic set of
fragment operations
 For example, GMAIL app is designed with multiple fragments, so the design of
GMAIL app will be varied based on the size of device such as tablet or mobile
device.
 Basic Fragment Code In XML:
<fragment
android:id="@+id/fragments"
android:layout_width="match_parent"
android:layout_height="match_parent" />
 Create A Fragment Class In Android Studio:
For creating a Fragment firstly we extend the Fragment class, then override key
lifecycle methods to insert our app logic, similar to the way we would with
an Activity class.
While creating a Fragment we must use onCreateView() callback to define the layout
and in order to run a Fragment.
 Creating a Fragment in Android
 Extend Fragment class.
 Provide appearance in XML or Java.
 Override onCreateView to link the appearance.
 Use the Fragment in your activity.
 There are three methods, at a minimum, that we need to implement
for a fragment.
 onCreate(): This method is called when the fragment is created by Android System.
 onCreateView(): This method is called when the user interface for the fragment
needs to be drawn for the first time. This method returns a view.
 onPause(): This method is called when the user is leaving the fragment.
import [Link];
import [Link];
import [Link];
import [Link];

public class FirstFragment extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return [Link]([Link].fragment_first, container, false);
}
}
 Here the inflater parameter is a LayoutInflater used to inflate the layout,
container parameter is the parent ViewGroup (from the activity’s layout) in
which our Fragment layout will be inserted.

 The savedInstanceState parameter is a Bundle that provides data about the


previous instance of the Fragment.
 The inflate() method has three arguments first one is the resource layout
which we want to inflate, second is the ViewGroup to be the parent of the
inflated layout.
 Passing the container is important in order for the system to apply layout
parameters to the root view of the inflated layout, specified by the parent
view in which it’s going and the third parameter is a boolean value indicating
whether the inflated layout should be attached to the ViewGroup (the second
parameter) during inflation.
 Programmatically add the fragment to an existing ViewGroup.
 At any time while your activity is running, you can add fragments to your activity
layout. You simply need to specify a ViewGroup in which to place the fragment.
 To make fragment transactions in your activity (such as add, remove, or replace a
fragment), you must use APIs from FragmentTransaction.
 You can get an instance of FragmentTransaction from your FragmentActivity like
this:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = [Link]()
 You can then add a fragment using the add() method, specifying the fragment to
add and the view in which to insert it. For example:
ExampleFragment fragment = new ExampleFragment();
[Link]([Link].fragment_container, fragment);
[Link]();
The first argument passed to add() is the ViewGroup in which the fragment should
be placed, specified by resource ID, and the second parameter is the fragment to
add.
Once you've made your changes with FragmentTransaction, you must call commit()
for the changes to take effect.
Service

 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 background like playing the music in background or handle network
operations when the user in different app.
 In android, the life cycle of service will follow two different paths
Started or Bound.
 Started Service
 A service is Started when an application component, such as an activity calls
startService() method. Once it started, it will run indefinitely in background
even if the component that started is destroyed.
 We can stop the Started service by using stopService() method or the service
can stop itself by calling stopSelf() method. In android, the Started service
component will performs a single operation and it won’t return any result to
the caller.

 Bound Service
 A service is bound when an application component binds to it by calling
bindService().
 Bound service offers a client-server interface that allows components to
interact with the service, send requests and, get results.
 It processes across inter-process communication (IPC). The client can unbind
the service by calling the unbindService() method..
 Android Services Lifecycle Diagram
 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 must 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 startService method.
Intent intent = new Intent(this, [Link]);
startService(intent);
 Android Service Callback Methods
onStartCommand()
 The system will invoke this method when an another component such as an
activity requests the service to be started by calling startService().
 In android, onStartCommand() method must return an integer and the integer
is a value that describe how the system will continue the service in the event
that the system kills it.
 The onStartCommand() method will return a value from one of the following
constants.
 START_STICKY-It will restart the service in case if it terminated and the Intent
data which is passed to onStartCommand() method is NULL.
 START_NOT_STICKY-It will not restart the service and it is useful for the
services which will run periodically.
 START_REDELIVER_INTENT-It recreates the service, call onStartCommand()
with last intent that was delivered to the service.
onCreate()
 The system will invoke this method when the service is created initially using
onStartCommand() or onBind() methods to do one time setup procedures.
 In case, if the service is already running, then this method will not call.
onDestroy()
 The system will invoke this method when the service is no longer used and is
being destroyed. This is the final call that the service will receive and we need
to implement this method in our service to clean up any unused resources
such as threads, receivers or listeners.
onBind()
 The system will invoke this method when an another component wants to
bind with the service by calling bindService().
 During implementation of this method, we must need to provide an interface
to the clients to communicate with the service by returning an IBinder object.
 In android, we must need to implement this method, in case if we don’t need
to allow binding, then we should return NULL..
onUnbind()
 The system calls this method when all clients are disconnected from a
particular interface published by the service.
onRebind()
 Calls this method when new clients are connected to the service after it had
previously been notified that all are disconnected in onUnbind(Intent).
Multimedia Framework

 The following classes are used to play sound and video in the Android
framework:
MediaPlayer
 This class is the primary API for playing sound and video.
AudioManager
 This class manages audio sources and audio output on a device.
 Manifest declarations:
 Internet Permission –
If you are using MediaPlayer to stream network-based content, your
application must request network access.
<uses-permission android:name="[Link]"
/>
 Wake Lock Permission –
If your player application needs to keep the screen from dimming or the
processor from sleeping, or uses the
[Link]() or [Link]()
methods, you must request this permission.
<uses-permission
android:name="[Link].WAKE_LOCK" />
Play Audio

 It supports several different media sources such as:


 Local resources

MediaPlayer mediaPlayer = [Link](context, [Link].sound_file_1);


[Link](); // no need to call prepare(); create() does that for you
 Internal URIs, such as one you might obtain from a Content Resolver
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
[Link](AudioManager.STREAM_MUSIC);
[Link](getApplicationContext(), myUri);
[Link]();
[Link]();

 External URLs (streaming)


String url = "[Link] // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
[Link](AudioManager.STREAM_MUSIC);
[Link](url);
[Link](); // might take long! (for buffering, etc)
[Link]();
Play Video

 In android, by using VideoView component and MediaController class we can easily


implement the video player in android applications to play the videos with multiple
playback options, such as play, pause, forward, backward, etc.

 Generally, the MediaController class in android will provide a playback options for
video player, such as play, pause, backward, forward, etc.

 The VideoView class in android will provide a functionalities to fetch and play the
videos using video player with minimal setup in android applications.
 Following is the code snippet, to use VideoView and MediaController
classes to implement video player in android application to play videos
based on our requirements.

VideoView videoView =(VideoView)findViewById([Link]);


MediaController mediaController= new MediaController(this);
[Link](videoView);
Uri uri = [Link]("[Link]://" + getPackageName() + "/" +
[Link].video1);
[Link](mediaController);
[Link](uri);
[Link]();
[Link]();
 VideoView class provides a different type of methods to control video files
based on requirements.
TextToSpeech

 In android, you can convert your text into speech by the help of TextToSpeech class.
 Constructor of TextToSpeech class
 TextToSpeech(Context context, [Link])
 You need to implement [Link] interface, for performing event
handling on TextToSpeech engine.
 There is only one method in this interface.
Methods of TextToSpeech class
Sensors

 A sensor is a device that detects and responds to some type of input from the physical
environment. The specific input could be light, heat, motion, moisture, pressure, or any one
of a great number of other environmental phenomena.
 The Android platform supports three broad categories of sensors:
 Motion sensors These sensors measure acceleration forces and rotational forces along
three axes. This category includes accelerometers, gravity
sensors, gyroscopes and rotational vector sensors.
 Environmental sensors These sensors measure various environmental parameters, such
as ambient air temperature and pressure, illumination, and humidity. This category
includes barometers, photometers and thermometers.
 Position sensors These sensors measure the physical position of a device. This category
includes orientation sensors and magnetometers.
 Android Sensor API
 SensorManager
Is the Android system service that gives an app access to hardware sensors.
 Sensor
Is the Android representation of a hardware sensor on a device.
 SensorEventListener
Is an interface that provides the callbacks to alert an app to sensor-related
events.
 SensorEvent
Is the data structure that contains the information that is passed to an app when
a hardware sensor has information to report.
 SensorManager
 SensorManager lets you access the device's sensors. Get an instance of this class by
calling getSystemService() with the argument SENSOR_SERVICE.
private SensorManager mSensorManager;
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
 Identifying Sensors
 SensorManager provides two methods to access Sensor objects:
 getSensorList(): returns all the sensors.
 getDefaultSensor(): returns the default sensor for the specified type.
 Example:
List<Sensor> deviceSensors =
[Link](Sensor.TYPE_ALL);
Example:
if ([Link](Sensor.TYPE_PRESSURE) != null) {
// Success! There's a pressure sensor.
}
else {
// Failure! No pressure sensor.
}
 SensorEventListener
 SensorEventListener is used for receiving notifications from the SensorManager when sensor
values have changed. In this class there are two public methods:

 onAccuracyChanged(Sensor sensor, int accuracy): Called when the accuracy of a sensor has
changed.
 onSensorChanged(SensorEvent event): Called when sensor values have changed.

 SensorEvent
 SensorEvent is the data structure that contains the information that is passed to an app when
a hardware sensor has information to report. The data members of the SensorEvent are:
 accuracy: The accuracy of the event.
 Can have the following values:
 SensorManager.SENSOR_STATUS_ACCURACY_HIGH
 SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM
 SensorManager.SENSOR_STATUS_ACCURACY_LOW
 SensorManager.SENSOR_STATUS_UNRELIABLE
 sensor: An instance of the Sensor class that generated the SensorEvent.
 timestamp: The time in milliseconds when the SensorEvent occurred.
 values: An array of values that represent sensor data.
 Sensor Rates
 When you register a listener, you specify the delay or measurement rate for the
listener. The predefined rates are:
 SENSOR_DELAY_FASTEST: get sensor data as fast as possible.
 SENSOR_DELAY_GAME: rate suitable for games.
 SENSOR_DELAY_UI: rate suitable for the user interface functions.
 SENSOR_DELAY_NORMAL: rate suitable for screen orientation changes. (The
default value).
 The sensors referenced through the Sensor class may be of two types:
 Raw sensors (hardware-based) give raw data from a sensor, and one raw sensor
corresponds to one actual physical component inside the Android device.
 Sensor.TYPE_LIGHT
 Sensor.TYPE_PROXIMITY
 Sensor.TYPE_PRESSURE
 Sensor.TYPE_TEMPERATURE (deprecated)
 Sensor.TYPE_ACCELEROMETER
 Sensor.TYPE_GYROSCOPE
 Sensor.TYPE_MAGNETIC_FIELD
 Sensor.TYPE_RELATIVE_HUMIDITY
 Sensor.TYPE_AMBIENT_TEMPERATURE
 Composite sensors (software-based) provide an abstraction layer between application code
and low-level device components by either combining the raw data of multiple raw sensors,
or by modifying the raw sensor data to make it easier to consume.
 Sensor.TYPE_ROTATION_VECTOR
 Sensor.TYPE_LINEAR_ACCELERATION
 Sensor.TYPE_GRAVITY
 Sensor.TYPE_ORIENTATION (deprecated)
 The sensors referenced through the Sensor class may be of two types:
 Raw sensors (hardware-based) give raw data from a sensor, and one raw sensor
corresponds to one actual physical component inside the Android device.
 Sensor.TYPE_LIGHT
 Sensor.TYPE_PROXIMITY
 Sensor.TYPE_PRESSURE
 Sensor.TYPE_TEMPERATURE (deprecated)
 Sensor.TYPE_ACCELEROMETER
 Sensor.TYPE_GYROSCOPE
 Sensor.TYPE_MAGNETIC_FIELD
 Sensor.TYPE_RELATIVE_HUMIDITY
 Sensor.TYPE_AMBIENT_TEMPERATURE
 Composite sensors (software-based) provide an abstraction layer between application code
and low-level device components by either combining the raw data of multiple raw sensors,
or by modifying the raw sensor data to make it easier to consume.
 Sensor.TYPE_ROTATION_VECTOR
 Sensor.TYPE_LINEAR_ACCELERATION
 Sensor.TYPE_GRAVITY
 Sensor.TYPE_ORIENTATION (deprecated)

You might also like