0% found this document useful (0 votes)
11 views220 pages

CP 313 All Lectures

The document outlines the course CP 313: Mobile Applications Development, detailing instructors, delivery modes, assessments, and an introduction to Android as an open-source mobile operating system. It covers the Android development environment, application components, project structure, and essential UI controls. Additionally, it provides references and resources for further learning in Android development.

Uploaded by

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

CP 313 All Lectures

The document outlines the course CP 313: Mobile Applications Development, detailing instructors, delivery modes, assessments, and an introduction to Android as an open-source mobile operating system. It covers the Android development environment, application components, project structure, and essential UI controls. Additionally, it provides references and resources for further learning in Android development.

Uploaded by

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

CP 313: MOBILE APPLICATIONS DEVELOPMENT

Sunday, 22 January 2023 REDMOL 1


Instructors

Mr. Siphael Betuel


0756836130
BA 02 Administration Block
Mr. Abraham Macha
0622843428

Sunday, 22 January 2023 REDMOL 2


Delivery Mode
Lectures
Tutorials
Labs

Sunday, 22 January 2023 REDMOL 3


Assessments
Test(s)
Assignments
Quizzes
Labs
Projects
UE

Sunday, 22 January 2023 REDMOL 4


Introduction

Sunday, 22 January 2023 REDMOL 5


Mobile Phones OS

Sunday, 22 January 2023 REDMOL 6


Introduction
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, led by
Google, and other companies.
Android programming is based on Java programming language
 If you have basic understanding on Java programming then it will
be a fun to learn Android application development.

Sunday, 22 January 2023 REDMOL 7


What is Android?

Sunday, 22 January 2023 REDMOL 8


What is Android?
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, led by
Google, and other companies.
Android offers a unified approach to application development for
mobile devices which means developers need only develop for
Android, and their applications should be able to run on different
devices powered by Android.

Sunday, 22 January 2023 REDMOL 9


What is Android?

The first beta version of the Android Software Development Kit


(SDK) was released by Google in 2007
The first commercial version, Android 1.0, was released in
September 2008.
The source code for Android is available under free and open source
software licenses.
Google publishes most of the code under the Apache License
version 2.0 and the rest, Linux kernel changes, under the GNU
General Public License version 2.

Sunday, 22 January 2023 REDMOL 10


Why Android ?

Sunday, 22 January 2023 REDMOL 11


Categories of Android applications

Sunday, 22 January 2023 REDMOL 12


Android Versions Naming

Sunday, 22 January 2023 REDMOL 13


Android API Levels
API Level is an integer value that uniquely identifies the framework API revision offered by a
version of the Android platform.
The framework API consists of:
A core set of packages and classes
A set of XML elements and attributes for declaring a manifest file
A set of XML elements and attributes for declaring and accessing resources
A set of Intents
A set of permissions that applications can request, as well as permission enforcements
included in the system
The initial release of the Android platform provided API Level 1 and subsequent releases have
incremented the API Level.

Sunday, 22 January 2023 REDMOL 14


Android API Levels

Sunday, 22 January 2023 REDMOL 15


Environment Setup
Java JDK
Android Studio

Sunday, 22 January 2023 REDMOL 16


Java Development Kit (JDK)
You can download the latest version of JDK from
https://www.oracle.com/java/technologies/downloads/
Finally set PATH and JAVA_HOME environment variables to refer to the directory that
contains java and javac

Sunday, 22 January 2023 REDMOL 17


JAVA IDEs
There are so many sophisticated Technologies are available
to develop android applications, the familiar technologies
are: -
Android Studio
◦Eclipse IDE(Deprecated)

Sunday, 22 January 2023 REDMOL 18


Android - Application Components
Application components are the essential building blocks of an
Android application.
These components are loosely coupled by the application manifest
file AndroidManifest.xml that describes each component of the
application and how they interact.

Sunday, 22 January 2023 REDMOL 19


Android - Application Components

Sunday, 22 January 2023 REDMOL 20


Activities
An activity represents a single screen with a user interface, in-short Activity performs actions
on the screen.
 For example, an email application might have one activity that shows a list of new emails,
another activity to compose an email, and another activity for reading emails.
If an application has more than one activity, then one of them should be marked as the activity
that is presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows −

public class MainActivity extends Activity {


}

Sunday, 22 January 2023 REDMOL 21


Services
A service is a component that runs in the background to perform long-running operations.
For example, a service might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking user interaction with an
activity.
A service is implemented as a subclass of Service class as follows −
public class MyService extends Service {
}

Sunday, 22 January 2023 REDMOL 22


Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from the
system.
For example, applications can also initiate broadcasts to let other applications know that some
data has been downloaded to the device and is available for them to use, so this is broadcast
receiver who will intercept this communication and will initiate appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcaster as an Intent object.
public class MyReceiver extends BroadcastReceiver {
public void onReceive(context,intent){}
}

Sunday, 22 January 2023 REDMOL 23


Content Providers
A content provider component supplies data from one application to others on request.
 Such requests are handled by the methods of the ContentResolver class.
The data may be stored in the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must implement
a standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends ContentProvider {
public void onCreate(){}
}

Sunday, 22 January 2023 REDMOL 24


Other components

