Vous êtes sur la page 1sur 35

ANDROID

Notes

JULY 14, 2019


KAVITA DHOKADE
Contents
1. What is Android .............................................................................................................................. 3
1.1 Features of Android ................................................................................................................ 3
2. Android Architecture ...................................................................................................................... 3
2.1 The Linux Kernel ...................................................................................................................... 3
2.2 C/C++ Libraries ........................................................................................................................ 4
2.3 Application Framework ........................................................................................................... 4
2.4 Applications............................................................................................................................. 5
3. Android Project Structure in Android Studio .................................................................................. 5
3.1 Android Project View .............................................................................................................. 6
3.2 Android Manifest File.............................................................................................................. 6
3.3 Java.......................................................................................................................................... 7
3.4 Res ........................................................................................................................................... 7
3.5 Gradle Scripts .......................................................................................................................... 7
3.6 The Project View ..................................................................................................................... 8
3.7 Idea ......................................................................................................................................... 8
3.8 Project Module(app) ............................................................................................................... 8
3.9 Gradle ...................................................................................................................................... 9
3.10 External Libraries .................................................................................................................... 9
3.11 What is R.java? ........................................................................................................................ 9
3.12 Android Compilers .................................................................................................................. 9
3.13 DEX .......................................................................................................................................... 9
3.14 Android ProGuard ................................................................................................................. 10
4. AVD Creation ................................................................................................................................. 10
5. Debug Android App....................................................................................................................... 10
5.1 Device File Explorer............................................................................................................... 10
6. Android Basic Components ........................................................................................................... 10
7. Activity and its Life cycle ............................................................................................................... 11
8. Android Activity Lifecycle methods .............................................................................................. 11
9. Toast Message in Android............................................................................................................. 12
9.1Android Toast Example ................................................................................................................ 12
9.2Toast class .................................................................................................................................... 12
10. UI Components ......................................................................................................................... 13
11. Android Event Listeners ............................................................................................................ 14
12. Android Intent ........................................................................................................................... 15
12.1 Types of intent: ..................................................................................................................... 15
13. Android Bundle ......................................................................................................................... 15
14. Adapter ..................................................................................................................................... 15
14.1 Types of adapter ................................................................................................................... 16
15. Fragment and its Lifecycle ........................................................................................................ 16
15.1 Android Fragment Lifecycle .................................................................................................. 16
15.2 Android Fragment Lifecycle Methods ................................................................................... 18
16. Intent Filter ............................................................................................................................... 19
17. Broadcast Receiver.................................................................................................................... 19
17.1 Creating the Broadcast Receiver........................................................................................... 20
17.2 Registering Broadcast Receiver............................................................................................. 20
18. Services ..................................................................................................................................... 20
19. Intent Services........................................................................................................................... 23
20. Android AsyncTask .................................................................................................................... 23
20.1 Android AsyncTask Example ................................................................................................. 24
20.2 Android Core: Looper, Handler, and HandlerThread ............................................................ 24
21. Android Shared Preferences ..................................................................................................... 30
22. Android AlertDialog .................................................................................................................. 31
22.1 Android AlertDialog Components ......................................................................................... 31
22.2 AlertDialog Functions ............................................................................................................ 31
23. Android SQLite .......................................................................................................................... 32
24. SQLiteOpenHelper class ............................................................................................................ 32
24.1 Constructors of SQLiteOpenHelper class .............................................................................. 32
24.2 Methods of SQLiteOpenHelper class .................................................................................... 33
25. SQLiteDatabase class ................................................................................................................ 33
25.1 Methods of SQLiteDatabase class......................................................................................... 33
1. What is Android

 Android is a mobile operating system developed by Google.


 It is based on the Linux kernel and other open source software, and is designed primarily
for touchscreen
 mobile devices such as smartphones and tablets.
 In addition, Google has further developed Android TV for televisions, Android Auto for
cars,
 and Wear OS for wrist watches, each with a specialized user interface.
 It is developed by Google and later the OHA (Open Handset Alliance). Java language is
mainly used to write
 the android code even though other languages can be used.

1.1 Features of Android


After learning what is android, let's see the features of android. The important features of android
are given below:

 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.

2.1 The Linux Kernel


Positioned at the bottom of the Android software stack, the Linux Kernel provides a level of
abstraction between the device hardware and the upper layers of the Android software stack.
Based on Linux version 2.6, the kernel provides pre-emptive multitasking, low-level core system
services such as memory, process and power management in addition to providing a network stack
and device drivers for hardware such as the device display, Wi-Fi and audio.

Android Runtime – ART

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.3 Application Framework


The Application Framework is a set of services that collectively form the environment in which
Android applications run and are managed. This framework implements the concept that Android
applications are constructed from reusable, interchangeable and replaceable components. This
concept is taken a step further in that an application is also able to publish its capabilities along
with any corresponding data so that they can be found and reused by other applications.

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.

3. Android Project Structure in Android Studio


When we start a new Android project in Android Studio, it will automatically create a lot of files
and folders for us. Let’s look at their functions and meaning. A New Project automatically opens in
the Android Project View.

Table of Contents

Sr. Table content


No
1 Android Project View
2 Android Manifest File
3 Java
4 Res
5 Gradle Scripts
6 The Project View
7 Idea
8 Project Module(app)
9 Gradle
10 External Libraries
11 What is R.java?
12 Android Compilers
13 DEX
14 Android ProGuard
3.1 Android Project View

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:

 java/ : Source files for the module.


 manifests/ : Manifest files for the module
 res/ : Resource files for the module

Here is the brief description of important files/folders in the Android project structure:

3.2 Android Manifest File


AndroidManifest.xml is one of the most important file in the Android project structure. It contains
information of the package, including components of the application such as activities, services,
broadcast receivers, content providers etc.
It performs the following tasks:

 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.5 Gradle Scripts


Gradle scripts are used to automate tasks. For the most part, Android Studio performs application
builds in the background without any intervention from the developer. This build process is
handled using the Gradle system, an automated build toolkit designed to allow the ways in which
projects are built to be configured and managed through a set of build configuration files. It uses
a language called groovy.
3.6 The Project View

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.

3.8 Project Module(app)


This is the actual project folder where the application code resides. The application folder has
following sub directories

 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.10 External Libraries


This is not actually a folder but a place where Referenced Libraries and information on targeted
platform SDK are shown.

3.11 What is R.java?


Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains
resource IDs for all the resources of res/ directory.
On creating any component in the activity_main.xml file, id for the corresponding component is
automatically created in this file. This id can be used in the activity source file to perform any action
on the component.

3.12 Android Compilers


The compilers convert compiled .class files to executable .dex files in the Dalvik format for further
execution in the Android environment. Following are the two important tools used:

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

Link To Refer : https://developers.arcgis.com/android/10-2/sample-code/emulator/

5. Debug Android App

Link To Refer : https://www.strv.com/blog/debugging-in-android-studio-as

5.1 Device File Explorer

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.

Link To Refer : https://developer.android.com/studio/debug/device-file-explorer

6. Android Basic Components


There are four different types of app components:

 Activities

 Services

 Broadcast receivers

 Content providers

Link to refer : https://developer.android.com/guide/components/fundamentals


7. Activity and its Life cycle
An Android activity is one screen of the Android app's user interface. In that way an Android
activity is very similar to windows in a desktop application. An Android app may contain one or
more activities, meaning one or more screens.

8. Android Activity Lifecycle methods


The 7 lifecycle methods of android activity.

Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.

onPause called when activity is not visible to the user.

onStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.

Link to refer :

https://developer.android.com/guide/components/activities/activity-lifecycle
9. Toast Message in Android

9.1Android Toast Example

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.

The android.widget.Toast class is the subclass of java.lang.Object class.

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.

9.2.1Constants of Toast class

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.

