APP (1)
APP (1)
Course
Dr. Meftah ZOUAI
Associate Professor, University of Biskra
LINFI Laboratory, Computer science department,
Mohamed Khider University, 07000, Biskra, Algeria
[email protected]
https://www.youtube.com/meftahzouai
General Information
UE Title: UEF1
Subject Title: Mobile Applications (AppMob)
Credits: 5
Coefficients: 3
Number of weeks: 14 -16 weeks
Semester workload: 42 hours
Weekly workload: lecture (1:30) + practical work (1:30)
Evaluation method: Continuous assessment(40%)+Examination (60%)
Outline
1983 1994 1996 1999 2000 2004 2007 2013 2018 2023
Mobile operating system (OS)
1. User interface: The way the operating system presents information and allows users to interact with
their devices is important. Some operating systems have a more intuitive interface, while others offer
more customization options.
2. App store: The availability and selection of apps is a crucial factor for many users. Some operating
systems have a large and well-established app store, while others have a more limited selection.
3. Security: The security features and protection against malware and hacking are important for many
users. Some operating systems are known for having strong security features, while others may have
more vulnerabilities.
4. Hardware compatibility: Some operating systems work better on certain hardware configurations and
can take advantage of specific features, while others may be more limited.
5. Updates and support: The frequency and quality of updates and support provided by the operating
system's manufacturer is important for many users. Some operating systems are known for providing
regular and reliable updates, while others may have a more limited lifespan.
6. Performance and battery life: The performance and efficiency of the operating system can impact the
device's speed and battery life. Some operating systems are optimized for performance and battery life,
while others may be more resource-intensive.
Mobile operating system (OS)
1. Utility apps: These apps provide practical functions and features, such as calculators, converters, and
organizers.
2. Lifestyle apps: These apps are designed to help users improve their daily life and routines, such as
fitness and wellness apps, cooking apps, and travel apps.
3. Gaming apps: These apps offer interactive and engaging gaming experiences, including arcade,
puzzle, and strategy games.
4. Social media apps: These apps provide users with a platform to connect and communicate with
others, including social networks, messaging apps, and dating apps.
5. Education and learning apps: These apps offer educational content and resources, including
language learning apps, educational games, and e-books.
6. Productivity apps: These apps help users increase their productivity and efficiency, including task
management apps, note-taking apps, and project management apps.
7. Entertainment apps: These apps offer users access to movies, music, and other forms of
entertainment, including streaming services and virtual reality apps.
8. Business and finance apps: These apps help users manage their finances and work, including banking
apps, accounting apps, and invoicing apps.
Mobile apps Development
Mobile App Development refers to the process of creating software applications
for mobile devices such as smartphones and tablets. It involves designing, coding,
testing, and deploying mobile applications that are capable of running on multiple
platforms, including Android, iOS, and others.
Native Web
App App
Native app development
This involves building an app for a specific platform, such as iOS or Android, using the platform's
native programming language and development tools. Native apps provide the best
performance and user experience, but require separate development for each platform.
Advantages: Disadvantages
• Best performance and user experience
Separate development for each platform
Access to all native features of the platform
•
•
Higher development costs
Ability to use platform-specific design guidelines
•
•
Longer development time
Better security due to platform-specific app
•
•
Higher maintenance costs
stores
•
Hybrid app development
This involves using a combination of web technologies, such as HTML, CSS, and JavaScript,
to create an app that can run on multiple platforms. Hybrid apps offer cross-platform
compatibility, but may have limited access to native features and may not perform as well as
native apps.
Disadvantages
Advantages:
• Cross-platform compatibility • Limited access to native features
• Lower development costs • Reduced performance compared to native apps
• Faster development time • Inconsistent user experience across platforms
• Easy to maintain • Dependence on third-party libraries
Cross-platform app development
This involves using a single codebase and development tools to create an app that can run
on multiple platforms. Cross-platform app development can save time and resources, but may
require trade-offs in terms of performance and user experience.
Disadvantages
Advantages:
• Cross-platform compatibility • Reduced performance compared to native apps
• Lower development costs • Inconsistent user experience across platforms
• Faster development time • Dependence on third-party libraries
• Easy to maintain • Limited access to native features
Progressive Web App (PWA) development
This involves building a web-based app that provides a native-like experience, using web
technologies such as HTML, CSS, and JavaScript. PWAs can be accessed from any device with a
web browser and can be installed on the user's device like a native app.
Disadvantages:
Advantages:
• Cross-platform compatibility • Reduced performance compared to native apps
• Lower development costs • Limited access to native features
• Easy to maintain • Dependence on web technologies
• Available offline • Limited discoverability compared to native apps
Mobile App Development Platform
A Mobile App Development Platform (MADP) is a software platform that
allows developers to build and deploy mobile apps across multiple platforms
and devices. MADPs provide a set of tools and services that simplify the mobile
app development process, including the ability to create, test, and deploy
mobile apps without requiring extensive knowledge of programming languages.
• Target audience: Who is your app's target audience and what devices do they use? For example, if
your target audience is mainly iOS users, you may want to consider developing your app for iOS.
• Project scope: What features do you want to include in your app and what is your budget?
Depending on your project scope, some platforms may be more suitable than others.
• Development skills: What development skills do you have and what skills would you need to learn
to develop your app on a particular platform?
• Time to market: How quickly do you want to get your app to market? Some platforms offer faster
development times, while others offer more features and customization options.
• Revenue potential: How will you generate revenue from your app and what platform offers the
best revenue potential for your app?
• Maintenance and support: How much maintenance and support will your app require and what
platform offers the best support options?
• Market share: What platform has the largest market share and what platform offers the most
potential for growth?
• Device compatibility: Will your app be compatible with a variety of devices and operating systems
or will it be specific to one platform?
Chapiter II:
Android Platform
Android Platform
The Android Platform refers to the software environment on which Android applications run. It
includes the Android operating system, which provides a set of core services and APIs that are used by
applications to access device features, as well as the libraries and frameworks that developers use to build
Android applications.
The Android Platform is designed to be open and flexible, with a modular architecture that
allows for easy customization and integration with other software components. It includes a variety of
system-level features and services, including user interface elements, multimedia support, networking, and
security.
The Android Platform also includes the Android Runtime, which is responsible for executing
Android applications. The Android Runtime includes the Dalvik Virtual Machine (DVM), which executes
code written in the Java programming language, as well as the Android Native Development Kit (NDK),
which allows developers to write native code in C or C++.
Android OS architecture
The architecture of the Android operating system is designed to provide a
high-level of abstraction over the underlying hardware and support a wide range of
devices with different configurations. The Android architecture is composed of
several key components, including:
1. Linux Kernel
2. Native Libraries
3. Android Runtime
4. Application Framework
5. Applications
Linux Kernel
Linux Kernel: The Linux kernel provides the basic foundation for the Android
operating system, including hardware abstraction and management, process
management, memory management, and other system services.
Native Libraries
Native Libraries: The native libraries provide a set of APIs for accessing the
device's hardware, such as the camera, sensors, and network interfaces. The libraries
are implemented in C/C++ and are tightly integrated with the Linux kernel.
Android Runtime
Android Runtime: The Android runtime consists of two main components: the
Dalvik virtual machine and the Core Libraries. The Dalvik virtual machine is
responsible for executing the code written in Java and ensuring that each app runs in
its own sandboxed environment. The Core Libraries provide a comprehensive set of
APIs for developers to build their apps, including support for graphics, data storage,
and networking.
Application Framework
Application Framework: The Application Framework is a set of higher-level
APIs that developers use to build their apps. The framework provides a rich set of
services, such as Activity and Service management, Content Provider, and
Notification management. The framework also provides a set of tools for managing
the user interface, such as the View System, which provides a flexible and powerful
way to build and manage user interfaces.
Applications
Application layer: The top-level component of the Android architecture is the
set of apps that run on the device. These apps are built using the Application
Framework and the Core Libraries, and they provide a wide range of functionality,
including games, productivity tools, and social networking.
Android app compilation process
The Android operating system uses a unique and detailed compilation process to turn the source
code of an Android app into an executable package that can run on an Android device. The following
is a more detailed explanation of the Android compilation process
Android app compilation process
.java .java
Java Source code Java Source code
Java Java
Compiler Compiler
.class .class
Java Bytecode Java Bytecode
Dex
Compiler
.dex
Dalvik Bytecode
Java VM Dalvik VM
Android studio
Android Studio is an Integrated Development Environment (IDE) designed specifically for
developing Android applications. It was developed by Google and is based on the IntelliJ IDEA
platform. Some key features of Android Studio include:
1. Code editor: The code editor provides code completion, code highlighting, and error checking to
make coding easier.
2. Layout Editor: The layout editor provides a visual interface for designing the UI of an app.
3. Emulator: Android Studio includes an emulator that allows developers to test their apps on a virtual
device.
4. Debugging tools: Android Studio includes a set of debugging tools that allow developers to identify
and fix bugs in their code.
5. Gradle build system: Android Studio uses the Gradle build system to build, test, and deploy apps.
6. Plugins: Android Studio supports a wide range of plugins that can be used to extend the functionality
of the IDE.
7. Integrated Development Environment: Android Studio provides an integrated environment that
allows developers to write, test, and deploy Android apps without leaving the IDE.
Android SDK
SDK stands for Software Development Kit. It is a collection of software development tools in
one installable package. SDKs are used to develop applications for a specific platform, such as Android
or iOS. An Android SDK includes libraries, tools, sample code, and documentations required to
develop Android applications.
1. Android Emulator: A virtual device that runs on your computer to test your app.
2. Android SDK Tools: A set of tools including ADB (Android Debug Bridge), which allows you to
communicate with an emulator or device, and AAPT(Android Asset Packaging Tool), which packages
resources into an APK.
3. Android Platform-Tools: A set of tools that provide additional functionality for debugging and
uploading your app.
4. Android Support Library: A set of support libraries that help you build compatibility into your app.
5. Google APIs: A set of APIs that allow you to access Google services from your app.
6. Sample code and documentation: A set of sample code and documentation to help you get started
with developing Android applications.
Android Project
These are some of the important directories and files that are included in an Android project:
The manifest file is required for every Android app and serves as a sort of blueprint for
how the app will interact with the Android operating system. It must be located in the root of
the project's source folder, and it is automatically created when you create a new Android
project in Android Studio.
In summary, the manifest file is a crucial component of an Android app that outlines
the app's structure and defines how it interacts with the operating system.
Manifest file
Here is an example of an AndroidManifest.xml file for a simple app:
• app/src/main/java: This is the main source code folder for your project, where you write
your application code. It contains the MainActivity.java file, which is the entry point of your
application.
• app/src/androidTest/java: This is the folder where you write your Android instrumentation
tests. These are tests that are designed to run on an Android device or emulator.
• app/src/test/java: This is the folder where you write your unit tests. These tests are
designed to run on the JVM, without any Android dependencies.
These folders are organized based on the type of code you are writing and the type of tests
you are performing. By separating the code into different folders, it is easier to manage and
maintain your codebase.
Res folder
The res folder in an Android project contains all the resources used by the
application, such as layout files, images, strings, and more. Here are some
of the common types of resources you'll find in the res folder:
• layout: Contains the XML files that define the user interface of the app.
drawable: Contains images and other resources used in the app.
• values: Contains XML files that define various values used throughout
the app, such as strings, colors, and dimensions.
• anim: Contains XML files that define animations used in the app.
• menu: Contains XML files that define menus used in the app.
These are just a few examples of the resources you might find in the res
folder. The specific contents of this folder can vary depending on the
needs of your application.
Gradle scripts folder
Gradle is a build automation tool that is used to build and manage
Android projects. In the Android Studio project, there are several
Gradle scripts:
1.build.gradle (Project): This script applies to the entire project and is used to configure
build settings for all the modules in the project.
2.build.gradle (Module): This script applies to the specific module in the project and is
used to configure build settings for that module.
3.gradle.properties: This file contains the properties that configure the build system itself.
4.settings.gradle: This file is used to specify which modules to include in the project.
These Gradle scripts play a crucial role in building and managing Android projects. They
define the dependencies, plugins, and configurations needed to build the project.
Chapiter III:
2.Right-click on the app folder in the Project view, then select New -> Activity -> Empty
Activity.
3.In the dialog that appears, enter the name of the Activity in the Activity name field.
4.Choose the layout and menu options you want for the Activity.
After you create the Activity, you can add code to it in the Java file and create the layout in
the XML file.
Creating Activities
To create an Activity in Android Studio, follow these steps:
2.Right-click on the app folder in the Project view, then select New -> Activity -> Empty
Activity.
3.In the dialog that appears, enter the name of the Activity in the Activity name field.
4.Choose the layout and menu options you want for the Activity.
After you create the Activity, you can add code to it in the Java file and create the layout in
the XML file.
Activity Lifecycle
The Activity Lifecycle refers to the different states that an activity can be in at any given time while it's running. It's
important for Android developers to understand the Activity Lifecycle in order to manage the behavior of their app as it transitions
between different states.
Running
1. onCreate()
2. onStart() onPause()
3. onResume()
onResume()
Stopped Paused
onStop()
onDestory()
Destoryed
Activity Class Example
Managing multiple Activities
Managing multiple activities refers to how the app handles the different states of various activities in
the application, such as creating, pausing, resuming, and destroying. The app can navigate between different
activities using an intent, which starts a new activity and passes the control to the new activity.
To manage multiple activities, the app developer needs to use different methods provided by the
Android OS, such as startActivity(), finish(), and onActivityResult(), etc. The startActivity() method starts a new
activity, the finish() method is used to finish the current activity, and the onActivityResult() method is called
when the activity returns a result.
The application can keep track of the different states of each activity by implementing the Activity
class's various callback methods, which include onCreate(), onStart(), onResume(), onPause(), onStop(),
onRestart(), and onDestroy(). The app can use these methods to save the activity's state when it is paused or
destroyed and to restore it when it is resumed.
To manage multiple activities efficiently, the app developer needs to design the app in such a way that it uses
resources efficiently, such as memory and CPU usage, and minimizes the number of activities to reduce the
overhead of starting and stopping activities.
Managing multiple Activities
To manage multiple activities in an Android app, you can use the following
approaches:
Start an Activity: You can start a new activity by creating an Intent and
calling the startActivity() method. This will create a new instance of the activity and
add it to the top of the activity stack.
Finish an Activity: When you no longer need an activity, you can call the
finish() method to remove it from the activity stack.
Pass data between Activities: You can pass data between activities by
adding extras to the intent that starts the new activity, or by using a Bundle object.
Launch modes: You can use launch modes to control how new activities are
launched and how they interact with existing activities in the activity stack.
Back stack: You can manage the back stack of activities by setting flags on
the intent that starts the new activity, or by using the TaskStackBuilder class to
build an artificial back stack.
Definition of an Activity in the AndroidManifest.xml file.
In the AndroidManifest.xml file, the activity is defined as an <activity> tag that contains
information about the activity, such as its class name, the application label, icon, required
permission, intent filters, etc. This tag is placed in the root <application> element.
Here's an example of an <activity> tag in the AndroidManifest.xml file:
In this example, the activity is named "MainActivity" and is defined with a label and an icon. It
also requires the "ACCESS_FINE_LOCATION" permission. Additionally, the <intent-filter> tag specifies that
this activity is the main (launcher) activity of the application, which will be launched when the user clicks
on the application icon on the home screen.
Definition of an Activity in the AndroidManifest.xml file.
Here's an example of an Android application with a single activity that
displays the message "Hello" in a Toast:
In the MainActivity.java file, add the following code:
This is not an exhaustive list, but it covers some of the most commonly used resource
types in Android app development.
Resources
Here's an example of how you might use some of these resource types in an Android app:
You can then reference this string in your layout XML file or Java
code like this:
Resources
Colors: You can define a color resource in the "colors.xml" file in your
app's resources. For example:
You can then reference this color in your layout XML file or Java
code like this:
Resources
Access resources in Java code:
Strings: You can access a string resource in Java code using the getString()
method of the Resources class. For example:
Colors: You can access a color resource in Java code using the getColor()
method of the Resources class. For example:
Dimensions: You can access a dimension resource in Java code using the
getDimension() method of the Resources class. For example:
Resources
You can access an image resource in Java code using the
getDrawable() method of the Resources class. For example:
This will retrieve the image with the name "my_image" from the "drawable"
folder in your app's resources. Note that the getDrawable() method was
deprecated in API level 22. In newer versions of Android, you should use the
getDrawable() method of the ContextCompat class instead, like this:
This will retrieve the image with the name "my_image" from the "drawable"
folder in your app's resources, and the this parameter should be replaced
with a reference to your Activity or Context. Once you have the Drawable
object, you can use it to set the image of an ImageView or other UI element
in your app.
Resources
You can apply a style to a view or a group of views in Java code using
the setStyle() method of the View class. Here's an example:
This will apply the style with the name "MyTextStyle" to the
myTextView view. The style should be defined in your app's resources, in the
"styles.xml" file. Here's an example of a style definition:
Chapiter IV:
Similar to a relative layout but allows for Complex UI designs with elements that
Constraint Layout
more precise positioning of UI elements need to be constrained to one another
Component Description
Specifies the general type of operation that the Intent is requesting. For example,
Action
"ACTION_VIEW" is used to request that the system display data to the user.
Specifies the URI or data that the Intent should operate on. For example, a web
Data
URL for a browser Intent.
Provides additional information about the Intent's action or component. For
Category
example, "CATEGORY_BROWSABLE" for a browser Intent.
Specifies the explicit class name of the component that should handle the Intent.
Component
Used when you want to launch a specific component within your application.
Provides additional data to the component that receives the Intent, such as key-
Extras
value pairs of data.
Example: Intent Filters
Intent Filters: Action (1)
The Intent class defines a number of action constants, including these:
• Short for Multipurpose Internet Mail Extensions, a specification for formatting non-
ASCII messages so that they can be sent over the Internet. For Examples:
• For Text "text/plain"
• For Image :"image/jpeg“ , "image/bmp“ ,"image/gif“ , "image/jpg“ ,"image/png"
• For Video: "video/wav“, "video/mp4"
Intent Filters: Data (2)
Some examples of Action/Data Pair
The target activity can be safely invoked by the browser to display data referenced by a
CATEGORY_BROWSABLE
link — for example, an image or an e-mail message.
Set if the activity should be an option for the default action (center press) to perform
CATEGORY_DEFAULT
on a piece of data.
an activity on the top of stack, whenever application will start, the activity containing
CATEGORY_LAUNCHER
this category will be opened first..
Intent Filters: Extras
❑Flags defined in the Intent class that function as metadata for the
intent. The flags may instruct the Android system how to launch an
activity and how to treat it after it’s launched. (More than 33 Flags):
❑FLAG_ACTIVITY_CLEAR_TASK - Clear any existing tasks on this stack before starting the
activity.
❑FLAG_ACTIVITY_NEW_TASK - Start the activity in a new task or reuse an existing task tied to
that activity.
❑ With FLAG_ACTIVITY_NEW_TASK:
Intent Filters: <intent-filter> Manifest tag
• A single IntentFilter may include more than one <action>,<category> and <data>. In this case the
target component must be able to handle any or all combination of Intents.
• To allow several specific combinations of <action>, <category> and <data>, define multiple
IntentFilters.
• Each IntentFilter will be tested against an incoming Intent to satisfy the <action>, <category> and
<data> tests. The Intent will be delivered to the component only if it can pass all the tests for at least
one IntentFilter.
• In order to receive implicit intents, you must include the CATEGORY_DEFAULT category in the intent
filter
<activity android:name="TestActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
Intent Filters: User Permissions
• The activities are arranged in a stack, called task, in the order in which each
activity is opened.
• When the current activity starts another, the new activity is pushed on the top
of the stack and takes focus. The previous activity remains in the stack, but is
stopped.
Activity Stack
Open WebPage
Intent
Start Activity
Broadcast
Implicit Intents
Implicit Intents: These Intents are used to request that the system
perform a specific action, such as viewing a web page, taking a photo, or
playing a video. With an implicit Intent, you specify the action that you want
to perform (using the Action property), along with any additional data or
categories that are required. The system then searches for a suitable
component that can handle the Intent. For example, you might use an
implicit Intent to open a web page:
Can you direct me to someone, who can help me setup the home
Internet, and I am using cable connection, living in EL ALIA , Biskra
Implicit Intents: Example
Activity 1 Activity 2
Intent
Activity 1 Activity 2
Intent
setData(Uri data) Sets the data for the Intent, specifying the data that should be acted upon.
setType(String type) Sets the MIME type for the Intent, specifying the type of data that is being passed.
setComponent(ComponentName
Sets the component for the Intent, specifying the name of the component that should be started.
component)
addCategory(String category) Adds a category to the Intent, specifying additional information about the action to be performed.
For example, applications can register for the ACTION_BOOT_COMPLETED system event which is fired once the
Android system has completed the boot process.
Android
System Broadcast
Recevier App
System broadcast
broadcast
Broadcast Receivers Process
BroadcastReceivers
When Events occur they
register to receive Those Intents are then
are represented as
events in which they broadcast to the system
Intents
are interested
Shared Content
Preferences File Storage Cloud Storage Database
Providers
Used to store
Used to sore Used to store
Used to store raw third party data Used to store
semi-structured
the data in Key files on memory
data with user
storage , that private data for
Value paire card or SD-card involves Parse API the app here the
configurable data
Google…firebase structured data
access
External file storage ….
SQL (SQLite)
@Override
public void onCreate(SQLiteDatabase db) {
// Create database tables using SQL queries
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Update the database structure when the version changes
}
}
SQLite Database Adapter: SQLiteOpenHelper
2. In your code, create an instance of your SQLiteOpenHelper class:
MyDatabaseHelper dbHelper = new MyDatabaseHelper(context);
2. Use ContentValues
ContentValues values = new ContentValues();
public long insert(String table, String nullColumnHack, contentValues.put("name", "Lucy");
ContentValues values) contentValues.put("amout", 4000); long id =
db.insert("account", null, values); db.close();
SQLite Data Manipulation: Query or select
NB: you couldn't use execSQL() to query data. Because execSQL() method has no return value.
Alternatively, you can use rawQuery() or query() method of SQLiteDatabase class to select and query data.
1. rawQuery()
public android.database.Cursor rawQuery(String sql, String[] selectionArgs)
Cursor cursor = db.rawQuery("SELECT name, amount FROM accounts
WHERE name = ?", new String[]{"Lucy"});
2. query() Using of Cursor: traverse query results
public Cursor query(String table, String[] columns, String while(cursor.moveToNext()) {
selection, String[] selectionArgs, String groupBy, String having, String name =
String orderBy, String limit) cursor.getString(cursor.getColumnIndex("name"));
float amount =
Cursor cursor = db.query("accounts", null, null, null, null, null,
cursor.getFloat(cursor.getColumnIndex("amount")
"amount DESC", "3");
);
buffer.append(name + ", " + amount + "\n"); }
db.close();
SQLite Data Manipulation: Traverse query results
Method Description
moveToFirst() Moves the cursor to the first row of the result set.
moveToLast() Moves the cursor to the last row of the result set.
moveToNext() Moves the cursor to the next row in the result set.
moveToPrevious() Moves the cursor to the previous row in the result set.
Moves the cursor to the specified position in the result
moveToPosition(int)
set.
SQLite Data Manipulation: Traverse query results
Method Description
moveToFirst() Moves the cursor to the first row of the result set.
moveToLast() Moves the cursor to the last row of the result set.
moveToNext() Moves the cursor to the next row in the result set.
moveToPrevious() Moves the cursor to the previous row in the result set.
moveToPosition(int) Moves the cursor to the specified position in the result set.
getCount() Returns the number of rows in the result set.
getColumnName(int) Returns the name of the column at the specified index.
getFloat(int) Retrieves the value of the specified column as a float.
getInt(int) Retrieves the value of the specified column as an integer.
getString(int) Retrieves the value of the specified column as a string.
isFirst() Checks if the cursor is pointing to the first row in the result set.
isLast() Checks if the cursor is pointing to the last row in the result set.
isBeforeFirst() Checks if the cursor is positioned before the first row.
isAfterLast() Checks if the cursor is positioned after the last row.
SQLite Data Manipulation: Update & Delete
1. update
public int update(String table, ContentValues values, String whereClause, String[] whereArgs)
2. delete
public int delete(String table, String whereClause, String[] whereArgs)
private MyContract() {}
}
Data Manipulation: Create a Content Provier
2. Create a Database Helper: Create a subclass of SQLiteOpenHelper to manage database
creation and version management. Override the onCreate() and onUpgrade() methods as
per your requirements.
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "my_database.db";
private static final int DATABASE_VERSION = 1;
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + MyContract.MyTable.TABLE_NAME + " (" + MyContract.MyTable.COLUMN_ID + "
INTEGER PRIMARY KEY, " + MyContract.MyTable.COLUMN_NAME + " TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Implement upgrade logic if needed
}
}
Data Manipulation: Create a Content Provier
3. Implement Content Provider: Create a subclass of ContentProvider to define the
content provider for your database. Override the necessary methods like onCreate(),
query(), insert(), update(), delete(), etc.
public class MyContentProvider extends ContentProvider { @Nullable
private MyDatabaseHelper databaseHelper; @Override
public Cursor query(@NonNull Uri uri, @Nullable String[]
@Override projection, @Nullable String selection, @Nullable String[]
public boolean onCreate() { selectionArgs, @Nullable String sortOrder)
databaseHelper = new MyDatabaseHelper(getContext()); {
return true; SQLiteDatabase db = databaseHelper.getReadableDatabase();
} Cursor cursor = db.query(MyContract.MyTable.TABLE_NAME,
projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(),
uri);
return cursor;
}
Data Manipulation: Create a Content Provier
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
long id = db.insert(MyContract.MyTable.TABLE_NAME, null, values);
if (id != -1) {
getContext().getContentResolver().notifyChange(uri, null);
return ContentUris.withAppendedId(uri, id);
}
return null;
}
// Implement other methods like update(), delete(), etc., based on your
requirements
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null; // Modify as per your requirements
}}
Data Manipulation: Create a Content Provier
4. Declare Content Provider in Manifest: Add the necessary entries to your app's manifest
file to declare the content provider.
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application ...>
...
<provider
android:name=".MyContentProvider"
android:authorities="com.example.myapp.provider"
android:exported="false" />
...
</application>
</manifest>
Using the sqlite3 Command-Line
• Start a virtual device (emulator) and launch the ADB shell
to connect to the database from a command prompt.
C:>adb devices
List of devices attached
emulator-5554 device
Services
Introduction(1)
A service is typically designed to run in the background, without a
visible user interface, and it can be implemented as a daemon or a thread.
The concept of a singleton is often used to ensure that there is only one
active instance of the service at any given time. This allows for resource
sharing and coordination of access to the service's functionalities.
Foreground services are typically used for operations that have high
importance, such as playing music, performing location tracking, or managing
ongoing downloads. By running as a foreground service, the app indicates to the
user that there is an ongoing operation that they should be aware of.
Foreground Service
Key characteristics of foreground services in Android include:
Characteristic Description
Foreground services display a persistent notification in the notification
Persistent Notification
bar to inform the user about the ongoing operation.
Background services are typically used for operations that do not need
immediate user attention but are necessary for the overall functionality of the
app. Examples include data synchronization, network requests, periodic
updates, or any task that requires continuous or periodic execution.
The Android system manages the lifecycle of background services, allowing them to be started and
Lifecycle Management
stopped by other components.
Background services should be mindful of system resources, such as CPU and battery usage, to optimize
Limited System Resources
performance.
Background services do not require continuous user interaction and focus on performing tasks in the
No User Attention
background.
Background services are typically designed for sequential execution and may not be suitable for parallel
Not Intended for Parallelism
tasks.
Background services support continuous or periodic operations that persist even when the app is not in
Ongoing Operations
the foreground.
Bound Service
A bound service in Android is a type of service that
allows components, such as activities or other services, to
bind to it and interact with it through an interface defined
by the service. It establishes a client-server relationship
between the service and the component binding to it.
Bound Service
Characteristic Description
Components can bind to a bound service using bindService() method, establishing a
Binding
client-server relationship with the service.
Bound services define an interface (typically implemented as an IBinder) for clients to
Interface
interact with the service.
Bound services' lifecycle is dependent on the components bound to it. The service is
Lifecycle
typically destroyed when all clients unbind.
Local or Remote Bound services can be bound either locally within the same process or remotely across
Binding different processes using inter-process communication (IPC).
Bound services facilitate data sharing between the service and its clients, allowing
Data Sharing
clients to access and modify shared data.
Bound services are typically used when the service's lifespan is tied to the lifespan of its
Contextual Lifetime
bound component(s).
Service Example: (1)
@Override
public class MyService extends Service { public void onDestroy() {
super.onDestroy();
private static final int NOTIFICATION_ID = 1; // Cleanup or release any resources here...
private static final String CHANNEL_ID = "ForegroundServiceChannel"; }
@Override @Nullable
public void onCreate() { @Override
super.onCreate(); public IBinder onBind(Intent intent) {
} return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { private void createNotificationChannel() {
// Perform your long-running task or operations here...
} }
}
Service Example: (2)
Make sure to declare the service in the AndroidManifest.xml file:
<service
android:name=". MyService "
android:enabled="true"
android:exported="false" />
To start the foreground service, you can use the following code in your activity: