Mobile Application Development Bikila
Mobile Application Development Bikila
Mobile Application Development Bikila
Institute of Technology
Faculty of Computing and Software Engineering
May, 2023
TABLE OF CONTENTS
Learning Objectives ........................................................................................................................ 1
Introduction ..................................................................................................................................... 2
The Android Platform ................................................................................................................. 2
Android UI Layouts .................................................................................................................... 3
Layout params ......................................................................................................................... 4
Android Layout Types ............................................................................................................ 5
Layout Attributes .................................................................................................................... 5
View Identification ................................................................................................................. 8
Android Resources ...................................................................................................................... 8
Organize resource in Android Studio ..................................................................................... 8
Alternative Resources ........................................................................................................... 10
Accessing Resources ............................................................................................................. 11
Accessing Resources in Code ............................................................................................... 11
Accessing Resources in XML............................................................................................... 12
Android Intents ......................................................................................................................... 13
Pending-Intent vs Regular Intent .......................................................................................... 14
Basic Components of an Android application .............................................................................. 14
Activities ................................................................................................................................... 14
Creating a new activity ......................................................................................................... 16
The role of setContentView() method .................................................................................. 16
Role of saveInstanceState() method...................................................................................... 17
Launching an Activity........................................................................................................... 18
Activity Launch Modes......................................................................................................... 20
Passing data between Activities ............................................................................................ 20
Handling Back Button Press ................................................................................................. 22
Handling configuration changes of Activities ...................................................................... 23
The Action bar ...................................................................................................................... 25
Fragments .................................................................................................................................. 26
Fragment Life Cycle ............................................................................................................. 27
How to use Fragments? ......................................................................................................... 28
Types of Fragments............................................................................................................... 28
Difference between fragments and activities ........................................................................ 28
Review questions and Answers ............................................................................................ 29
Services ..................................................................................................................................... 30
Types of services................................................................................................................... 30
Creating a service .................................................................................................................. 31
Stopping services .................................................................................................................. 32
Broadcast Receiver ................................................................................................................... 33
Registering broadcast recievers ............................................................................................ 34
Creating custom broadcast reciever ...................................................................................... 34
Sending broadcast messages from an app ............................................................................. 36
Receiving a broadcast message ............................................................................................. 36
Exchanging data between broadcast recievers and other components ................................. 37
Handling different types of broadcasts ................................................................................. 39
Content Providers...................................................................................................................... 40
Review questions and answers.............................................................................................. 41
Lifecycle Methods of application components ............................................................................. 42
Android Activities life cycle ..................................................................................................... 42
Android Services life cycle ....................................................................................................... 43
Android Broadcast Receivers life cycle .................................................................................... 45
Android Content Providers life cycle ....................................................................................... 45
Basics of event handling in Android ............................................................................................. 46
Event listeners registration ........................................................................................................ 46
Basics of graphics and multimedia support in Android ................................................................ 49
Basics of data storage in android .................................................................................................. 51
Shared preferences .................................................................................................................... 51
Internal storage.......................................................................................................................... 52
External storage ........................................................................................................................ 52
SQLite database ........................................................................................................................ 53
Network connection/cloud storage ........................................................................................... 54
Android studio environment ......................................................................................................... 56
The AndroidManifest.xml..................................................................................................... 58
Reference Books suggested for reading ........................................................................................ 58
Review exercises ........................................................................................................................... 58
LEARNING OBJECTIVES
1) Describe the basic components of an Android application.
2) Define the lifecycle methods of Android application components.
3) Describe the basics of event handling in Android.
4) Describe the basics of graphics and multimedia support in Android.
5) Demonstrate basic skills of using an integrated development environment (Android
Studio) and Android Software Development Kit (SDK) for implementing Android
applications.
6) Demonstrate through a simple application the understanding of the basic concepts of
Android
T HE A NDROID P LATFORM
Android is an open source and Linux-based Operating System for mobile devices such as
smartphones and tablet computers. Android was developed by the Open Handset Alliance (OHA),
led by Google, and other companies. Android includes a Linux kernel-based OS, a rich UI, end-
user applications, code libraries, application frameworks, multimedia support, and much more.
And, yes, even telephone functionality is included! Whereas components of the underlying OS are
written in C or C++, user applications are built for Android in Java.
A Linux kernel provides a foundational hardware abstraction layer, as well as core services such
as process, memory, and file-system management.
The kernel is where hardware-specific drivers are implemented—capabilities such as Wi-
Fi and Bluetooth are here.
A NDROID UI L AYOUTS
The basic building block for user interface is a View object which is created from the View class
and occupies a rectangular area on the screen and is responsible for drawing and event handling.
View is the base class for widgets, which are used to create interactive UI components like
buttons, text fields, etc.
The ViewGroup is a subclass of View and provides invisible container that hold other Views or
other ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical
layout defines the visual structure for an Android user interface and can be created either at run
time using View/ViewGroup objects or you can declare your layout using simple XML file
main_layout.xml which is located in the res/layout folder of your project.
This tutorial is more about creating your GUI based on layouts defined in XML file. A layout
may contain any type of widgets such as buttons, labels, textboxes, and so on. Following is a
simple example of XML file having LinearLayout −
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button" />
</LinearLayout>
Once your layout has created, you can load the layout resource from your application code, in
your Activity.onCreate() callback implementation as shown below −
There are number of Layouts provided by Android which you will use in almost all the Android
applications to provide different view, look and feel.
LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally.
2 Relative Layout
The FrameLayout is a placeholder on screen that you can use to display a single view.
6 List View
Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are few
common attributes among all the layouts and there are other attributes which are specific to that
layout. Following are common attributes and will be applied to all the layouts:
This specifies how much of the extra space in the layout should be allocated to the
View.
10 android:layout_x
You can specify width and height with exact measurements but more often, you will use one of
these constants to set the width or height −
Gravity attribute plays important role in positioning the view object and it can take one or more
(separated by '|') of the following constant values.
View Identification
A view object may have a unique ID assigned to it which will identify the View uniquely within
the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/my_button"
The at-symbol (@) at the beginning of the string indicates that the XML parser should
parse and expand the rest of the ID string and identify it as an ID resource.
The plus-symbol (+) means that this is a new resource name that must be created and
added to our resources. To create an instance of the view object and capture it from the
layout, use the following −
There are many more items which you use to build a good Android application. Apart from
coding for the application, you take care of various other resources like static content that your
code uses, such as bitmaps, colors, layout definitions, user interface strings, animation
instructions, and more. These resources are always maintained separately in various sub-
directories under res/ directory of the project.
This tutorial will explain you how you can organize your application resources, specify
alternative resources and access them in your applications.
XML files that define property animations. They are saved in res/anim/ folder and
accessed from the R.anim class.
2 color/
XML files that define a state list of colors. They are saved in res/color/ and accessed
from the R.color class.
3 drawable/
Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps, state
lists, shapes, animation drawable. They are saved in res/drawable/ and accessed from
the R.drawable class.
4 layout/
XML files that define a user interface layout. They are saved in res/layout/ and
accessed from the R.layout class.
5 menu/
XML files that define application menus, such as an Options Menu, Context Menu,
or Sub Menu. They are saved in res/menu/ and accessed from the R.menu class.
6 raw/
XML files that contain simple values, such as strings, integers, and colors. For
example, here are some filename conventions for resources you can create in this
directory −
arrays.xml for resource arrays, and accessed from the R.array class.
integers.xml for resource integers, and accessed from the R.integer class.
bools.xml for resource boolean, and accessed from the R.bool class.
colors.xml for color values, and accessed from the R.color class.
dimens.xml for dimension values, and accessed from the R.dimen class.
strings.xml for string values, and accessed from the R.string class.
styles.xml for styles, and accessed from the R.style class.
8 xml/
Arbitrary XML files that can be read at runtime by calling Resources.getXML(). You
can save various configuration files here which will be used at run time.
Your application should provide alternative resources to support specific device configurations.
For example, you should include alternative drawable resources ( i.e.images ) for different screen
resolution and alternative string resources for different languages. At runtime, Android detects
the current device configuration and loads the appropriate resources for your application.
To specify configuration-specific alternatives for a set of resources, follow the following steps −
Below is an example which specifies images for a default screen and alternative images for high
resolution screen.
MyProject/
app/
manifest/
AndroidManifest.xml
java/
MyActivity.java
res/
drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
layout/
activity_main.xml
info.xml
values/
strings.xml
Below is another example which specifies layout for a default language and alternative layout for
Arabic language.
MyProject/
app/
manifest/
AndroidManifest.xml
java/
MyActivity.java
Accessing Resources
During your application development you will need to access defined resources either in your
code, or in your layout XML files. Following section explains how to access your resources in
both the scenarios −
When your Android application is compiled, a R class gets generated, which contains resource
IDs for all the resources available in your res/ directory. You can use R class to access that
resource using sub-directory and resource name or directly resource ID.
Example
To access res/drawable/myimage.png and set an ImageView you will use following code −
Here first line of the code make use of R.id.myimageview to get ImageView defined with id
myimageview in a Layout file. Second line of code makes use of R.drawable.myimage to get an
image with name myimage available in drawable sub-directory under /res.
Example
Now you can set the text on a TextView object with ID msg using a resource ID as follows −
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
This application code will load this layout for an Activity, in the onCreate() method as follows −
Consider the following resource XML res/values/strings.xml file that includes a color resource
and a string resource −
Now you can use these resources in the following layout file to set the text color and text string
as follows −
A NDROID I NTENTS
Intents and Intent-Filters bring the “click it” paradigm to the core of mobile application use (and
development) for the Android platform:
• An Intent is a declaration of need. It’s made up of a number of pieces of information
that describe the desired action or service. Usually intent is made up of the requested
action and, generically, the data that accompanies the requested action.
• An Intent-Filter is a declaration of capability and interest in offering assistance to
those in need. It can be generic or specific with respect to which Intents it offers to
service.
The action attribute of an Intent is typically a verb: for example, VIEW, PICK, or EDIT. A
number of built-in Intent actions are defined as members of the Intent class. For example, to
view a piece of information, an application employs the following Intent action:
android.content.Intent.ACTION_VIEW
The data component of an Intent is expressed in the form of a URI and can be virtually any
piece of information, such as a contact record, a website location, or a reference to a media clip.
The Intent-Filter defines the relationship between the Intent and the application.
o Intent-Filters can be specific to the data portion of the Intent, the action portion, or both.
o Intent-Filters also contain a field known as a category. The category helps classify the
action.
For example, the category named CATEGORY_LAUNCHER instructs Android that the Activity
containing this Intent-Filter should be visible in the main application launcher or home screen.
Intent-Filters are often defined in an application’s AndroidManifest.xml file with the <intent-
filter> tag.
There are three types of Intents, Implicit and Explicit intents, and Pending-Intents.
Implicit intents rely on intent filters and the Android environment to dispatch the
Intent to the appropriate recipient
Explicit intent specifies the exact class that will handle the Intent.
In the world of mobile application development, an Android application is the most popular choice
of developers. It offers a wide range of components that work together to deliver an excellent user
experience.
a) Activities,
b) Services,
c) Broadcast Receivers, and
d) Content Providers.
A CTIVITIES
Activities are responsible for managing the user interface (UI) and handling user interactions.
The Activity employs one or more Views to present the actual UI elements to the user.
The Activity class is extended by user classes.
One of the primary tasks an Activity performs is displaying UI elements, which are
implemented as Views and are typically defined in XML layout files.
Example of an Activity with one EditText and Button:
The UI for the above java code is created in the following xml file with a Linear layout:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Please enter your home address."/>
<EditText
android:id="@+id/address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoText="true"/>
<Button
android:id="@+id/launchmap"
android:layout_width="wrap_content"
</LinearLayout>
Figure – high level diagram of Activity , and its relation with views , resources and
manifest
The `setContentView()` method takes a layout resource ID as its parameter, which is the ID of
the XML layout file that defines the UI components of the Activity. The method inflates the
layout and adds the UI components to the Activity's view hierarchy.
```
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
```
In this example, the `setContentView()` method is called in the `onCreate()` method of the
Activity, passing the `R.layout.activity_main` layout resource ID as its parameter. The
`activity_main.xml` layout file defines the UI components of the Activity and is located in the
`res/layout` directory of the app's resources.
It's important to note that the `setContentView()` method should only be called once in the
`onCreate()` method of an Activity. If you call it multiple times, the UI components from the
previous call will be replaced with the components from the latest call.
In summary, the `setContentView()` method is used to inflate a layout file and set the UI
components of an Activity. It's an important method that's called in the `onCreate()` method of
an Activity to set up the initial UI.
When an Activity is destroyed due to a configuration change, the system calls the
`onSaveInstanceState()` method and passes in a `Bundle` object as a parameter. The `Bundle`
object is used to store key-value pairs that represent the state of the Activity's UI and data. The
key-value pairs are typically used to store things like the text entered into an EditText field or the
position of a SeekBar.
```
public class MyActivity extends AppCompatActivity {
private int mCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
mCount = savedInstanceState.getInt("count");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("count", mCount);
}
In this example, the Activity has a `TextView` that displays a count value, and a button that
increments the count when clicked. The `onSaveInstanceState()` method is overridden to save
the current count value in the `Bundle` object. The `onCreate()` method retrieves the count value
from the `Bundle` object and sets it as the initial value of the count variable.
By saving the state of the Activity's UI and data in the `onSaveInstanceState()` method, the state
can be restored when the Activity is recreated, preserving the user's progress and preventing data
loss.
Launching an Activity
In Android, you can launch an Activity from another application by using an `Intent`. The
`Intent` is used to specify the package name and class name of the target Activity, as well as any
additional data or flags that should be passed to the Activity.
In this example, the `setClassName()` method is used to specify the package name and class
name of the target Activity. The `startActivity()` method is then called to launch the Activity.
You can also include additional data or flags in the `Intent` to pass to the target Activity. For
example, to pass a String value to the target Activity, you can use the `putExtra()` method:
```
Intent intent = new Intent();
intent.setClassName("com.example.myapp", "com.example.myapp.MainActivity");
intent.putExtra("message", "Hello from another app!");
startActivity(intent);
```
In this example, the `putExtra()` method is used to add a String value with the key "message" to
the `Intent`. This value can then be retrieved by the target Activity using the `getStringExtra()`
method.
It's important to note that launching an Activity from another application requires that the target
Activity be declared as "exported" in the manifest file of the target application. If the Activity is
not exported, the system will not allow it to be launched from another application.
In Android, both startActivity() and startActivityForResult() are used to launch a new activity
from an existing activity. However, they differ in how they handle the result of the launched
activity.
1. startActivity(): This method is used to launch a new activity from an existing activity, without
expecting any result from the launched activity.
Once the new activity is launched, the existing activity goes into the background and the
new activity becomes the foreground activity.
1. Standard: This is the default launch mode for an Activity. Each time a new instance of the
Activity is launched, a new instance is created on top of the activity stack, regardless of whether
an existing instance of the Activity already exists.
2. SingleTop: In this launch mode, if an instance of the Activity already exists at the top of the
activity stack, the system reuses that instance by calling its `onNewIntent()` method instead of
creating a new instance. If the Activity is not at the top of the stack, a new instance is created.
3. SingleTask: In this launch mode, the system creates a new task and adds the Activity to the
task as the root Activity. If an instance of the Activity already exists in the task, the system
removes all Activities on top of it and reuses it by calling its `onNewIntent()` method. If no
instance of the Activity exists in the task, a new instance is created.
4. SingleInstance: This is the most restrictive launch mode. In this mode, the system creates a
new task and adds the Activity to the task as the root Activity. However, the system does not
allow any other Activities to be launched into the same task. If an Activity with the same launch
mode already exists in a separate task, the system routes the Intent to the existing task with that
Activity, creating a new instance of the task if necessary.
To set the launch mode of an Activity, you can use the `android:launchMode` attribute in the
Activity's manifest file. For example, to set the launch mode to SingleTop, you can add the
following line to the Activity's manifest entry:
```
android:launchMode="singleTop"
```
2. Bundle: A Bundle is a container for a set of values. It can be used to pass data between
activities using the `putExtra()` method, just like an Intent. The difference is that a Bundle can
contain multiple values and can be used to pass complex data types.
3. Static variable: A static variable can be used to store data that needs to be accessed by multiple
activities. The variable can be declared in a separate class and accessed by both activities.
In a separate class:
```
```
public class MyActivity extends AppCompatActivity {
@Override
public void onBackPressed() {
// Add custom behavior here
super.onBackPressed();
}
}
```
In this example, the `onBackPressed()` method is overridden to provide custom behavior when
the back button is pressed. You can add your own code in this method to handle the back button
press, such as displaying a confirmation dialog or navigating back to a specific screen.
It's important to call the `super.onBackPressed()` method at the end of the method to ensure that
the default behavior of the back button is still executed. This will ensure that the user can still
navigate back to the previous screen or Activity if necessary.
You can also override the `onKeyDown()` method to handle the back button press. The
`onKeyDown()` method is called when any key is pressed, including the back button. Here's an
example of how to override the `onKeyDown()` method:
In this example, the `onKeyDown()` method is overridden to handle the back button press
specifically. The method checks if the key code is `KeyEvent.KEYCODE_BACK` to determine
if the back button was pressed. If the back button was pressed, you can add your own code to
handle the press and return `true` to indicate that the back button press was handled.
To handle configuration changes in an Activity and avoid these problems, you can override the
`onSaveInstanceState()` method and the `onRestoreInstanceState()` method. These methods
allow you to save and restore the state of the Activity's UI and data when a configuration change
occurs.
```
public class MyActivity extends AppCompatActivity {
private int mCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
mCount = savedInstanceState.getInt("count", 0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("count", mCount);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCount = savedInstanceState.getInt("count", 0);
}
In this example, the Activity has a `TextView` that displays a count value, and a button that
increments the count when clicked. The `onSaveInstanceState()` method is overridden to save
the current count value in the `Bundle` object. The `onRestoreInstanceState()` method is
overridden to restore the count value from the `Bundle` object.
By saving the state of the Activity's UI and data in the `onSaveInstanceState()` method and
restoring it in the `onRestoreInstanceState()` method, the state can be preserved when a
configuration change occurs, preventing data loss and UI flickering.
It's important to note that not all configuration changes trigger a restart of the Activity. For
example, changes to the device's screen size or density do not trigger a restart. To handle these
types of configuration changes, you can use the `android:configChanges` attribute in the
Activity's manifest entry to specify which configuration changes you want to handle manually.
For example, to handle screen orientation changes manually, you can add the following line to
the Activity's manifest entry:
```
android:configChanges="orientation"
```
The ActionBar was introduced in Android 3.0 (API level 11) as a replacement for the previous
options menu and title bar. It provides a more modern and flexible way to display app-specific
actions and navigation options.
The ActionBar can be customized to fit the design and branding of an app. You can add custom
icons, change the background color, and add custom views to the ActionBar.
```
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
```
The `onOptionsItemSelected()` method is overridden to handle the selection of menu items in the
ActionBar. In this example, the method checks for the selection of the Up button and calls the
`onBackPressed()` method to navigate back to the previous Activity.
A Fragment is a piece of an activity which enable more modular activity design. It will not be
wrong if we say, a fragment is a kind of sub-activity.
A fragment has its own layout and its own behaviour with its own life cycle callbacks.
You can add or remove fragments in an activity while the activity is running.
You can combine multiple fragments in a single activity to build a multi-pane UI.
A fragment can be used in multiple activities.
Fragment life cycle is closely related to the life cycle of its host activity which means
when the activity is paused, all the fragments available in the activity will also be
stopped.
A fragment can implement a behaviour that has no user interface component.
Fragments were added to the Android API in Honeycomb version of Android which API
version 11.
You create fragments by extending Fragment class and You can insert a fragment into your
activity layout by declaring the fragment in the activity's layout file, as a <fragment> element.
Prior to fragment introduction, we had a limitation because we can show only a single activity on
the screen at one given point in time. So we were not able to divide device screen and control
different parts separately. But with the introduction of fragment we got more flexibility and
removed the limitation of having a single activity on the screen at a time. Now we can have a
single activity but each activity can comprise of multiple fragments which will have their own
layout, events and complete life cycle.
Following is a typical example of how two UI modules defined by fragments can be combined
into one activity for a tablet design, but separated for a handset design.
Android fragments have their own life cycle very similar to an android activity. This section
briefs different stages of its life cycle.
Here is the list of methods which you can to override in your fragment class −
First of all decide how many fragments you want to use in an activity. For example let's
we want to use two fragments to handle landscape and portrait modes of the device.
Next based on number of fragments, create classes which will extend the Fragment class.
The Fragment class has above mentioned callback functions. You can override any of the
functions based on your requirements.
Corresponding to each fragment, you will need to create layout files in XML file. These
files will have layout for the defined fragments.
Finally modify activity file to define the actual logic of replacing fragments based on
your requirement.
Types of Fragments
Single frame fragments − Single frame fragments are using for hand hold devices like
mobiles, here we can show only one fragment as a view.
List fragments − fragments having special list view is called as list fragment
Fragments transaction − Using with fragment transaction. we can move one fragment to
another fragment.
In other words, an Activity typically represents a complete user interface that can contain
multiple fragments, whereas a Fragment represents a portion of that user interface. While an
Activity is standalone and can exist on its own, a Fragment must always be hosted by an
Activity.
Another difference between Activities and Fragments is their lifecycle. Activities have their own
lifecycle, which is managed by the operating system, and they can be destroyed and recreated as
needed. Fragments also have their own lifecycle, which is tied to the lifecycle of the hosting
Activity, and they can be added, removed, and replaced dynamically at runtime.
Overall, Activities and Fragments serve different purposes in the Android framework, with
Activities defining the overall structure and behavior of the application and Fragments providing
a modular and flexible way to design user interfaces.
S ERVICES
In many applications, certain tasks are being performed without using any UI i.e., the task is
being performed in the background. For example, the Music app of our mobile device or any other.
Music application runs in the background and while using the Music app, you can use any other
application normally. So, this feature is implemented using the Service or IntentService.
Types of services
There are many types of services in android, the following are some of them:
a) A started service
A service that is started by calling the startService() method from another component. Once
started, the service can continue to run in the background even if the component that started it is
destroyed.
b) A Bound service
Works by binding a service to an application using bindService() is stopped by calling the
unbindService() method.
c) A Background service
A background service performs an operation that isn't directly noticed by the user. For
example, if an app used a service to compact its storage, that would usually be a background
service.
d) A Foreground service
A foreground service performs some operation that is noticeable to the user. For example, an
audio app would use a foreground service to play an audio track. Foreground services must
display a Notification.
Creating a service
To create an Android Service, you can follow the following steps:
```
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Code to execute when Service is started
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// Not used in this Service
return null;
}
@Override
public void onDestroy() {
// Code to execute when Service is destroyed
super.onDestroy();
}
}
```
Note: Remember to declare your Service in the AndroidManifest.xml file, otherwise it won't
work.
Stopping services
To stop an Android service, you can call the `stopService()` method or the `stopSelf()` method
from within the service itself.
Here's how you can use the `stopService()` method to stop a service:
This will stop the service if it's currently running. If the service is not running, calling
`stopService()` has no effect.
Note that if you want the service to stop itself automatically when it has completed its work, you
can call `stopSelf()` from within the `onDestroy()` method of the service. This method is called
when the service is about to be destroyed and is a good place to do any cleanup work that needs
to be done.
B ROADCAST R ECEIVER
The following are some of the important system wide generated intents:
public MyReceiver() { }
@Override
Toast.makeText(context,"Action:"+intent.getAction(),
Toast.LENGTH_SHORT).show();
<intent-filter>
</intent-filter>
</receiver>
2) By defining it programmatically
intentFilter.addAction(getPackageName()+"android.net.conn.CONNECTIVITY_CHANGE"
);
registerReceiver(myReceiver, filter);
Like Services, BroadcastReceivers don’t have a UI. Even more important, the code running in
the onReceive method of a BroadcastReceiver should make no assumptions about persistence
or long-running operations.
2. Override the `onReceive()` method. This method is called when the `BroadcastReceiver`
receives a broadcast. You can use the `Context` and `Intent` parameters to access information
about the broadcast and perform any necessary actions in response.
```
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("com.example.myapp.MY_ACTION")) {
// Do something in response to the broadcast
}
}
```
3. Register the `BroadcastReceiver` in your app. You can do this either in the manifest file or in
code using the `registerReceiver()` method.
To register the `BroadcastReceiver` in the manifest file, add a `<receiver>` element to your
manifest file with the appropriate attributes:
```
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.example.myapp.MY_ACTION" />
</intent-filter>
</receiver>
```
Once you have defined your custom `BroadcastReceiver`, you can send broadcasts to it from
other components in your app using the `sendBroadcast()` method. When a broadcast is sent,
your `BroadcastReceiver`'s `onReceive()` method will be called, allowing you to perform any
necessary actions in response.
1. Create an `Intent` object. You should specify the action that you want to broadcast using the
`setAction()` method. You can also include any other data that you want to send with the
broadcast using the various `putExtra()` methods.
```
Intent intent = new Intent();
intent.setAction("com.example.myapp.MY_ACTION");
intent.putExtra("message", "Hello, world!");
```
2. Call the `sendBroadcast()` method on your `Context` object, passing in the `Intent` as a
parameter.
```
context.sendBroadcast(intent);
```
When you call `sendBroadcast()`, the Android system will broadcast the `Intent` to all registered
`BroadcastReceiver` components that have a matching intent filter. Your `BroadcastReceiver`'s
`onReceive()` method will be called if it matches the intent filter.
Note that you can also use other methods to send broadcasts, such as `sendOrderedBroadcast()`
or `sendStickyBroadcast()`, depending on your requirements. However, these methods are less
commonly used and have some limitations, so `sendBroadcast()` is usually the best choice for
most use cases.
3. Register the `BroadcastReceiver` in your app. You can do this either in the manifest file or in
code using the `registerReceiver()` method.
To register the `BroadcastReceiver` in the manifest file, add a `<receiver>` element to your
manifest file with the appropriate attributes:
```
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.example.myapp.MY_ACTION" />
</intent-filter>
</receiver>
```
In this example, the `MyReceiver` class is registered to receive broadcasts with the action
`com.example.myapp.MY_ACTION`.
Once you have registered your `BroadcastReceiver`, it will receive broadcasts with the specified
action. When a broadcast is received, your `BroadcastReceiver`'s `onReceive()` method will be
called, allowing you to perform any necessary actions in response.
Note that you can also use intent filters to specify additional criteria for the broadcasts that your
`BroadcastReceiver` should receive, such as data URI or MIME type. This allows you to receive
only the broadcasts that are relevant to your app.
1. Using Intent extras: You can include data in the `Intent` that is broadcasted from your
`BroadcastReceiver` using the `putExtra()` method. Other components that receive the broadcast
can then retrieve the data from the `Intent` using the corresponding `getExtra()` method.
For example, in your `BroadcastReceiver` you can include data like this:
2. Using the Application class: If you need to share data between different components of your
app, you can store the data in the `Application` class. The `Application` class is a singleton that
is created when your app starts, and can be accessed from any component in your app.
For example, in your `Application` class you can define a public method to set and get data:
```
public class MyApp extends Application {
private String message;
3. Using a local broadcast: If you need to pass data between components within your app only,
you can use a local broadcast instead of a global broadcast. Local broadcasts are delivered only
to components within your own app, and are not visible to other apps.
Here are the steps to handle different types of broadcasts in your `BroadcastReceiver`:
1. Define an action string for each type of broadcast that your `BroadcastReceiver` should
handle. You can define these as constants in your code:
```
public static final String ACTION_ONE = "com.example.myapp.ACTION_ONE";
public static final String ACTION_TWO = "com.example.myapp.ACTION_TWO";
```
2. Create an `IntentFilter` object and add the actions that your `BroadcastReceiver` should handle
using the `addAction()` method:
```
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_ONE);
filter.addAction(ACTION_TWO);
```
3. Override the `onReceive()` method in your `BroadcastReceiver` and check the action of the
received `Intent` using the `getAction()` method. You can then perform any necessary actions
based on the action of the received `Intent`:
```
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ACTION_ONE)) {
Note that you can also use other criteria in your `IntentFilter`, such as data URI or MIME type,
to further specify the type of broadcast that your `BroadcastReceiver` should handle. This allows
you to receive only the broadcasts that are relevant to your app.
C ONTENT P ROVIDERS
Content Providers manage access to data stored within the application. Content providers are the
standard interface that connects data in one process with code running in another process.
Implementing a content provider has many advantages. Most importantly you can configure a
content provider to allow other applications to securely access and modify your app data.
Here are some common questions that are usually asked about Android Content Providers:
A Content Provider in Android is a component that manages access to a shared set of app data. It
provides a standard interface for other apps to query, insert, update, and delete data in your app's
database. Content Providers are used to securely share data between different apps in the Android
system.
- Providing a standardized interface for other apps to access your app's data.
- Allowing your app to be integrated with other apps in the Android system, such as the Contacts
app or the Gallery app.
To create a Content Provider in Android, you need to define a subclass of the `ContentProvider`
class and implement the necessary methods, such as `query()`, `insert()`, `update()`, and `delete()`.
You also need to define a `URI` scheme that identifies the data that your Content Provider
manages.
To access data from a Content Provider in your app, you need to use a `ContentResolver` object.
You can use the `ContentResolver` to query, insert, update, and delete data in the Content
Provider's database. You also need to define the `URI` scheme that identifies the data you want to
access.
To secure your Content Provider, you can define permissions that restrict access to specific data
or operations. You can also use a `ProviderInfo` object to specify the permissions that other apps
need to access your Content Provider.
To test your Content Provider, you can use unit tests to verify that the `query()`, `insert()`,
`update()`, and `delete()` methods work correctly. You can also use integration tests to verify that
your Content Provider works correctly with other apps in the Android system.
To optimize the performance of your Content Provider, you can use techniques such as using
indexes and caching to improve query performance. You can also use a `CursorLoader` to
asynchronously load data from the Content Provider in the background, which can help to improve
the responsiveness of your app.
Android activities are the building blocks of any Android application. They are responsible for
managing the UI and user interactions. The lifecycle methods of activities govern the behavior of
the activities during runtime.
The lifecycle of an activity begins when it is first created and ends when it is destroyed.
During this lifecycle, the activity goes through various states, and the lifecycle methods are
called accordingly.
1. onCreate(): This is the first method that is called when the activity is created. This
method is responsible for initializing the activity and setting up the UI.
2. onStart(): This method is called when the activity becomes visible to the user. This is the
point where the activity is ready to interact with the user.
3. onResume(): This method is called when the activity is in the foreground and has focus.
At this point, the activity is fully interactive, and the user can interact with the UI.
4. onPause(): This method is called when the activity loses focus but is still visible to the
user. This can happen when another activity is launched on top of the current activity.
5. onStop(): This method is called when the activity is no longer visible to the user. This
can happen when the user navigates to another activity or when the activity is destroyed.
6. onRestart(): This method is called when the activity is stopped and then started again.
This can happen when the user navigates back to the activity.
7. onDestroy(): This is the final method that is called when the activity is destroyed. This
method is responsible for releasing any resources that were allocated by the activity.
Android services are components that run in the background and perform tasks without requiring
user interaction. Services can be used to perform tasks such as playing music, downloading files,
or updating data in the background.
1. onCreate(): This is the first method that is called when the service is created. This method
is responsible for initializing the service and setting up any resources that are needed.
When a service is started, it runs independently of the activity that started it.
When a service is bound, it runs in the same process as the activity that bound it, and the activity
can communicate with the service.
When a service is started, it will continue to run until it is stopped by calling the stopService()
method.
When a service is bound, it will continue to run until all clients unbind from it by calling the
unbindService() method.
Android Broadcast Receivers are components that enable the system to deliver events or messages
to the application outside of a regular user interface. They are used to listen to system-wide events,
such as the completion of a phone call or the receipt of a text message. Understanding the lifecycle
methods of broadcast receivers is essential for building robust and efficient Android applications.
The following are the two lifecycle methods of an Android Broadcast Receiver:
1. onReceive(): This is the only method that is called when a broadcast event is received
by the receiver. This method is responsible for performing the task that the receiver
was created for.
2. onDestroy(): This method is called when the receiver is destroyed. This method is
responsible for releasing any resources that were allocated by the receiver.
It is important to note that broadcast receivers are typically registered dynamically at runtime
and are not always active. When a broadcast event is received by the receiver, the system wakes
up the receiver if it is not already active.
Developers must be careful not to create receivers that consume too many resources, as it can
result in poor performance and battery life. To avoid this, receivers can be registered with certain
restrictions, such as only running when the device is charging or when the screen is on.
It is important to note that broadcast receivers are intended for short-lived operations, and any
long-running operations should be performed by services.
Android Content Providers are components that enable applications to share data with other
applications. They provide a standard interface to access a shared data set, such as a database.
Understanding the lifecycle methods of content providers is essential for building robust and
efficient Android applications.
The following are the four lifecycle methods of an Android Content Provider:
1. onCreate(): This is the first method that is called when the provider is created. This
method is responsible for initializing the provider and setting up any resources that are
needed.
2. query(): This method is called when an application requests data from the provider. This
method is responsible for returning a cursor object that contains the requested data.
3. insert(): This method is called when an application wants to add data to the provider.
This method is responsible for inserting the data into the provider's data set.
It is important to note that Content Providers are typically used in conjunction with other Android
components, such as Activities and Services. Content Providers can also be used to share data
between different applications. Developers must be careful when designing Content Providers, as
they can expose sensitive data to other applications if not properly secured.
Event handling is an essential part of building Android applications. It refers to the process of
detecting and responding to user interactions with the UI, such as clicking a button or swiping
a screen. In Android, event handling is done through the use of event listeners and event
handlers.
Event listeners are objects that are attached to UI components, such as buttons and text fields.
When a user interacts with a UI component, the listener detects the event and triggers the
appropriate event handler. E.g. Button
Event handlers are methods that are defined in the code and are responsible for responding to
specific events. E.g. onClickListener( context )
Event Listeners Registration is the process by which an Event Handler gets registered with an
Event Listener so that the handler is called when the Event Listener fires the event.
For example, if a user clicks a button, the event listener attached to the button detects the click
event and triggers the appropriate event handler. The event handler then performs the desired
action, such as displaying a message or launching another activity.
In Android, there are several types of events that can be handled, including:
1. Click events: These are triggered when a user clicks a button or other UI component.
2. Touch events: These are triggered when a user touches the screen, such as swiping or
scrolling.
3. Key events: These are triggered when a user presses a key on the device's keyboard.
4. Focus events: These are triggered when a UI component gains or loses focus.
In Android, it is possible to register event listeners for views directly in the XML layout file
using the `android:onClick` attribute. This can be a convenient way to register simple event
listeners without having to write any Java code.
Here's an example of how to register a click listener for a button directly in the XML layout:
```
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="onButtonClick"/>
```
In this example, the `android:onClick` attribute is set to "onButtonClick", which is the name
of a method that will be called when the button is clicked. To define the method, you can add
the following code to your activity:
```
```
Note that the method must be public, have a void return type, and take a single `View`
parameter. The parameter represents the view that was clicked, which is passed automatically
by the system when the method is called.
This approach can be a handy way to register simple event listeners, but it does have some
limitations. For example, it only works for certain types of events (such as clicks), and it can
Can be achieved
Using an Anonymous Inner Class
Activity class implements the Listener interface.
In Android, you can register an event listener by implementing listener interfaces in your
Java code. This approach allows you to handle events more flexibly and perform more
advanced logic than using the XML `android:onClick` attribute.
Here's an example of how to register a click listener for a button by implementing the
`View.OnClickListener` interface:
```
myButton.setOnClickListener(new View.OnClickListener() {
@Override
});
```
In this example, a reference to the button is obtained using `findViewById`, and a new
`View.OnClickListener` instance is created and passed to the `setOnClickListener` method.
The `onClick` method of the `View.OnClickListener` interface is then implemented to define
what should happen when the button is clicked.
You can also implement other listener interfaces to handle different types of events. For
example, to handle long clicks, you can implement the `View.OnLongClickListener`
interface:
```
@Override
return true; // true to indicate that the event has been consumed
});
```
Using listener interfaces allows you to handle events more flexibly and perform more
advanced logic than using the XML `android:onClick` attribute. It also allows you to handle
a wider range of events than what is supported by the `android:onClick` attribute.
Android provides robust support for graphics and multimedia, allowing developers to create rich
and engaging applications. Multimedia support has moved from OpenCORE to Stagefright as of
Android 3.0. Some of the key features of graphics and multimedia support in Android include:
1. 2D and 3D graphics: Android provides support for both 2D and 3D graphics, with
libraries such as OpenGL ES and Canvas.
2. Image and video playback: Android provides support for playing back images and videos
in a variety of formats, including JPEG, PNG, and MP4.
Playing a video is slightly more complicated than playing audio with the MediaPlayer
API, in part because you have to provide a view surface for your video to play on.
Android has a VideoView widget that handles that task for you; you can use it in any
layout manager.
<VideoView android:id="@+id/video"
android:layout_width="320px"
android:layout_height="240px" />
3. Audio playback: Android provides support for playing back audio in a variety of formats,
including MP3 and AAC.
Probably the most basic need for multimedia on a cell phone is the ability to play audio
files, whether new ringtones, MP3s, or quick audio notes. Android’s MediaPlayer is easy
to use. At a high level, all you need to do to play an MP3 file is follow these steps:
a. Put the MP3 in the res/raw directory in a project (note that you can also use a URI to
access files on the network or via the internet).
b. Create a new instance of the MediaPlayer, and reference the MP3 by calling
MediaPlayer.create().
c. Call the MediaPlayer methods prepare() and start().
By using these features, developers can create applications that are more visually appealing and
engaging for users. It is important to note that graphics and multimedia can be resource-intensive,
so developers must be careful not to create applications that consume too many resources.
S HARED PREFERENCES
Shared preference stores key-value pair of data.
The SharedPreferences class provides a general framework to store and retrieve persistent
key-value pairs of data types. You can save any primitive data types like Booleans, floats,
ints, longs and strings. The data will persist across user sessions ( even if the app is killed
).
Below are the steps for working with shared preferences in Android:
```
SharedPreferences sharedPreferences =
getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE);
```
ii. Write data to shared preferences:
To write data to shared preferences, you need to use the edit() method to get an
instance of the SharedPreferences.Editor class, and then call the putXXX()
method to store the data. XXX can be any data type like String, Boolean, Int,
Float, Long, etc. Finally, call the commit() method to save the data.
```
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "John");
editor.putInt("age", 30);
editor.putBoolean("is_logged_in", true);
editor.commit();
```
```
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("username");
editor.commit();
```
It's important to note that shared preferences are not suitable for storing large amounts of
data or sensitive data like passwords. It's best to use other storage options like internal
storage or SQLite databases for those purposes.
I NTERNAL STORAGE
Used to store private data on device memory.
To create and write a private file in storage - Call openFileOutput( ) with name of file and
mode, Write to the file with write( ), Close the stream with close( ).
To read a file , Call openFileInput( ) with name of file, Read bytes from file using read()
Close the stream with close( ).
E XTERNAL STORAGE
Stores public data on shared external storage
For Example:
DIRECTORY_MUSIC for music files
```
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "MyDatabase.db";
@Override
public void onCreate(SQLiteDatabase db) {
// Create tables and initial data
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Upgrade database schema
}
}
```
2. Create tables and initial data:
In the onCreate() method of the database helper class, you can create tables
and add initial data to the database.
```
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE users (_id INTEGER PRIMARY KEY, name
TEXT, email TEXT)");
db.execSQL("INSERT INTO users (name, email) VALUES ('John',
'[email protected]')");
}
```
3. Query data from the database:
```
SQLiteDatabase db = myDatabaseHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM users", null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String email = cursor.getString(cursor.getColumnIndex("email"));
// Do something with the data
}
cursor.close();
```
4. Insert, update, or delete data from the database:
To insert, update, or delete data from the database, you can use the insert(),
update(), or delete() methods of the SQLiteDatabase class.
```
SQLiteDatabase db = myDatabaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "Mary");
values.put("email", "[email protected]");
long newRowId = db.insert("users", null, values);
```
5. Close the database:
To close the database, you need to call the close() method of the
SQLiteDatabase class.
```
db.close();
```
It's important to note that when working with SQLite databases, you should use
parameterized queries to protect against SQL injection attacks.
1. Set up Firebase: To use Firebase, you need to create a Firebase project and add the
Firebase SDK to your Android app. You can follow the instructions in the Firebase
documentation to set up Firebase for Android.
```java
FirebaseDatabase database = FirebaseDatabase.getInstance();
```
3. Write data to the database: To write data to the Firebase database, you need to get a
reference to the database location where you want to store the data. You can do this by
calling the child() method on the database instance and passing it the path to the location.
```java
DatabaseReference myRef = database.getReference("users");
myRef.child("userId1").setValue("John");
```
4. Read data from the database: To read data from the Firebase database, you can use the
addValueEventListener() method to listen for changes to the data at a particular location.
```java
DatabaseReference myRef = database.getReference("users/userId1");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String username = dataSnapshot.getValue(String.class);
Log.d(TAG, "Username: " + username);
}
@Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
```
5. Update or delete data in the database: To update or delete data in the Firebase database,
you need to get a reference to the location of the data and use the updateChildren() or
removeValue() method.
```java
DatabaseReference myRef = database.getReference("users/userId1");
myRef.updateChildren(Collections.singletonMap("name", "Mary"));
myRef.removeValue();
```
From the above file, we can understand that , The android application
• contains 1 activity called ‘Activity1’
• has one Intent-filter, which makes Activity1 the main activity (action.MAIN) and puts it
in launcher window (category.LAUNCHER)
• can have additional components in its files as follows:
o <uses-permission> tag, used to allow certain permissions
o <services> tag, to represent services
o <reciever> tag, to represent broadcast reciever
The Android Debug Bridge (adb) utility permits you to interact with the Android emulator
directly from the command line or script. Have you ever wished you could navigate the
filesystem on your smartphone? Now you can with adb! It works as a client/server TCP-
based application.
REVIEW EXERCISES
1. Which of these was the first-ever phone released that was able to run the Android OS?
a. HTC Hero
b. Motorola Droid
c. T-Mobile G1
d. Google gPhone
a. Muffin
b. Honeycomb
c. Gingerbread
d. Cupcake
b. Android Package
c. Application Package
4. Which of these is an XML file that consists of all the text used in an application?
a. string.java
b. string.xml
c. text.xml
d. stack.xml
a. Paused
b. Destroyed
c. Running
d. Starting
Answer (a)
8. Which of the following is the first callback method that is invoked by the system during an
activity life-cycle?
a. onClick() method
b. onCreate() method
c. onStart() method
d. onRestart() method
Answer: (c)
10. Which of the following android component displays the part of an activity on screen?
a. View
b. Manifest
Answer: (d)
Answer: (b)
a. Source code
b. List of strings used in the app
c. Permission that the application requires
d. None of the above
Answer: (c)
13. In which state the activity is, if it is not in focus, but still visible on the screen?
a. Stopped state
b. Destroyed state
c. Paused state
d. Running state
Answer: (c)
14. In Android studio, which of the following callback is called when an activity starts interacting
with the user?
a. onDestroy
b. onCreate
c. onResume
Answer: (c)
15. Which of the following class in android displays information for a short period of time and
disappears after some time?
a. toast class
b. log class
c. maketest class
d. None of the above
Answer: (a)
a. android.view.View
b. android.view.ViewGroup
c. android.widget
d. None of the above
Answer: (b)
17. Which of the following layout in android aligns all children either vertically or horizontally?
a. RelativeLayout
b. TableLayout
c. FrameLayout
d. LinearLayout
Answer: (d)
a) Linear Layout
b) Constraint Layout
c) Relative Layout
d) Card Layout
Answer (b)
Answer (a)
a. Gradle
b. AndroidManifest
c. AVD
d. SDK
Answer (a)