Sunday, 22 January 2023 REDMOL 25


Sunday, 22 January 2023 REDMOL 26
Proposed references
I. The Busy Coder's Guide to Android Development, CommonsWare, LLC, by
Mark L. Murphy, 2008
II. https://www.youtube.com/playlist?list=PLonJJ3BVjZW6hYgvtkaWvw
AVvOFB7fkLa
III. http://www.tutorialspoint.com/android/index.htm
IV. http://developer.android.com/index.html
V. https://www.udemy.com/
VI. http://www.androidhive.info/

Sunday, 22 January 2023 REDMOL 27


CP 313: MOBILE APPLICATIONS DEVELOPMENT
Android Project Structure

Android Studio is the official IDE (Integrated


Development Environment) developed by JetBrains
community which is freely provided by Google for
android app development.
After completing the setup of Android Architecture
we can create android application in the studio.
Android Project Structure(Manifests Folder)

Manifests folder contains AndroidManifest.xml for our


creating the android application.
 This file contains information about our application such as
android version, metadata, states package for Kotlin file and
other application components.
 It acts as an intermediator between android OS and our
application.
Android Project Structure (Manifest file)
Android Project Structure (Manifest file)

Among many other things, the manifest file is required to declare the following:
• The app's package name.
usually matches your code's namespace. The Android build tools use this to
determine the location of code entities when building your project. When
packaging the app, the build tools replace this value with the application ID
from the Gradle build files, which is used as the unique app identifier on the
system and on Google Play.
Android Project Structure (Manifest file)

An intent-filter
This is a tag used in the manifest file of your app, generally for two
basic reasons:-
To specify which activity of your app is going to be
the launcher activity(the home screen).
It is used to register broadcast receivers or services.
Android Project Structure (Manifest file)

App components
For each app component that you create in your app, you must declare a
corresponding XML element in the manifest file:
<activity> for each subclass of Activity.
<service> for each subclass of Service.
<receiver> for each subclass of BroadcastReceiver.
<provider> for each subclass of ContentProvider.
If you subclass any of these components without declaring it in the manifest
file, the system cannot start it.
Android Project Structure (Manifest file)

Icons and labels


A number of manifest elements have icon and label attributes for
displaying a small icon and a text label, respectively, to users for the
corresponding app component.
In every case, the icon and label that are set in a parent element become
the default icon and label value for all child elements. For example, the
icon and label that are set in the <application> element are the default icon
and label for each of the app's components (such as all activities).
Android Project Structure (Manifest file)

Permissions
Android apps must request permission to access sensitive user data (such as
contacts and SMS) or certain system features (such as the camera and internet
access).
Each permission is identified by a unique label.
For example, an app that needs to send SMS messages must have the following
line in the manifest:
<manifest ... >
<uses-permission android:name="android.permission.SEND_SMS"/>
...
</manifest>
Android Project Structure (Manifest file)

Device compatibility
The manifest file is also where you can declare what types of hardware or
software features your app requires, and thus, which types of devices your app is
compatible with.
Google Play Store does not allow your app to be installed on devices that don't
provide the features or system version that your app requires.
There are several manifest tags that define which devices your app is compatible
with.
The following are just a couple of the most common tags.
Android Project Structure (Manifest file)

<uses-feature>
The <uses-feature> element allows you to declare hardware and software features
your app needs. For example, if your app cannot achieve basic functionality on a
device without a compass sensor, you can declare the compass sensor as required
with the following manifest tag:

<manifest ... >


<uses-feature android:name="android.hardware.sensor.compass“
android:required="true" />
...
</manifest>
Android Project Structure (Manifest file)

<uses-sdk>
Each successive platform version often adds new APIs not available in the
previous version.
To indicate the minimum version with which your app is compatible, your
manifest must include the <uses-sdk> tag and its minSdkVersion attribute.
Android Project Structure (Java folder)

Java folder contains all the java and Kotlin source code (.java) files which we
create during the app development, including other Test files.
If we create any new project using java, by default the class file
MainActivity.java file will create automatically under the package name
“com.example.myapplication1” like as shown below.
Android Project Structure (Java folder)
Android Project Structure (Resource (res) folder)

Resource folder is the most important folder because it


contains all the non-code sources like images, XML layouts,
UI strings for our android application
Android Project Structure (Resource (res) folder)
Android Project Structure (Resource (res) folder)

res/drawable folder
It contains the different type of images used for the development of
the application.
We need to add all the images in drawable folder for the application
development.
Android Project Structure (Resource (res) folder)

res/layout folder
Layout folder contains all XML layout files which we used to define
the user Interface of our application.
It contains the activity_main.xml file.
Android Project Structure (Resource (res) folder)

res/mipmap folder
This folder contains launcher.xml files to define icons which are used
to show on the home screen.
It contains different density type of icons depends upon the size of the
device such as hdpi, mdpi, xhdpi.
Android Project Structure (Resource (res) folder)

res/values folder
Values folder contains a number of XML files like strings, dimens,
colors and styles definitions.
One of the most important file is strings.xml file which contains the
resources.
Android Project Structure (Resource (res) folder)

A menu
This resource defines an application menu (Options Menu, Context
Menu, or submenu) that can be inflated with MenuInflater.
Android Project Structure (Gradle Scripts folder)