9.2.2Methods of Toast class

The widely used methods of Toast class are given below.


Method Description

public static Toast makeText(Context context, makes the toast containing text
CharSequence text, int duration) and duration.

public void show() displays toast.

public void setMargin (float horizontalMargin, float changes the horizontal and
verticalMargin) vertical margin difference.

9.2.3Android Toast Example

 Toast.makeText(getApplicationContext(),"Hello
Kavita",Toast.LENGTH_SHORT).show();

Another code:

 Toast toast=Toast.makeText(getApplicationContext(),"Hello Kavita",Toast.LENGTH_SH


ORT);
toast.setMargin(50,50);
toast.show();

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

Link To Refer : https://www.tutlane.com/tutorial/android/android-ui-controls-textview-edittext-


radio-button-checkbox

11. Android Event Listeners


In android, Event Listener is an interface in the View class that contains a single call-back method.
These methods will be called by the Android framework when the View which is registered with
listener is triggered by user interaction with the item in UI.

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.

onCreateContextMenu() This method is called when a Context Menu is being built.


Link to Refer : https://www.tutlane.com/tutorial/android/android-input-events-event-listeners-
event-handling

12. Android Intent


Android Intent is the message that is passed between components such as activities, content
providers, broadcast receivers, services etc. It is generally used with startActivity() method to
invoke activity, broadcast receivers etc.

12.1 Types of intent:

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

13. Android Bundle


Android Bundle is used to pass data between activities. The values that are to be passed are
mapped to String keys which are later used in the next activity to retrieve the values.

Link to Refer : https://developer.android.com/reference/android/os/Bundle

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.

 BaseAdapter – It is parent adapter for all other adapters


 ArrayAdapter – It is used whenever we have a list of single items which is backed by an
array
 Custom ArrayAdapter – It is used whenever we need to display a custom list
 SimpleAdapter – It is an easy adapter to map static data to views defined in your XML file
 Custom SimpleAdapter – It is used whenever we need to display a customized list and
needed to access the child items of the list or grid

Link To Refer : https://developer.android.com/reference/android/widget/Adapter

15. Fragment and its Lifecycle


Android Fragment is the part of activity, it is also known as sub-activity. There can be more than
one fragment in an activity. Fragments represent multiple screen inside one activity.

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 FragmentManager class is responsible to make interaction between fragment objects.

15.1 Android Fragment Lifecycle

The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods for
fragment.
15.2 Android Fragment Lifecycle Methods

No. Method Description

1) onAttach(Activity) it is called only once when it is attached


with activity.

2) onCreate(Bundle) It is used to initialize the fragment.

3) onCreateView(LayoutInflater, creates and returns view hierarchy.


ViewGroup, Bundle)

4) onActivityCreated(Bundle) It is invoked after the completion of


onCreate() method.

5) onViewStateRestored(Bundle) It provides information to the fragment


that all the saved state of fragment view
hierarchy has been restored.

6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

8) onPause() is called when fragment is no longer


interactive.

9) onStop() is called when fragment is no longer


visible.

10) onDestroyView() allows the fragment to clean up


resources.

11) onDestroy() allows the fragment to do final clean up


of fragment state.
12) onDetach() It is called immediately prior to the
fragment no longer being associated with
its activity.

Link to refer : https://developer.android.com/guide/components/fragments

16. Intent Filter


An intent filter is an expression in an app's manifest file that specifies the type of intents that the
component would like to receive. For instance, by declaring an intent filter for an activity, you
make it possible for other apps to directly start your activity with a certain kind of intent.

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.

Links to refer : https://developer.android.com/guide/topics/manifest/intent-filter-element

17. Broadcast Receiver


Broadcast Receivers simply respond to broadcast messages from other applications or from the
system itself. These messages are sometime called events or intents. 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.

There are following two important steps to make Broadcast Receiver works for the system
broadcasted intents −

 Creating the Broadcast Receiver

 Registering Broadcast Receiver

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.

