Académique Documents
Professionnel Documents
Culture Documents
Notes
It is open-source.
Anyone can customize the Android Platform.
There are a lot of mobile applications that can be chosen by the consumer.
2. Android Architecture
Android is structured in the form of a software stack comprising applications, an operating system,
run-time environment, middleware, services and libraries.
When an Android app is built within Android Studio it is compiled into an intermediate bytecode
format (referred to as DEX format). When the application is subsequently loaded onto the device,
the Android Runtime (ART) uses a process referred to as Ahead-of-Time (AOT) compilation to
translate the bytecode down to the native instructions required by the device processor. This
format is known as Executable and Linkable Format (ELF).
2.2 C/C++ Libraries
The Android runtime core libraries outlined in the preceding section are Java-based and provide
the primary APIs for developers writing Android applications. It is important to note, however, that
the core libraries do not perform much of the actual work and are, in fact, essentially Java
“wrappers” around a set of C/C++ based libraries. When making calls, for example, to the
android.opengl library to draw 3D graphics on the device display, the library actually ultimately
makes calls to the OpenGL ES C++ library which, in turn, works with the underlying Linux kernel to
perform the drawing tasks.
2.4 Applications
Located at the top of the Android software stack are the applications. These comprise both the
native applications provided with the particular Android implementation (for example web
browser and email applications) and the third-party applications installed by the user after
purchasing the device.
Table of Contents
The Android project view shows all the build files at the top level of the project hierarchy
under Gradle Scripts. Each project module appears as a folder at the top level of the project
hierarchy and contains these three elements at the top level:
Here is the brief description of important files/folders in the Android project structure:
It is responsible to protect the application to access any protected parts by providing the
permissions
It also declares the android api that the application is going to use
It lists the instrumentation classes. The instrumentation classes provide profiling and other
information. These information are removed just before the application is published etc.
3.3 Java
The java folder contains the Java source code files of the application organized into packages. We
can have more than one package in the Android application. It’s always a good practice to break
the source code of the application into different packages based on its core functionality. All the
source files of the Activities, Services etc. go into this folder.
3.4 Res
Res folder is where all the external resources for the application such as images, layout XML files,
strings, animations, audio files etc. are stored.
Sub folders:
Drawable: This folder contains the bitmap file to be used in the program. There are different
folders to store drawables. They are drawable-ldpi, drawable-mdpi, drawable-
hdpi,drawable-xdpi etc. The folders are to provide alternative image resources to specific
screen configurations. Ldpi, mdpi & hdpi stands for low density, medium density & high
density screens respectively. The resources for each screen resolutions are stored in
respective folders and the android system will choose it according to the pixel density of the
device
Layout: It contains XML files that define the User Interface of the application
Menu: XML files that define menus for the application goes into this folder
Mipmap: The mipmap folders is used for placing the app icons only. Any other drawable
assets should be placed in the relevant drawable folders as before.
Values : XML files that define simple values such as strings, arrays, integers, dimensions,
colors, styles etc. are placed in this folder
3.7 Idea
Eclipse uses project.properties file for project specific metadata. Here in Android Studio, this .idea
does the same thing. This means the project specific metadata is stored by Android Studio.
Build : This has all the complete output of the make process i.e. classes.dex, compiled
classes and resources, etc. In the Android Studio GUI, only a few folders are shown. The
important part is that the R.java is found here under build/generated/source/r/…/R.java
Libs : This is a commonly seen folder in eclipse and android studio, which optionally can
hold the libraries or .jar files
Src : The src folder can have both application code and android unit test script. You will find
two folders named “androidTest” and “main” correspond to src folder. The main folder
contains two subfolders java and res. The java folder contains all the java codes and res
contains drawables, layouts etc.
3.9 Gradle
This is where the gradle build systems jar wrapper is found. This jar is how Android Studio
communicates with gradle installed in Windows/MAC.
3.13 DEX
Dalvik Virtual Machine is an Android Virtual Machine optimized for mobile devices. It optimizes the
virtual machine for memory, battery life and performance. The Dex compiler converts the class
files into the .dex file that run on the Dalvik Virtual Machine. The Multiple class files are converted
into one dex file. Following flow depicts compiling and packaging process from the source file:
The javac tool compiles the java source file into the class file.
The dx tool takes all the class files of the application and generates a single .dex file. It is a
platform-specific tool.
The Android Assets Packaging Tool (aapt) handles the packaging process.
3.14 Android ProGuard
The ProGuard tool shrinks, optimizes, and obfuscates the code by removing unused code and
renaming classes, fields, and methods with semantically obscure names. The result is a smaller
sized .apk file that is more difficult to reverse engineer.
4. AVD Creation
To launch the AVD Manager:
In Android Studio, select Tools > Android > AVD Manager, or click on the AVD Manager
icon in the toolbar.
The AVD Manager screen shows your current virtual devices.
Click the Create Virtual Device button then click Next.
Select the desired system version for the AVD adn click Next.
Choose a Release Name, must be Android 4.0.3 or higher, from the table and click Next.
Type in an Name for your emulator in the text box next to AVD Name.
Ensure Use Host GPU is checked and click Finish
In principle, one way to transfer files is to use Android Studio. With a device connected by USB,
open the DDMS: Tools > Android > Android Device Monitor. Select the device in the Devices panel
and then select the File Explorer tab in the right panel.
Activities
Services
Broadcast receivers
Content providers
Method Description
onResume called when activity will start interacting with the user.
Link to refer :
https://developer.android.com/guide/components/activities/activity-lifecycle
9. Toast Message in Android
Andorid Toast can be used to display information for the short period of time. A toast contains
message to be displayed quickly and disappears after sometime.
You can also create custom toast as well for example toast displaying image. You can visit next
page to see the code for custom toast.
9.2Toast class
Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.
There are only 2 constants of Toast class which are given below.
Constant Description
public static final int LENGTH_LONG displays view for the long duration of time.
public static final int LENGTH_SHORT displays view for the short duration of time.
public static Toast makeText(Context context, makes the toast containing text
CharSequence text, int duration) and duration.
public void setMargin (float horizontalMargin, float changes the horizontal and
verticalMargin) vertical margin difference.
Toast.makeText(getApplicationContext(),"Hello
Kavita",Toast.LENGTH_SHORT).show();
Another code:
10. UI Components
Following are the commonly used UI or input controls in android applications.
TextView
EditText
AutoCompleteTextView
Button
ImageButton
ToggleButton
CheckBox
RadioButton
RadioGroup
ProgressBar
Spinner
TimePicker
DatePicker
SeekBar
AlertDialog
Switch
RatingBar
Following are the call-back methods which included in event listener interface.
Method Description
onClick() This method is called when the user touches or focus on the item
using navigation-keys or trackball or presses on "enter" key or
presses down on the trackball.
onLongClick() This method is called when the user touches and holds the item or
focuses on the item using navigation-keys or trackball and presses
and holds "enter" key or presses and holds down on the trackball
(for one second).
onFocusChange() This method is called when the user navigates onto or away from
the item, using the navigation-keys or trackball.
onKey() This method is called when the user is focused on the item and
presses or releases a hardware key on the device.
onTouch() This method is called when the user performs a touch event,
including a press, a release, or any movement gesture on the screen.
Explicit Android Intent is the Intent in which you explicitly define the component that needs to be
called by Android System. When you open an activity from another activity in the same Android
app, you use Explicit Intents.
2. action
the
The
Whenever
Implicit
This
over is typically
OS
email,
Android
you
youdecides
want
used
sms,
delegate
Intents
to
when
social
perform.
iswhich
responsibility
the
Implicit
youintent
want
network
The
component
to
where
decision
share
toetc.
instead
another
the
to is
handle
is
data
ofapplication
abest
defining
from
this
classic
Android
1action
to
application
the
from
example
run
is
exact
left
your
to
for
components,
the
another.
application,
of implicit
operating
thisSharing
you
category.
you
Intents.
system.
intents.
Intent
define
data
use
Link To Refer : https://developer.android.com/reference/android/content/Intent
14. Adapter
Android adapters are the bridges between the core data source and the android UI views like
ListView, GridView or Spinner.
Here data source is the source from where we get the data and UI components are list or grid items
in which we want to display that data.
14.1 Types of adapter
There are the some commonly used Adapter in Android used to fill the data in the UI components.
Android fragment lifecycle is affected by activity lifecycle because fragments are included in
activity.
Each fragment has its own life cycle methods that is affected by activity life cycle because
fragments are embedded in activity.
The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods for
fragment.
15.2 Android Fragment Lifecycle Methods
An intent filter is an instance of the IntentFilter class. However, since the Android system must
know about the capabilities of a component before it can launch that component, intent filters are
generally not set up in Java code, but in the application's manifest file (AndroidManifest.xml)
as <intent-filter> elements. (The one exception would be filters for broadcast receivers that are
registered dynamically by calling Context.registerReceiver(); they are directly created as IntentFilter
objects.)
A filter has fields that parallel the action, data, and category fields of an Intent object. An implicit
intent is tested against the filter in all three areas. To be delivered to the component that owns the
filter, it must pass all three tests. If it fails even one of them, the Android system won't deliver it to
the component — at least not on the basis of that filter. However, since a component can have
multiple intent filters, an intent that does not pass through one of a component's filters might
make it through on another.
There are following two important steps to make Broadcast Receiver works for the system
broadcasted intents −
There is one additional steps in case you are going to implement your custom intents then you
will have to create and broadcast those intents.
17.1 Creating the Broadcast Receiver
A broadcast receiver is implemented as a subclass of Broadcast Receiver class and overriding the
onReceive() method where each message is received as a Intent object parameter.
BROADCAST-RECEIVER
18. Services
A service is a component that runs in the background to perform long-running operations without
needing to interact with the user and it works even if application is destroyed.
1 Started
A service has life cycle callback methods that you can implement to monitor changes in the
service's state and you can perform work at the appropriate stage. The following diagram on the
left shows the life cycle when the service is created with startService() and the diagram on the
right shows the life cycle when the service is created with bindService()
To create an service, you create a Java class that extends the Service base class or one of its
existing subclasses. The Service base class defines various callback methods and the most
important are given below. You don't need to implement all the callbacks methods. However, it's
important that you understand each one and implement those that ensure your app behaves the
way users expect.
1 onStartCommand()
The system calls this method when another component, such as an activity, requests
that the service be started, by calling startService(). If you implement this method, it is
your responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.
2 onBind()
The system calls this method when another component wants to bind with the service
by calling bindService(). If you implement this method, you must provide an interface
that clients use to communicate with the service, by returning an IBinder object. You
must always implement this method, but if you don't want to allow binding, then you
should return null.
3 onUnbind()
The system calls this method when all clients have disconnected from a particular
interface published by the service.
4 onRebind()
The system calls this method when new clients have connected to the service, after it
had previously been notified that all had disconnected in its onUnbind(Intent).
5 onCreate()
The system calls this method when the service is first created
using onStartCommand() or onBind(). This call is required to perform one-time set-up.
6 onDestroy()
The system calls 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, receivers, etc.
You can also extend the Intent Service class for your service implementation.
The Intent Service is used to perform a certain task in the background. Once done, the instance
of Intent Service terminates itself automatically. An example for its usage would be downloading
certain resources from the internet.
The Intent Service class offers the onHandleIntent() method which will be asynchronously called
by the Android system.
Android application runs on a single thread when launched. Due to this single thread model tasks
that take longer time to fetch the response can make the application non-responsive. To avoid this
we use android AsyncTask to perform the heavy tasks in background on a dedicated thread and
passing the results back to the UI thread. Hence use of AsyncTask in android application keeps the
UI thread responsive at all times.
The basic methods used in an android AsyncTask class are defined below :
Params : The type of the parameters sent to the task upon execution
Progress : The type of the progress units published during the background computation
Result : The type of the result of the background computation
myTask.execute();
In the above snippet we’ve used a sample classname that extends AsyncTask and execute method
is used to start the background thread.
Note:
MultiThreading and task running are old subjects. Java itself has java.util.concurrent package
and Fork/Join framework to facilitate it. Several libraries have been written to streamline
asynchronous operations. RxJava is the most popular library today for reactive programming
Looper, Handler, and Handler Thread are the Android’s way of solving the problems of
asynchronous programming.
Use Cases:
1. The main thread in Android is built with a Looper and Handlers. So, the understanding of
2. The developers writing libraries cannot afford to use third party libraries because of the
library size. So, for them, the best option is to utilize the existing available resource.
Writing own solution for it may not always get that level of efficiency and optimization.
3. The same argument can also be made for companies/individuals shipping out SDKs. The
clients can have varied implementations, but all of them will share the common android
framework APIs.
4. Understanding them fully will enhance the capacity to follow the Android SDK and
Java threads are one-time use only and die after executing its run method.
Can we improve upon it?
The Thread is a double-edged sword. We can speed up the execution by distributing the tasks
among threads of execution, but can also slow it down when threads are in excess. Thread
creation in itself is an overhead. So, the best option is to have an optimum number of threads
2. The task is executed serially by that thread and is maintained in a queue (Message
Queue).
The above model is implemented in the Android via Looper, Handler, and HandlerThread. The
1. Message Queue is a queue that has tasks called messages which should be processed.
2. Handler enqueues task in the Message Queue using Looper and also executes them when the
3. Looper is a worker that keeps a thread alive, loops through Message Queue and sends
a Looperand MessageQueue object and associate the thread with them in Thread Local storage
class. Looper.loop() must be called to start the associated looper. Similarly, the looper must be
Looper.loop();
}
}
A Handler gets implicitly associated with the thread that instantiates it via thread’s Looper, but
we can explicitly tie it to a thread by passing the thread’s looper in the constructor of
the Handler.
1. Message: It is a class that defines various useful methods to deal with message data. To
here:https://developer.android.com/reference/android/os/Message.html
2. Runnable: A runnable can also be posted in the MessageQueue. Ex: posting and running a task
In the above example, we create a Handler and provide Looper associated with the main thread.
This associate this handler to the main thread. When we post the Runnable, it gets queued in the
Handler is capable of message manipulation in a wide variety of ways, which can found
here: https://developer.android.com/reference/android/os/Handler.html
Creating an own thread and providing Lopper and MessageQueue is not the right way to deal
with the problem. So, Android has provided HandlerThread(subclass of Thread) to streamline the
process. Internally it does the same things that we have done but in a robust way. So, always
use HandlerThread.
One of the ways to create the HandlerThread is to subclass it and most of the time you will be
Handler handler;
@Override
protected void onLooperPrepared() {
handler = new Handler(getLooper()) {
@Override
public void handleMessage(Message msg) {
// process incoming messages here
// this will run in non-ui/background thread
}
};
}
}
Note: We have instantiated the Handler when the onLooperPrepared() is called. So,
1. Looper is only prepared after HandlerThread’s start() is called i.e. after the thread is
running.
2. A Handler can be associated with a HandlerThread, only after it’s Looperis prepared.
Android stores Shared Preferences settings as XML file in shared_prefs folder under
DATA/data/{application package} directory. The DATA folder can be obtained by
calling Environment.getDataDirectory().
SharedPreferences is application specific, i.e. the data is lost on performing one of the following
options:
As the name suggests, the primary purpose is to store user-specified configuration details, such as
user specific settings, keeping the user logged into the application.
MODE_PRIVATE: the default mode, where the created file can only be accessed by the
calling application
MODE_WORLD_READABLE: Creating world-readable files is very dangerous, and likely to
cause security holes in applications
MODE_WORLD_WRITEABLE: Creating world-writable files is very dangerous, and likely to
cause security holes in applications
MODE_MULTI_PROCESS: This method will check for modification of preferences even if the
Shared Preference instance has already been loaded
MODE_APPEND: This will append the new preferences with the already existing preferences
MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would
enable write ahead logging by default
Android AlertDialog is one of the most important and basic component in Android applications.
Alert dialog box is used to show alerts to the users, get confirmation from the users. In order to
make an alert dialog, we need to make an object of AlertDialogBuilder which is an inner class
of AlertDialog. Its syntax is given below.
1. setIcon(Drawable icon): This method set the icon of the alert dialog box
2. setCancelable(boolean cancelable): This method sets the property that the dialog can be
cancelled or not
3. setMessage(CharSequence message): This method sets the message to be displayed in the
alert dialog
4. setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems,
DialogInterface.OnMultiChoiceClickListener listener): This method sets list of items to be
displayed in the dialog as the content. The selected option will be notified by the listener
5. setOnCancelListener(DialogInterface.OnCancelListener onCancelListener): This method
Sets the callback that will be called if the dialog is cancelled
6. setTitle(CharSequence title): This method set the title to be appear in the dialog
7. getListView(): This function is used to get the list view used in the dialog
After creating and setting the dialog builder, we need to create an alert dialog by calling
the create() method of the builder class. Its syntax is shown below.
alertDialog.show();
It is embedded in android by default. So, there is no need to perform any database setup or
administration task.
Constructor Description
There are many methods in SQLiteOpenHelper class. Some of them are as follows:
Method Description
public abstract void onCreate(SQLiteDatabase db) called only once when database is
created for the first time.
There are many methods in SQLiteDatabase class. Some of them are as follows:
Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String inserts a record on the database. The table specifies the
nullColumnHack, ContentValues table name, nullColumnHack doesn't allow completely null
values) values. If second argument is null, android will store null
values if values are empty. The third argument specifies
the values to be stored.
int update(String table, updates a row.
ContentValues values, String
whereClause, String[] whereArgs)