Gradle means automated build system and it contains number of


files which are used to define a build configuration which can be
apply to all modules in our application.
 In build.gradle (Project) there are build scripts and in build.gradle
(Module) plugins and implementations are used to build
configurations that can be applied to all our application modules.
Layouts in android
Android Layout is used to define the user interface that holds the
UI controls or widgets that will appear on the screen of an android
application or activity screen.
Each activity contains multiple user interface components and those
components are the instances of the View and ViewGroup
Layouts in android
A layout defines the structure for a user interface in your app, such as
in an activity.
All elements in the layout are built using a hierarchy of View and
ViewGroup objects.
A View usually draws something the user can see and interact with.
ViewGroup is an invisible container that defines the layout structure
for View and other ViewGroup objects.
Layouts in android
Layouts in android
The View objects are usually called "widgets" and can be
one of many subclasses, such as Button or TextView.
The ViewGroup objects are usually called "layouts" can be
one of many types that provide a different layout structure,
such as LinearLayout or ConstraintLayout .
Layouts in android(LinearLayout)
LinearLayout is a view group that aligns all children in a single
direction, vertically or horizontally.
Layouts in android(common properties)
android:id
This is the ID which uniquely identifies the view.
android:layout_width
This is the width of the layout.
android:layout_height
This is the height of the layout

android:layout_marginTop
This is the extra space on the top
side of the layout.
Layouts in android(common properties)
android:layout_marginBottom
This is the extra space on the bottom side of the layout.
android:layout_marginLeft
This is the extra space on the left side of the layout.
android:layout_marginRight
This is the extra space on the right side of the layout.
android:layout_gravity
This specifies how child Views are positioned.
Layouts in android(common properties)
android:layout_weight
This specifies how much of the extra space in the layout
should be allocated to the View.
Layouts in android(Relative Layout)
RelativeLayout is a view group that displays child views in relative positions.
RelativeLayout enables you to specify how child views are positioned relative to
each other.
The position of each view
can be specified as relative to
sibling elements or relative to the parent.
Layouts in android(Table Layout)
TableLayout - displays elements in the form of a table, with rows and
columns.
Android UI Controls
There are number of UI controls provided by Android that
allow you to build the graphical user interface for your app.
A TextView displays text to the user and optionally allows
them to edit it.
A TextView is a complete text editor, however the basic class
is configured to not allow editing.
Android UI Controls(attributes of text view)
android:id
This is the ID which uniquely identifies the control.
android:capitalize
If set, specifies that this TextView has a textual input method and should automatically capitalize
what the user types.
android:hint
Hint text to display when the text is empty.
android:password
Whether the characters of the field are displayed as password dots instead of themselves. Possible
value either "true" or "false".
Android UI Controls(Edit Text)
A EditText is an overlay over TextView that configures itself to be
editable.
It is the predefined subclass of TextView that includes rich editing
capabilities.
Android UI Controls(Button)
A Button is a Push-button which can be pressed, or clicked, by the
user to perform an action.
Android UI Controls(Check Box)
A CheckBox is an on/off switch that can be toggled by the
user.
You should use check-boxes when presenting users with a
group of selectable options that are not mutually exclusive.
Android UI Controls(Radio Button)
A RadioButton has two states: either checked or unchecked.
This allows the user to select one option from a set.
Android UI Controls(Spinner)
Spinner allows you to select an item from a drop down
menu
END
CP 313: MOBILE APPLICATIONS DEVELOPMENT
Contents
oActivities
● Defining an activity
● Starting a new activity with an intent
● Passing data between activities with extras
● Navigating between activities
What is an Activity?
oAn Activity is an application component
● Represents one window, one hierarchy of views
● Typically fills the screen, but can be embedded in other
activity or a appear as floating window
● Java class, typically one activity in one file
What is an Activity?
oAn activity represents a single screen with a user interface
just like window or frame of Java.
oAndroid activity is the subclass of ContextThemeWrapper
class.
Activity Life Cycle
If you have worked with C, C++ or Java programming language then
you must have seen that your program starts from main() function.
Very similar way, Android system initiates its program with in an
Activity starting with a call on onCreate() callback method.
 There is a sequence of callback methods that start up an activity and
a sequence of callback methods that tear down an activity as shown in
the next slide.
Activity Life Cycle
Activity Life Cycle
onCreate(): This is the first callback and called when the activity is first created.
onStart(): This callback is called when the activity becomes visible to the user.
onResume(): This is called when the user starts interacting with the application.
onPause(): The paused activity does not receive user input and cannot execute any
code and called when the current activity is being paused and the previous activity is
being resumed.
onStop(): This callback is called when the activity is no longer visible.
onDestroy(): This callback is called before the activity is destroyed by the system.
onRestart(): This callback is called when the activity restarts after stopping it.
What does an Activity do?
Represents an activity, such as ordering groceries, sending
email, or getting directions
● Handles user interactions, such as button clicks, text entry,
or login verification
● Can start other activities in the same or other apps
● Has a life cycle—is created, started, runs, is paused,
resumed, stopped, and destroyed
Examples of Activities
Apps and activities
Activities are loosely tied together to make up an app
● First activity user sees is typically called "main activity"
● Activities can be organized in parent-child relationships in
the Android manifest to aid navigation
Layouts and Activities
An activity typically has a UI layout
● Layout is usually defined in one or more XML files
● Activity "inflates" layout as part of being created
Implement new activities
1.Define layout in XML
2. Define Activity Java class
○ extends AppCompatActivity
3. Connect Activity with Layout
○ Set content view in onCreate()
4. Declare Activity in the Android manifest
1. Define layout in XML
2. Define Activity Java class
3. Connect activity with layout
3. Connect activity with layout
package com.example.myapplication10;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
3. Connect activity with layout
public class MainActivity extends AppCompatActivity {
private EditText FirstName,LastName, Results;
private Button Submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirstName = (EditText) findViewById(R.id.editTextFName);
LastName =(EditText) findViewById(R.id.editTextLName);
Results =(EditText) findViewById(R.id.tvResults);
Submit =(Button) findViewById(R.id.btnSubmit);
3. Connect activity with layout
Submit.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

int num1=Integer.parseInt(FirstName.getText().toString());

int num2=Integer.parseInt(LastName.getText().toString());

int sum=num1+num2;

Results.setText("The Answer is "+sum);

});

}
4. Declare activity in Android manifest
4. Declare main activity in manifest
Intents
What is an intent?
An intent is a description of an operation to be performed.
An Intent is an object used to request an action from another
app component via the Android system.
What can intents do?
oStart activities
◦ A button click starts a new activity for text entry
◦ Clicking Share opens an app that allows you to post a photo
● Start services
◦ Initiate downloading a file in the background
● Deliver broadcasts
◦ The system informs everybody that the phone is now charging
Types of Intents
Explicit Intent
Implicit Intent
Types of Intents (Explicit Intent)

We can also pass the information from one activity to another using explicit intent.
Types of Intents (Implicit Intent)

We can also pass the information from one activity to another using explicit intent.
Starting Activities
Start an Activity with an explicit intent
To start a specific activity, use an explicit intent
1. Create an intent
○ Intent intent = new Intent(this, ActivityName.class);
2. Use the intent to start the activity
○ startActivity(intent);
public void onClick(View v) {
}
});

}
public void Activity2(){
Intent myIntent = new Intent(this,HomeActivity.class);
startActivity(myIntent);
}
}
Sending and Receiving Data
We can send data while calling one activity from another activity
using intent.
 All we have to do is add the data to Intent object using putExtra()
method.
The data is passed in key value pair.
The value can be of types like int, float, long, string, etc.
Sending Data
Submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Activity2();

}
});
}
public void Activity2(){
int num1=Integer.parseInt(FirstName.getText().toString());
int num2=Integer.parseInt(LastName.getText().toString());
//int sum=num1+num2;
// Results.setText("The Answer is "+sum);
Intent myIntent = new Intent(this,HomeActivity.class);
myIntent.putExtra("numberOne:",num1);
myIntent.putExtra("numberTwo:",num2);
startActivity(myIntent);
}
}
Receiving Data
public class HomeActivity extends AppCompatActivity {
private TextView n1,n2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
n1=(TextView)findViewById(R.id.tvNumber1);
n2=(TextView)findViewById(R.id.tvNumber2);

Intent intent =getIntent();


int number_one = Integer.parseInt(intent.getStringExtra("numberOne"));
int number_two = Integer.parseInt(intent.getStringExtra("numberTwo"));
n1.setText(number_one);
n2.setText(number_two);

}
}
Intents can be used for broadcasting a
message
Suppose that the battery of your mobile phone is low and
the message is sent to different android applications to your
phone alerting that the battery is low
Your Turn
Services
Broadcast Message
Implicit Intents
END
CP 313: Mobile Application Development

Android Fragments
Lecture # 4

REDMOL Saturday, October 07, 2023


Fragments
• Fragment represents a behavior or a portion of
UI in an Activity.
• It is a kind of sub-activity.
• Multiple fragments can be combined in a
single activity to build a multi-pane UI and
reuse a fragment in multiple activities.
• You can add or remove fragments in an activity
while activity is running.

REDMOL Saturday, October 07, 2023 2


Fragments
• An activity can contain any number of fragments.
• Fragment life cycle is closely related to lifecycle
of its host activity
• This means when activity is paused, all
fragments available in activity will also be
stopped.

REDMOL Saturday, October 07, 2023 3


Fragments

• Fragments were added to Android API in


Honeycomb (3.0) version of Android which
API version 11.
• Earlier we had a limitation because we can
show only a single activity on screen at one
given point in time. So we were not able to
divide device screen and control different
parts separately.

REDMOL Saturday, October 07, 2023 4


Fragments

• But with fragment we got more flexibility and


removed limitation of having a single activity
on screen at a time. Fragments will have their
own layout, events and complete lifecycle.
• You create fragments by extending Fragment
class and you can insert a fragment into your
activity layout by declaring fragment in
activity's layout file, as a <fragment> element.

REDMOL Saturday, October 07, 2023 5


Fragments

REDMOL Saturday, October 07, 2023 6


Fragment Lifecycle

REDMOL Saturday, October 07, 2023 7