17.2 Registering Broadcast Receiver


An application listens for specific broadcast intents by registering a broadcast receiver
in AndroidManifest.xml file. Consider we are going to register MyReceiver for system generated
event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has
completed the boot process.

BROADCAST-RECEIVER

Link to refer : https://developer.android.com/reference/android/content/BroadcastReceiver

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.

A service can essentially take two states −

Sr.No. State & Description

1 Started

A service is started when an application component, such as an activity, starts it by


calling startService(). Once started, a service can run in the background indefinitely,
even if the component that started it is destroyed.
2 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, get results, and even do so across processes with
interprocess communication (IPC).

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.

Sr.No. Callback & Description

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.

19. Intent Services

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.

Link to Refer : https://developer.android.com/guide/components/services

20. Android AsyncTask


Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform
heavy tasks in the background and keep the UI thread light thus making the application more
responsive.

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 :

 doInBackground() : This method contains the code which needs to be executed in


background. In this method we can send results multiple times to the UI thread by
publishProgress() method. To notify that the background processing has been completed
we just need to use the return statements
 onPreExecute() : This method contains the code which is executed before the background
processing starts
 onPostExecute() : This method is called after doInBackground method completes
processing. Result from doInBackground is passed to this method
 onProgressUpdate() : This method receives progress updates from doInBackground
method, which is published via publishProgress method, and this method can use this
progress update to update the UI thread
The three generic types used in an android AsyncTask class are given 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

20.1 Android AsyncTask Example


To start an AsyncTask the following snippet must be present in the MainActivity class :

MyTask myTask = new MyTask();

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:

 The AsyncTask instance must be created and invoked in the UI thread.


 The methods overridden in the AsyncTask class should never be called. They’re called
automatically
 AsyncTask can be called only once. Executing it again will throw an exception

Link to refer : https://developer.android.com/reference/android/os/AsyncTask

20.2 Android Core: Looper, Handler, and HandlerThread


These are among the building blocks of Android OS.

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

and designing an asynchronous application.

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

it is essential to create an unblocked responsive UI.

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

package classes in general.

What is the problem with java thread?

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

and reuse them for tasks execution.

Model for thread reusability:

1. The thread is kept alive, in a loop via it’s run() method.

2. The task is executed serially by that thread and is maintained in a queue (Message

Queue).

3. The thread must be terminated when done.

What is the Android’s way of doing it?

The above model is implemented in the Android via Looper, Handler, and HandlerThread. The

System can be visualized to be a vehicle as in the article’s cover.

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

task comes out of the Message Queue.

3. Looper is a worker that keeps a thread alive, loops through Message Queue and sends

messages to the corresponding handler to process.

4. Finally Thread gets terminated by calling Looper’s quit() method.


One thread can have only one unique Looper and can have many unique Handlers associated with
it.

Creating Looper and Message Queue for a Thread:


A thread gets a Looper and Message Queue by calling Looper.prepare() after its

running. Looper.prepare() identifies the calling thread, creates

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

terminated explicitly through looper.quit().

class LooperThread extends Thread {


public Handler mHandler;

public void run() {


Looper.prepare();

mHandler = new Handler() {


public void handleMessage(Message msg) {
// process incoming messages here
// this will run in non-ui/background thread
}
};

Looper.loop();
}
}

Creating Handler for a Thread:

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.

handler = new Handler() {


@Override
public void handleMessage(Message msg) {
// process incoming messages here
// this will run in the thread, which instantiates it
}
};
Sending messages to the MessageQueue via Handler can be done by two modes:

1. Message: It is a class that defines various useful methods to deal with message data. To

send an object we set the obj variable.

Message msg = new Message();


msg.obj = "send message";
handler.sendMessage(msg);

Detailed overview of Message class can be found

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 main thread.

new Handler(Looper.getMainLooper()).post(new Runnable() {


@Override
public void run() {
// this will run in the main thread
}
});

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

