0% found this document useful (0 votes)
46 views39 pages

Android Basics for Developers

Android is an open source operating system for mobile devices. It includes activities which represent screens, fragments which define reusable UI components, and layouts which define the structure and organization of views and view groups on screens.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views39 pages

Android Basics for Developers

Android is an open source operating system for mobile devices. It includes activities which represent screens, fragments which define reusable UI components, and layouts which define the structure and organization of views and view groups on screens.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Introduction to Android

{ 1. An Introduction to Android
2. Activity
3. Layout
C O N T E N T S
4. Android Services
5. Android Broadcast Receiver
6. An Introduction to SQLite

/ / H U A W E I D e v e l o p e r s P l a y b o o k ; + - < / > # ; = [ ]
}
{

Introduction to Android

/ / H U A W E I D e v e l o p e r s ; + - < / > # ; = [ ]
}
Android

{ Android is an open source and Linux-based Operating System for mobile devices such as smartphones and
tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other
companies. Currently It became a complete set of operating systems for different devices like wearables,
mobiles, notebooks, smart TVs, tablets, set-top boxes, etc.

Key Features of the Android Operating System:

 User Interface
 Multiple Language Support
 Multi-tasking
 Connectivity
 Extensive Application Support etc.

+ - </> # ; = []”/!*
}
{
Android Application Components

Application components are the essential building blocks of an Android application. Each component is an
entry point through which the system or a user can enter your app. These components are loosely coupled
by the application manifest file Android Manifest.xml that describes each component of the application
and how they interact.
There are four different types of app components:
• Activities
• Services
• Broadcast receivers
• Content providers

+ - </> # ; = []”/!*
}
{

Activity

/ / H U A W E I D e v e l o p e r s ; + - < / > # ; = [ ]
}
What is Activity

{ An activity is the entry point for interacting with the user. It


represents a single screen with a user interface. For example, an
email app might have one activity that shows a list of new emails,
another activity to compose an email, and another activity for
reading emails.

Activity Life Cycle


The lifecycle is the set of states an activity can be in during its
entire lifetime, from when it's created to , when it's destroyed and
the system reclaims its resources.

+ - </> # ; = []”/!*
}
{
onCreate() : In this state, the activity is created.

onStart() : This callback method is called when the activity becomes visible to the user.

onResume() : The activity is in the foreground and the user can interact with it.

onPause() : Activity is partially obscured by another activity. Another activity that’s in the foreground is

semi-transparent.

onstop() : The activity is completely hidden and not visible to the user.

onRestart() : From the Stopped state, the activity either comes back to interact with the user or the activity

is finished running and goes away. If the activity comes back, the system invokes onRestart()

onDestroy() : Activity is destroyed and removed from the memory.

+ - </> # ; = []”/!*
}
Task and Back Stack

{  The activities are arranged in a stack—the back stack—in the order in which each activity is opened.
 For example, an Email app might have one activity to show a list of new messages. When the user selects a
message, a new activity opens to view that message. This new activity is added to the back stack. If the user
presses the Back button, that new activity is finished and popped off the stack.
 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. When an activity stops, the system retains the
current state of its user interface.

+ - </> # ; = []”/!*
}
{
 When the user presses the Back button, the current activity is popped from the top of the stack (the
activity is destroyed) and the previous activity resumes (the previous state of its UI is restored).
 Activities in the stack are never rearranged, only pushed and popped from the stack

Each new activity in a task adds an item to the back stack. When the user presses the Back button, the
current activity is destroyed and the previous activity resumes.
If the user continues to press Back, then each activity in the stack is popped off to reveal the previous one,
until the user returns to the Home screen (or to whichever activity was running when the task began). When
all activities are removed from the stack, the task no longer exists.

+ - </> # ; = []”/!*
}
Introduction to Fragments

{ A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own
layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their
own--they must be hosted by an activity or another fragment.

+ - </> # ; = []”/!*
}
Fragment Lifecycle

{ Many events can occur between these states -- for example the user can hit the back
button.

onAttach() is called when the Fragment is attached to its parent activity


onCreate() is called to initially create the fragment
onCreateView() is called to created its user interface -- it inflates the fragment UI
onActivityCreated() is called once the parent activity and the fragment UI are
created.
onStart() is called the start of the visible lifetime, any UI changes can be applied
before the fragment goes visible
onResume() is called at the start of the active lifetime such as resuming any
paused UI updates needed by the fragment that were suspended when it became

}
inactive.

+ - </> # ; = []”/!*
{
onPause() called at the end of the active lifetime; persist all edits or state changes, suspend UI updates,
threads, or CPU intensive processes that don't need to be updated when the Activity isn't the active
foreground activity
onSaveInstanceState() called to save UI state changes at the end of the active lifecycle
onStop() called at the end of the visible lifetime
onDestroyView() called when the fragment's view is detached
onDestroy() called at the end of the full lifetime
onDetach() called when the Fragment has been detached from its parent activity.

+ - </> # ; = []”/!*
}
{

Layout

/ / H U A W E I D e v e l o p e r s ; + - < / > # ; = [ ]
}
Layout: ViewGroups and Views

{  A Layout defines the structure for a user


interface in your app, such as in an activity.
 All user interface elements in an Android app are
built using View and ViewGroup objects.
 A View is an object that draws something on the
screen that the user can interact with.
- Examples: buttons and text fields
 A ViewGroup is a special view that contain
other views(called children). The view group is
the base class for layouts and views containers.
-Examples: linear, relative or constraint layout

+ - </> # ; = []”/!*
}
Common Layouts

{ Linear Layout Relative Layout Constraint Layout

A layout that organizes Enables you to specify the Figure 1. The editor shows view
C below A, but it has no vertical
its children into a single location of child objects constraint
horizontal or vertical row. relative to each other (child
It creates a scrollable if A to the left of child B) or to
the length of the window the parent (aligned to the
exceeds the length of the top of the parent).

}
screen.
Figure 2. View C is now vertically
+ - </> # ; = []”/!* constrained below view A
Layout Attributes & Parameters

{
android:id - This is the ID which uniquely identifies the view.
android:layout_width - This is the width of the layout.
android:layout_height - This is the height of the layout.
android:layout_margintTop - This is the extra space on the top side
of the layout.
android:layout_marginBottom - This is the extra space on the
bottom side of the layout.
android:layout_marginLeft - This is the extra space on the left side
Figure 1. Visualization of a view hierarchy with layout
of the layout. parameters associated with each view.
android:layout_marginRight - This is the extra space on the right
Layout attributes define layout parameters for the
side of the layout. View that are appropriate for the ViewGroup in which
it resides.
android:layout_gravity - This specifies how child Views are

}
positioned.
android:layout_weight - This specifies how much of the extra space
in the layout should be allocated to the View.
+ - </> # ; = []”/!*
{

Services

/ / H U A W E I D e v e l o p e r s ; + - < / > # ; = [ ]
}
{
What is Android Services?
A Service is an application component that can perform long-
running operations in the background. It does not provide a user
interface. Once started, a service might continue running for some
time, even after the user switches to another application.
In android, services have 2 possible paths to complete its life cycle
1. Started
2. Bounded.

+ - </> # ; = []”/!*
}
{
Started
A service is started when an application component calls startService() method. Once started, a service
can run in the background indefinitely, even if the component which is responsible for the start is
destroyed.
Two option are available to stop the execution of service:
 By calling stopService() method,
 The service can stop itself by calling stopSelf() method.

+ - </> # ; = []”/!*
}
{
Bounded
A service is bound when an application component binds to it by calling bindService(). Bound service
offers a client-server interface that allows components to interact with the service, send requests and, get
results. It processes across inter-process communication (IPC). A bound service runs only as long as
another application component is bound to it. Multiple components can bind to the service at once, but
when all of them unbind, the service is destroyed. The client can unbind the service by calling
the unbindService() method.
Components which can bind to Service are Activity, Service and Content Provider and you cannot use a
broadcast receiver to connect to a service.

+ - </> # ; = []”/!*
}
{
Bound services can be of two types
 Local binding
 Remote binding
In Local binding, the service and the component which wants to bind to that particular service are the
part of the same app process. In remote binding, the service and the component that wants to bind to
that particular service are in two different processes.
Local binding is implemented using IBinder interface and remote binding is implemented in two
mechanisms that is Messenger API and AIDL (Android Interface Definition Language). The messenger is
basically a queued concept where in, any component which wants to connect to a service will trigger
request and these are queued, and most suited for non multi-threaded scenario. AIDL is more suited for
multi-threaded environment.

+ - </> # ; = []”/!*
}
Resource Crunch Situation and Service Behavior

{ When you keep on starting multiple apps there may arise a situation where in the resource crunch
situation will happen and android may actually decide to kill your app that is not running in the
foreground. In case you had a service that was running in your app which is running in the background,
then android will not try to kill that particular app because Service is always gets a higher priority but that
doesn't mean just because you keep a service it will not get killed. If the resource crunch actually do
happen and it is very severe the android operating system may actually decide to even kill the app that
has a service.
Later, there will be a time where android operating system will have enough resources to host the service
that had been killed earlier, then what should happen to the service that had been killed that is
determined by the value that you have returned in the onstartcommand whether you want to restart the

}
service and whether the restarted service will have a intent value populated so that it can continue with its
work.