Fragment Lifecycle
Phase I: When a fragment gets created, it goes through
following states:

• onAttach() // when a frag is attached to its


hosting activity
• onCreate() //frag is initialized, but no UI
• onCreateView() //frag sets up and returns its UI.
This view is given to hosting
activity afterwards.
• onActivityCreated() // Now frag’s life cycle is
depending upon its hosting activity’s life
REDMOL
cycle Saturday, October 07, 2023 8
Fragment Lifecycle
Phase II: When fragment becomes visible, it goes
through these states:
onStart() //hosting activity is about to become
visible
onResume() // hosting activity is about to become
visible and ready for user interaction

REDMOL Saturday, October 07, 2023 9


Fragment Lifecycle

Phase III: When fragment goes into background mode,


it goes through this states.
onPaused() //hosting activity is visible, but another
activity is in the foreground and has focus
onStop() // When hosting activity is not visible

REDMOL Saturday, October 07, 2023 10


Fragment Lifecycle
Phase IV: When fragment is destroyed, it goes through
following states:
• onPaused() • onStop()
• onDestroyView() //hosting activity is about to be
destroyed any frag that it is hosting also has to
be shut down
• onDestroy() //release frag resources
• onDetach() //null out references to hosting
activity

REDMOL Saturday, October 07, 2023 11


ADDING FRAGMENTS TO ACTIVITIES
Two general ways
1. First,
i. Fragment can be statically added to the activity’s
layout file.
ii. It is then used in a call to setContentView method.
2. Second,
i. Add it programmatically (dynamicaaly) using
FragmentManager

REDMOL Saturday, October 07, 2023 12


How to use Fragments?
This involves number of simple steps to create Fragments.
• 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.
• Fragment class has above mentioned callback functions.
• You can override any of the functions based on your
requirements.
REDMOL Saturday, October 07, 2023 13
How to use Fragments?
• 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 actual logic of
replacing fragments based on your requirement.

A Useful Trick!
• Press Ctrl and click on keyword of java in Android Studio.
You will get complete definitions of that keyword.
REDMOL Saturday, October 07, 2023 14
ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY

 STEP ONE
Create the fragment

REDMOL Saturday, October 07, 2023 15


ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY

REDMOL Saturday, October 07, 2023 16


ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY

REDMOL Saturday, October 07, 2023 17


ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY

 STEP TWO
Define the activity to host the fragment

REDMOL Saturday, October 07, 2023 18


ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY
<? xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment Title"
android:textSize="40dp"
android:gravity="center">
</TextView>
REDMOL Saturday, October 07, 2023 19
ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY
<Button
android:id="@+id/btnFirstFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment One"
android:textSize="40dp"
android:layout_below="@id/tvTitle"
android:gravity="center"></Button>
<Button
android:id="@+id/btnSecondFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment Two"
android:textSize="40dp"
android:layout_below="@id/btnFirstFragment"
android:gravity="center"></Button>
REDMOL Saturday, October 07, 2023 20
ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY

<LinearLayout
android:id="@+id/fragMentCOntainer"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_below="@id/btnSecondFragment"
android:layout_margin="30dp"
android:layout_height="wrap_content">
android:la
</LinearLayout>

</RelativeLayout>

REDMOL Saturday, October 07, 2023 21


ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY

REDMOL Saturday, October 07, 2023 22


ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY

Step Three
Add the fragment in the activity you have
created

REDMOL Saturday, October 07, 2023 23


ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY

public class MainActivity extends AppCompatActivity {


Button fragOne, fragTwo;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
fragOne=(Button) findViewById(R.id.btnFirstFragment );
fragTwo=(Button) findViewById(R.id.
btnSecondFragment );
REDMOL Saturday, October 07, 2023 24
ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY
fragOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment frag1=new FragmentOne();
FragmentTransaction ft=getSupportFragmentManager().
beginTransaction();
ft.replace(R.id.fragMentCOntainer ,frag1);
ft.addToBackStack(null);
ft.commit();
}
});
REDMOL Saturday, October 07, 2023 25
ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY

fragTwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment frag2=new FragmentTwo();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragMentCOntainer ,frag2);
ft.addToBackStack(null);
ft.commit();
}
});

REDMOL Saturday, October 07, 2023 26


REDMOL Saturday, October 07, 2023 27
CP 313: Mobile Apps
Development
Services, Broadcast Receivers and
Notifications
Contents

• Services
• Broadcast Receivers
• Notifications
Services

• A Service is an application component that


can perform long-running operations in the
background.
• It does not provide a user interface.
• Once started, a service might continue
running for some time, even after the user
switches to another application.
Services

• Additionally, a component can bind to a


service to interact with it and even perform
interprocess communication (IPC).
• For example, a service can handle network
transactions, play music, perform file I/O, or
interact with a content provider, all from the
background.
Characteristics of a services
• Services starts with an Intent
• Can stay running when the user switches the
applications
• Services have life cycle
• Runs in the main thread of its hosting process
Types of Services
(There are three types of services:)
Foreground Services
• 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.
• Foreground services continue running even when the
user isn't interacting with the app.
Types of Services
(There are three types of services:)