main thread’s MessageQueue and then executed in the main thread.

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

using this method.

private class MyHandlerThread extends HandlerThread {

Handler handler;

public MyHandlerThread(String name) {


super(name);
}

@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,

that Handler can be associated with that Looper.

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.

Other way to create the HandlerThread:

HandlerThread handlerThread = new HandlerThread("MyHandlerThread");


handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
Note: HandlerThread needs to call myHandlerThread.quit() to free the resources and stop the

execution of the thread.

21. Android Shared Preferences


Shared Preferences allows activities and applications to keep preferences, in the form of key-value
pairs similar to a Map that will persist even when the user closes the application.

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:

 on uninstalling the application


 on clearing the application data (through Settings)

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.

To get access to the preferences, we have three APIs to choose from:

 getPreferences() : used from within your Activity, to access activity-specific preferences


 getSharedPreferences() : used from within your Activity (or other application Context), to
access application-level preferences
 getDefaultSharedPreferences() : used on the PreferenceManager, to get the shared
preferences that work in concert with Android’s overall preference framework

In this tutorial we’ll go with getSharedPreferences(). The method is defined as follows:

getSharedPreferences (String PREFS_NAME, int mode)

PREFS_NAME is the name of the file.

mode is the operating mode.

Following are the operating modes applicable:

 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

22. Android AlertDialog


Android AlertDialog is used in cases when we require the user to choose an option from the prompt

presented on the screen.

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.

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

22.1 Android AlertDialog Components

1. Title: Note that title is optional


2. Content: This displays the message to the user. It can be a string message, a list or custom
layout
3. Action Buttons: These buttons are of three types. They are Positive, Negative and Neutral
action buttons. An alert dialog can have maximum three action buttons. In general following
are the conventions for the buttons:
 If you want the user to accept the action, use Positive action button. It is normally
displayed as OK/YES.
 If the user wants to cancel the action, then you can use Negative action button (NO).
 If the user wants to postpone the decision use Neutral action button (Later).

22.2 AlertDialog Functions


Besides this, there are some functions available to customise the alert dialog as 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 alertDialog = alertDialogBuilder.create();

alertDialog.show();

Link to refer : https://developer.android.com/guide/topics/ui/dialogs

23. Android SQLite


SQLite is an open-source relational database i.e. used to perform database operations on android
devices such as storing, manipulating or retrieving persistent data from the database.

It is embedded in android by default. So, there is no need to perform any database setup or
administration task.

SQLiteOpenHelper class provides the functionality to use the SQLite database.

24. SQLiteOpenHelper class


The android.database.sqlite.SQLiteOpenHelper class is used for database creation and version
management. For performing any database operation, you have to provide the implementation
of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.

24.1 Constructors of SQLiteOpenHelper class

There are two constructors of SQLiteOpenHelper class.

Constructor Description

SQLiteOpenHelper(Context context, String name, creates an object for creating,


SQLiteDatabase.CursorFactory factory, int version) opening and managing the
database.

SQLiteOpenHelper(Context context, String name, creates an object for creating,


SQLiteDatabase.CursorFactory factory, int version, opening and managing the
DatabaseErrorHandler errorHandler) database. It specifies the error
handler.
24.2 Methods of SQLiteOpenHelper class

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.

public abstract void onUpgrade(SQLiteDatabase db, called when database needs to be


int oldVersion, int newVersion) upgraded.

public synchronized void close () closes the database object.

public void onDowngrade(SQLiteDatabase db, int called when database needs to be


oldVersion, int newVersion) downgraded.

25. SQLiteDatabase class


It contains methods to be performed on sqlite database such as create, update, delete, select etc.

25.1 Methods of SQLiteDatabase class

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)

Cursor query(String table, String[] returns a cursor over the resultset.


columns, String selection, String[]
selectionArgs, String groupBy, String
having, String orderBy)

Link to Refer : https://developer.android.com/reference/android/database/sqlite/package-


summary

Vous aimerez peut-être aussi