+ - </> # ; = []”/!*
{
START_STICKY
If android stops services forcefully, using with START_STICKY, it can be restarted automatically without the
user interaction.
 Services are being explicitly managed & long running.
 No need to remember state at kill time.
The typical scenario is a music service which is constantly running a music audio. When it gets killed it will
restart when the resources are available, but with the null intent, so that it may not have to remember
which song was playing earlier, you don't want your music service to automatically start blasting music in
your ears in your unexpected time because it got killed some quiet time back. 111

+ - </> # ; = []”/!*
}
{
START_NOT_STICKY
If android stops services forcefully, it will not restart services till user start services.
 Services are being not explicitly managed.
 Services are periodically running and self stopping.
Alarm services are a kind of service which is periodically will do some kind of backend job, like polling the
data from the server every ten minutes or 20 minutes. So during that time if it gets killed there is no need
to restart it because it is always going to be once again triggered after 10 or 20 minutes. So tasks which
need to be run in the background periodically are the best examples of START_NOT_STICKY services.

+ - </> # ; = []”/!*
}
{
START_REDELIVER_INTENT
If android stops services forcefully, it will restart services by re-sending an intent.
 Services are being explicitly managed.
 Restart from previous state at the kill time.
A typical example is file download. If the file download service gets killed somewhere in between because
of the resource crunch and when later resources become available the file download should continue from
there it had been stopped.

+ - </> # ; = []”/!*
}
{

Broadcast Receiver

/ / H U A W E I D e v e l o p e r s ; + - < / > # ; = [ ]
}
{
What is Android Broadcast Receiver?
A broadcast receiver (receiver) is an Android component which allows you to register for system or
application events. All registered receivers for an event are notified by the Android runtime once this event
happens.
For example, applications can register for the ACTION_BOOT_COMPLETED system event which is fired
once the Android system has completed the boot process.

+ - </> # ; = []”/!*
}
{
 The broadcast message is referred to as an Event or
Intent. Broadcast receivers, unlike Activities have no
user interface.
 The Broadcast Receiver’s job is to pass a notification to
the user, in case a specific event occurs
 Using a Broadcast Receiver, applications can register for
a particular event. Once the event occurs, the system will
notify all the registered applications.
Examples :
1. battery Low notification that you see on your
mobile screen.

}
2. Wi-Fi Activated/Deactivated message

+ - </> # ; = []”/!*
{
Creating a BroadcastReceiver
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the
onReceive() method where each message is received as a Intent object parameter.

public class MyBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
...

}
}

+ - </> # ; = []”/!*
}
{
Registering the BroadcastReceiver in android app
A BroadcastReceiver can be registered in two ways.
1. By defining it in the AndroidManifest.xml file as shown below.

<receiver android:name=".MyBroadcastReceiver"
android:permission="android.permission.SEND_SMS">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"/>
</intent-filter>
</receiver>

Using intent filters you tell the system any intent that matches our subelements should get delivered
to that specific broadcast receiver.

+ - </> # ; = []”/!*
}
{
2. By defining it programmatically.
Following snippet shows a sample example to register broadcast receiver programmatically.

IntentFilter intentFilter = new IntentFilter();


intentFilter.addAction(Intent. ACTION_AIRPLANE_MODE_CHANGED);
MyReceiver myReceiver = new MyReceiver();
this.registerReceiver(myReceiver, filter);

+ - </> # ; = []”/!*
}
{
Un Registering the BroadcastReceiver
To unregister a broadcast receiver in onStop() or onPause() of the activity

@Override
protected void onPause() {
unregisterReceiver(myReceiver);
super.onPause();
}

+ - </> # ; = []”/!*
}
{

SQLite

/ / H U A W E I D e v e l o p e r s ; + - < / > # ; = [ ]
}
{
What is 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.
Whenever an application needs to store large amount of data then using SQLite is more preferable than
other repository system like SharedPreferences or saving data in files.

+ - </> # ; = []”/!*
}
{
What is Room Database
Room Database is a part of the Android Architecture components which provides an abstraction layer over
SQLite which allows for more robust database access. The room is an ORM (object relational mapper) for
SQLite database in Android.

+ - </> # ; = []”/!*
}
{
Why Room DB
 Compile-time verification of SQL queries. each @Query and @Entity is checked at the compile time,
that preserves your app from crash issues at runtime and not only it checks the only syntax, but also
missing tables.
 Reduces Boilerplate code
 Easily integrated with other Architecture components (like LiveData).

+ - </> # ; = []”/!*
}
{
Questions?

/ / H U A W E I D e v e l o p e r s ; + - < / > # ; = [ ]
}
{

Thank You

/ / H U A W E I D e v e l o p e r s ; + - < / > # ; = [ ]
}

You might also like