Foreground Services
• When you use a foreground service, you must
display a notification so that users are actively
aware that the service is running.
• This notification cannot be dismissed unless the
service is either stopped or removed from the
foreground.
Types of Services
(There are three types of services:)

Background
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.
Types of Services
(There are three types of services:)

Bound
A service is bound when an application component binds to it by calling
bindService().
 A bound service offers a client-server interface that allows
components to interact with the service, send requests, receive results,
and even do so across processes with interprocess communication
(IPC).
 A bound service runs only as long as another application component is
bound to it.
Multiple components can bind to the service at once, but when all of
them unbind, the service is destroyed.
Services life cycle
• In android, services have Two (2) possible paths to complete its
life cycle namely Started and Bounded.
Started Service (Unbounded Service):
• By following this path, a service will initiate when an
application component calls the startService() method.
• Once initiated, the service can run continuously in the
background even if the component is destroyed which
was responsible for the start of the service.
Services life cycle
• To create a service, you must create a subclass of
Service or use one of its existing subclasses.
• In your implementation, you must override some
callback methods that handle key aspects of the
service lifecycle and provide a mechanism that allows
the components to bind to the service, if appropriate.
• These are the most important callback methods that
you should override:
Services life cycle
onStartCommand()
• The system invokes this method by calling startService()
when another component (such as an activity) requests
that the service be started.
• When this method executes, the service is started and
can run in the background indefinitely.
Services life cycle
• If you implement this, it is your responsibility to stop the
service when its work is complete by calling stopSelf()
or stopService().
• If you only want to provide binding, you don't need to
implement this method.
Services life cycle
Services life cycle
 Bounded Service:
• It can be treated as a server in a client-server interface.
• By following this path, android application components can
send requests to the service and can fetch results.
• A service is termed as bounded when an application
component binds itself with a service by calling bindService()
method.
• To stop the execution of this service, all the components must
unbind themselves from the service by using unbindService()
method.
Services life cycle
onBind()
The system invokes this method by calling
bindService() when another component wants to bind
with the service (such as to perform RPC).
 In your implementation of this method, you must
provide an interface that clients use to communicate
with the service by returning an IBinder.
You must always implement this method; however, if
you don't want to allow binding, you should return null.
Services life cycle
onCreate()
The system invokes this method to perform one-time
setup procedures when the service is initially created
(before it calls either onStartCommand() or onBind()).
If the service is already running, this method is not
called.
Services life cycle
onDestroy()
The system invokes this method when the
service is no longer used and is being destroyed.
Your service should implement this to clean up
any resources such as threads, registered
listeners, or receivers.
This is the last call that the service receives.
Declaring a service in the manifest
• You must declare all services in your application's manifest file, just as you
do for activities and other components.
• To declare your service, add a <service> element as a child of the
<application> element. Below is an example:
<manifest ... >
...
<application ... >
<service android:name=".ExampleService" />
...
</application>
</manifest>
Creating a started service
• A started service is one that another component starts by
calling startService(), which results in a call to the service's
onStartCommand() method.
• When a service is started, it has a lifecycle that's independent of
the component that started it.
• The service can run in the background indefinitely, even if the
component that started it is destroyed.
• As such, the service should stop itself when its job is complete
by calling stopSelf(), or another component can stop it by
calling stopService().
Creating a started service
• An application component such as an activity can start the
service by calling startService() and passing an Intent that
specifies the service and includes any data for the service to use.
• The service receives this Intent in the onStartCommand() method.
• The Service class is the base class for all services.
• When you extend this class, it's important to create a new thread
in which the service can complete all of its work; the service uses
your application's main thread by default, which can slow the
performance of any activity that your application is running.
Creating a started service (Interface)
<? xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/
android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Service App"
android:textStyle="bold"
android:textSize="40dp"
android:textColor="@color/teal_200"
android:gravity="center">
</TextView>
<Button
android:id="@+id/btnStartService"
Creating a android:layout_width="match_parent"
android:layout_height="wrap_content"
started service android:layout_below="@+id/tvTitle"
android:layout_marginTop="30sp"
(Interface) android:text="Start Service"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="@color/Red"
android:gravity="center">
</Button>

<Button
android:id="@+id/btnStopService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btnStartService"
android:layout_marginTop="30sp"
android:text="Stop Service"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="@color/Red"
android:gravity="center">
</Button>
Creating a package com.example.
Service by myapplication;
extending a
import android.app.Service;
service class. import android.content.Intent;
import android.os.IBinder;

public class Service_one extends


Service {
public Service_one() {
}
Overriding @Override
public void onCreate() {
onCreate(), super.onCreate();
}
onSstartCOm
mand() and @Override
public int onStartCommand(Intent intent, int
onDestroy() flags, int startId) {
return super.onStartCommand(intent, flags,
methods startId);
}

@Override
public void onDestroy() {
super.onDestroy();
}
public class MainActivity extends AppCompatActivity {
Button startService, stopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Link the setContentView(R.layout.activity_main);


startService=(Button) findViewById(R.id.btnStartService);

Interface with
stopService=(Button) findViewById(R.id.btnStopService);
startService.setOnClickListener(new View.OnClickListener() {
@Override

the service public void onClick(View v) {


Intent myIntent=new Intent(MainActivity.this,Service_one.class);
startService(myIntent);
}
});
stopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this, Service_one.class);
stopService(i);
}
});
}
public int onStartCommand(Intent intent, int flags, int
startId) {
myPlayer=MediaPlayer.create(Service_one.this, Settings.
MediaPlayer System.DEFAULT_RINGTONE_URI);
myPlayer.setLooping(true);
Class myPlayer.start();
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
myPlayer.stop();

}
}
Services Behaviors
Services Behaviors
START_STICKY
 Services that are explicit managed and long running ie. Your
starting your services and you are stopping your services using
startService() and stopService() methods.
The advantage of START_STICKY is if the service get killed, it will
automatically get started.
But when it get restarted, it will not get the intent values, so the
intent value will be NULL ie. It will not remember what was the
previous calculated value in the intent.
Music service is a good example here. You don’t your music to get
started automatic on your ears in unexpected time.
Services Behaviors
START_NOT_STICKY
You are not starting the service but the intent is triggered you will
start it.
Here the services are running periodically and get self stop.
If the service get stopped, it will not automatically restarted. If the
service get killed, and intent is triggered, then the service will start.
Tasks that runs periodically in the background are examples of
START_NOT_STICKY
Alarm service is an example of such a service.
Services Behaviors
START_REDELIVER_INTENT
Here The services will always get restated and it will
get the previous intent values.
Good example is a file download.
If the file stopped due to internet connection, when the
internet connection is available, then the file has to
restated automatically and it has to continue where it
ended when the internet connection get lost.
Bound Services
• A bound service is the server in a client-server interface.
• A bound service allows components (such as activities)
to bind to the service, send requests, receive responses,
and even perform interprocess communication (IPC).
• A bound service typically lives only while it serves
another application component and does not run in the
background indefinitely.
Bound Services
• A bound service is an implementation of the Service
class that allows other applications to bind to it and
interact with it.
• To provide binding for a service, you must implement
the onBind() callback method.
• This method returns an IBinder object that defines the
programming interface that clients can use to interact
with the service.
Bound Services
• A client can bind to the service by calling bindService().
• When it does, it must provide an implementation of
ServiceConnection, which monitors the connection with the
service.
• The bindService() method returns immediately without a
value, but when the Android system creates the connection
between the client and service, it calls
onServiceConnected() on the ServiceConnection, to deliver
the IBinder that the client can use to communicate with the
service.
Bound Services
• Multiple clients can connect to the service at once.
• However, the system calls your service's onBind()
method to retrieve the IBinder only when the first client
binds.
• The system then delivers the same IBinder to any
additional clients that bind, without calling onBind() again.
• When the last client unbinds from the service, the system
destroys the service (unless the service was also started
by startService()).
Creating a Bound Service
• When you implement your bound service, the most important
part is defining the interface that your onBind() callback method
returns.
• When creating a service that provides binding, you must provide
an IBinder that provides the programming interface that clients
can use to interact with the service.
• There are three ways you can define the interface:
Creating a Bound Service
Creating a Bound Service
Extending the Binder class
If your service is private to your own application and runs in the
same process as the client (which is common), you should
create your interface by extending the Binder class and returning
an instance of it from onBind().
The client receives the Binder and can use it to directly access
public methods available in either the Binder implementation or
even the Service.
Creating a Bound Service
Using a Messenger
If you need your interface to work across different processes, you
can create an interface for the service with a Messenger.
Using AIDL
AIDL (Android Interface Definition Language) performs all the
work to decompose objects into primitives that the operating
system can understand and marshall them across processes to
perform IPC.
 The previous technique, using a Messenger, is actually based on
AIDL as its underlying structure
Creating a bound Service
Creating a bound Service
Creating a bound Service
Creating a bound Service
Creating a bound Service
Creating a bound Service
Creating a bound Service
Creating a bound Service
BROADCAST RECEIVERS
Examples Events occurring in android
Register events in manifest file (static) or
in code(dynamically)
Step One: Creating a Java class that
extends Broadcast Receiver
package com.example.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class BroadCastReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText (context, "Incoming SMS", Toast.LENGTH_LONG ).show();
}
}
Step Two: Register the Broadcast Receiver
<? xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-
permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".BroadCastReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter></receiver>
</application></manifest>
Your Turn

Learn how to register broadcast


receiver in a code instead of
manifest file
Android Notifications
END
Data Storage
LECT_SIX
Introduction
• Depending on the requirements of your
application, you may need to store data in a
variety of places.
• For example, if an application interacts with
music files and a user wants to play them in
more than one music program, you have to store
them in a location where all applications can
access them.
Introduction
• An application that needs to store sensitive data,
such as encrypted usernames and password
details, shouldn’t share data — placing it in a
secure, local storage environment is the best
strategy.
• Regardless of your situation, Android provides
various options for storing data.
Where you can save your data?
Where you can save your data?
Where you can save your data?
Shared preferences
 If you have a relatively small collection of key-values
that you'd like to save, you should use the
SharedPreferences APIs.
A SharedPreferences object points to a file containing
key-value pairs and provides simple methods to read
and write them.
 Each SharedPreferences file is managed by the
framework and can be private or shared.
Shared preference

Demo
Shared preference
Shared preference
public class MainActivity extends AppCompatActivity {
Button save;
EditText name,email;
public static final StringSHARED_PREF ="shared preference";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
save=(Button) findViewById(R.id.btnSave );
name=(EditText) findViewById(R.id.etName );
email=(EditText) findViewById(R.id.etEMail );
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveData();
}
});
}
Shared preference

public void saveData(){


SharedPreferences sp=getSharedPreferences(SHARED_PREF M , ODE_PRIVATE );
SharedPreferences.Editor edit=sp.edit();
edit.putString("name",name.getText().toString());
edit.putString("email",email.getText().toString());
edit.apply();
Toast.makeText (MainActivity.this, "Data successfully saved", Toast.LENGTH_SHORT ).show();
}
}
Introduction
Internal storage:
A location for saving files on the device.
Files stored in internal storage are private to
your application by default, and other
applications cannot access them. (Neither can
the user, except by using your application.)
When the application is uninstalled, the private
files are deleted as well.
Introduction
Local cache:
The internal data directory for caching data
rather than storing it persistently.
Cached files may be deleted at any time.
You use the getCacheDir() method, available on
the Activity or Context objects in Android.
Introduction
If you store data in an internal data directory and
the internal storage space begins to run low,
Android may delete files to reclaim space.
Don’t rely on Android to delete your files for you
though! You should delete your cache files
yourself to stay within a reasonable limit
(for example, around 1MB) of space consumed
in the cache directory.
Introduction
External storage:
Every Android device supports shared external storage for
files — either removable storage, such as a Secure Digital
card (SD card) or non removable storage.
Files saved to external storage are public (any person or
application can alter them), and no level of security is
enforced.
 Users can modify files by either using a file manager
application or connecting the device to a computer via a
USB cable and mounting the device as external storage.
Sqlite database
SQLite database:
 A lightweight SQL database implementation
that’s available across various platforms
(including Android, iPhone, Windows, Linux, and
Mac) and fully supported by Android.
 You can create tables and perform SQL queries
against the tables accordingly.
Sqlite database
SQLite is a opensource SQL database that
stores data to a text file on a device.
Android comes in with built in SQLite database
implementation.
SQLite supports all the relational database
features. In order to access this database, you
don't need to establish any kind of connections
for it like JDBC,ODBC e.t.c
Sqlite database
Sqlite database (Data types)
Sqlite database

Demo
Step One
• Create an HELPER class and override its methods
• A helper class to manage database creation and
version management.
• SQLiteOpenHelper class provides the functionality to use the
SQLite database.
• For performing any database operation, you have to provide the
implementation of onCreate() and onUpgrade() methods of
SQLiteOpenHelper class.
Step One
public class DatabaseHelper extends SQLiteOpenHelper {
public static final StringDATABASE ="users.db";
public static final StringTABLE_NAME ="students";
public DatabaseHelper(Context context) {
super(context,DATABASE , null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
}
Step Two
• Affect the onCreate() and onUpgrade() methods
Step Two
public class DatabaseHelper extends SQLiteOpenHelper {
public static final StringDATABASE ="users.db";
public static final StringTABLE_NAME ="students";
public DatabaseHelper(Context context) {
super(context,DATABASE , null, 1);
SQLiteDatabase db=this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+TABLE_NAME +"(Id INTEGER PRIMARY KEY AUTOINCREMENT,Name TEXT,EMAIL
TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME );
onCreate(db);
}
}
Step Three
• In the Main Activity, create an instance of the
Helper class to access the Helper class we have
created so far.
• Use the instance of the helper class to call the
constructor
• Once the constructor is called it is going to
create the database and the table.
Step Three

public class MainActivity extends AppCompatActivity {


DatabaseHelper dbhelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
dbhelper = new DatabaseHelper(this);
}
}
Step Four
• Create a layout to insert data to the table
Step Four
• Within the helper class we have created, create a method to insert
data to the table.

//Constants
public static final String DATABASE="users.db";
public static final String TABLE_NAME="students";
public static final String COL1="Id";
public static final String COL2="Name";
public static final String COL3="EMAIL";
Step Four
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME );
onCreate(db);
}
public boolean insertData(String name,String email){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues myContentValues=new ContentValues();
myContentValues.put(COL2 ,name);
myContentValues.put(COL3 ,email);
Long results=db.insert(TABLE_NAME ,null,myContentValues);
if(results==-1){
return false
}else{
return true;
}
}
}
Step Five
• Within the Main Class create a method to add data from the
layout and then use the instance of the Helper class to call the
method that insert data.
Step Five
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
dbhelper = new DatabaseHelper(this);
saveData=(Button) findViewById(R.id.btnSave );
name=(EditText) findViewById(R.id.etName );
email=(EditText) findViewById(R.id.etEMail );
addData();

}
Step Five
public void addData(){
saveData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted= dbhelper.insertData(name.getText().toString(),email.getText().
toString());
if(isInserted=true){
Toast.makeText (MainActivity.this, "Data addedd Successfully", Toast.LENGTH_SHORT ).
show();
}else{
Toast.makeText (MainActivity.this, "Data not Addedd", Toast.LENGTH_SHORT ).show();
}
}
});

}
END

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy