KEMBAR78
1-Introduction To Android | PDF | Java (Programming Language) | Android (Operating System)
0% found this document useful (0 votes)
12 views83 pages

1-Introduction To Android

Uploaded by

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

1-Introduction To Android

Uploaded by

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

Android 1: Background

1
Buzzwords…
• The Android platform originated in a separate
company
• It was acquired by Google
• It is supported by the Open Handset Alliance
(OHA)
• From a business perspective, Android is
distinguished by the fact that many vendors are
cooperating to provide a non-proprietary
development environment
2
Android … What?
• Android is a Linux-based platform for
mobile devices …
– Operating System
– Middleware
– Applications
– Software Development Kit (SDK)

• Which kind of mobile devices … (examples)

SMARTPHONES
TABLETS
EREADERS ANDROID TV GOOGLE GLASSES
?
3
Android – At a Glance
• Software stack for mobile devices
– incl. OS, middleware and key applications
• Open source – source code is open and contributions are
welcome
• Application framework enabling reuse/replacement of apps
• Dalvik virtual machine optimized for mobile
• Integrated browser based on webkit
• Optimized graphics – 2D graphics library, 3D based on OPEN
GL ES
• SQLite, Firebase for data storage
• Media support (MPEG4, H.264, MP3, AAC, JPG, PNG,…)
• Support for radio interfaces, Bluetooth, WiFi, Camera, GPS,
accelerometer
• Software Development Kit (SDK)
• Preinstalled applications from Google Mobile Service (GMS)
– Gmail, Maps, Search, Voice Search, Youtube
Key components of this successful alliance
are:
• Hardware device manufacturers
• Mobile service providers
• Android/Google, which provides the basic
software operating and development
environments
• Independent app developers marketing
through the app store or other places

5
The platform is based on:
• A secure operating system, Linux
• Virtual machines running on top of Linux
(known as Dalvik virtual machines, now ART)
• A widely-known object-oriented language,
Java, now Kotlin also as an official language.
• An advanced software development
environment, Android Studio

6
Proprietary vs. non-proprietary
• Android is based on open source licensing
• Developers do not have to pay fees to use the
development tool kit
• They do not have to pay fees on the apps
developed with it
• The app developer API includes everything
that a “native” programmer would have
access to

7
Versions
• The different versions of Android have been
given the names of “sweets”
• Version 9 is the last version named as Pie
• As with all growing platforms, backwards
compatibility and other issues can be
significant
• Form version 10 released in September 2019,
they are simply identified by numbers.

8
9
Development Software
• There are various different ways of going
about developing apps for Android
• Development environments range from the
graphical to heavy-duty programming
• For example, there are environments
specifically designed to help developers
implement games without necessarily
becoming expert in the details of raw Android
development
10
• The Java SDK
• Android Studio with the Android SDK, latest
3.5.3 version with support of Kotlin
• Java is available for downloading from the Java
(Oracle) Web site, www.java.com
• Android Studio is available through the Google
Web site, developer.android.com

11
Another useful aspect of the development
environment: The Emulator
• It comes with an emulator for handheld
devices
• This means that you can initially develop and
test code on a PC with the development
environment installed
• You don’t literally have to develop on the
handheld device

12
Emulation isn’t the be-all, end-all:
• The emulator is slow
• The emulator can be problematic
• The emulator may not fully model the
hardware device of interest
• The reality is that you eventually have to test
and finish development on a hardware device
if you expect to roll out the app on that device

13
The Emulator: Boon or Bane?
• It is unbelievable how slow the emulator is on
an up-to-date, reasonably powerful machine
with a reasonable amount of memory
• If you try to launch an app on an emulator that
hasn’t yet fully started, the app won’t run
• This can be a source of confusion and problems
• The moral of the story is to make sure the
emulator is fully up and running before trying to
run an app on it
14
• The emulator is a big benefit if you don’t have
a device at hand
• The emulator is also a big benefit if you’re
having trouble with the device drivers
• Finally, the emulator is convenient if you want
to take screen shots of your app

15
The Android Architecture

} Stack
Architecture

Open Source
Architecture
(Apache/MIT License v.
2.0)

Business-friendly License
16
Software Stack
• Linux kernel
• Libraries
• Android run time
– core libraries
– Dalvik virtual machine
• application layer
• application protocol
Built on top of
Linux kernel (v.
2.6-3.0)
Advantages:

 Portability (i.e. easy


to compile on different
harwdare
architectures)

 Security (e.g. secure


multi-process
environment)

 Power Management
18
• Linux version 2.6.x for core system services.
• Provides proven driver model.
• Provides memory management, process
management, security model, networking
and lot of core OS infrastructure
Native Libraries
(C/C++ code)

Graphics (Surface Manager)

Multimedia (Media
Framework)

Database DBMS
(SQLite)

Font Management
(FreeType)

 WebKit

C libraries (Bionic)

….
20
• Libc: c standard library
• SSL: Secure Socket Layer

• Surface Manager:
responsible for
composing different
drawing surfaces onto the
screen.
• OpenGL|ES : 3D Image Engine
• SGL : 2D image Engine.
 Hence we can combine 3D and 2D graphics in the same application.
• Media Framework : Core part of the android multimedia.
MPEG4,H264,MP3,AAC…..

• FreeType: To render the fonts.


• WebKit: open source browser engine. Helps to work well on small screen.
• SQLite: Embedded Database
Application
Libraries
(Core Components of Android)

Activity Manager

Package Manager

Telephony Manager

Location Manager

Contents Provider

Notification Manager

….

22
•Android runtime meet the needs of running in an embedded environment
i.e. where is limited battery, limited Memory and limited CPU.

• CORE LIBRARIES:
Java Programming Language
 contains all the collection classes, utilities, IO.. all these utilities which
you come across and expect to use.

•DALVIK VIRTUAL MACHINE:


Java based license free VM
Optimization for low memory requirements.
DVM runs .dex files (byte codes) that converts during built time.
 more efficient and run very well on
small processors.
structures are designed to be shared
across processes due to which multiple
instance of DVM running on device at
the same time one in several processes
Applications
(Written in Java code)

Android Play Store

Entertainment

Productivity

Personalization

Education

Geo-communication

….

24
Applications
• All apps (native and 3rd party) are written using
the same APIs and run on the same run time
executable
• All apps have APIs for hardware access, location-
based services, support for background services,
map-based activities, 2D and 3D graphics.
• App Widgets are miniature app views that can be
embedded in other apps like Home Screen
Dalvik Virtual
Machine (VM)
Novel Java Virtual
Machine
implementation (not
using the Oracle JVM)

Open License (Oracle


JVM is not open!)

Optimized for
memory-constrained
devices

Faster than Oracle


JVM

26 ….
Dalvik VM
• All applications written in Java are converted to the
dalvik executable .dex
• Every android app runs its own process, with its own
instance of the dalvik virtual machine under zygote.
• Not a traditional JVM, but a custom VM designed to
run multiple instances efficiently on a single device
• VM uses linux kernel to handle low-level functionality
incl. security, threading, process and memory
management
• Discontinued after Kitkat and replaced by ART from
Lollypop onwards which uses AOT (Ahead-of-time)
compilation
Dalvik Java Virtual Machine (JVM)
Java Source Java Source
Java Standard Edition
Code Code
Java Java
Compiler Compiler
Java Byte Java Byte
Code Code
Dex
Compiler
Stack-based Dalvik Byte
byte-code Code
Register-based
byte-code
Java Virtual Dalvik Virtual
Machine Machine
(JVM) (VM)

28
29
AndroidX
• Artifacts within the androidx namespace comprise
the Android Jetpack libraries. Like the Support
Library, libraries in the androidx namespace ship
separately from the Android platform and provide
backward compatibility across Android releases.
• AndroidX is a major improvement to the original
Android Support Library, which is no longer
maintained. androidx packages fully replace the
Support Library by providing feature parity and new
libraries.
30
Features of AndroidX
• All packages in AndroidX live in a consistent namespace
starting with the string androidx. The Support Library
packages have been mapped into
corresponding androidx.* packages. For a full mapping of all
the old classes and build artifacts to the new ones, see
the Package Refactoring page.
• Unlike the Support Library, androidx packages are separately
maintained and updated. The androidx packages use
strict Semantic Versioning, starting with version 1.0.0. You can
update AndroidX libraries in your project independently.
• Version 28.0.0 is the last release of the Support Library. There
will be no more android.support library releases. All new
feature development will be in the androidx namespace. 31
Migrating to AndroidX
• Before you migrate, bring your app up to date. We
recommend updating your project to use the final
version of the support library: version 28.0.0. This is
because AndroidX artifacts with version 1.0.0 are
binary equivalent to the Support Library 28.0.0
artifacts.
• With Android Studio 3.2 and higher, you can migrate
an existing project to AndroidX by selecting Refactor
> Migrate to AndroidX from the menu bar.
• The refactor command makes use of two flags. By
default, both of them are set to true in
your gradle.properties file.
32
Migrating to AndroidX
• android.useAndroidX=true
• The Android plugin uses the appropriate AndroidX
library instead of a Support Library.android.
• enableJetifier=true
• The Android plugin automatically migrates existing
third-party libraries to use AndroidX by rewriting
their binaries.

33
Application Fundamentals
• Android applications are written in the Java
programming language.
• The compiled Java code — along with any data and
resource files required by the application — is bundled
by the aapt (Android Asset Packaging tool) into an
Android package, an archive file marked by an .apk
suffix.
• This file is the vehicle for distributing the application and
installing it on mobile devices; it's the file users
download to their devices. All the code in a single .apk
file is considered to be one application.
Application Fundamentals
• By default, every application runs in its own
Linux process. Android starts the process
when any of the application's code needs to
be executed, and shuts down the process
when it's no longer needed and system
resources are required by other applications.
• Each process has its own virtual machine
(VM), so application code runs in isolation
from the code of all other applications.
Application Fundamentals
• By default, each application is assigned a unique
Linux user ID. Permissions are set so that the
application's files are visible only to that user and
only to the application itself — although there are
ways to export them to other applications as well.
• It's possible to arrange for two applications to share
the same user ID, in which case they will be able to
see each other's files. To conserve system resources,
applications with the same ID can also arrange to run
in the same Linux process, sharing the same VM.
Application Fundamentals
• Activities
– application presentation layer
• Services
– invisible components, update data sources, visible activities, trigger
notifications
– perform regular processing even when app is not active or invisible
• Content Providers
– shareable data store
• Intents
– message passing framework
– broadcast messages system wide, for an action to be performed
• Broadcast receivers
– consume intent broadcasts
– lets app listen for intents matching a specific criteria like location
• Notifications
– Toast, Snackbar notification
– Status Bar Notification
– Dialog notification
Application Components
• An Android application can make use of
elements of other applications. If your
application needs to display a scrolling list of
images and another application has developed
a suitable scroller and made it available to
others, you can call upon that scroller to do
the work.
• Your application simply starts up that piece of
the other application when the need arises.
Application Components
• The system must start an application process
when any part of it is needed, and instantiate
the Java objects for that part. Android
applications don't have a single entry point
(no main() function).
• Android applications have essential
components that the system can instantiate
and run as needed.
Android Applications Design
APPLICATION DESIGN:

 GUI Definition

 Events Management

 Background Operations

 Application Data Management

 User Notifications
40
Android Applications Design
APPLICATION COMPONENTS

 Activities

 Intents
 Services
 Content Providers
 Broadcast Receivers

41
Android Components: Activities
 An Activity corresponds to a single
screen of the Application.
Android
HelloWorld  An Application can be composed of
Button1
multiples screens (Activities).

Hello World!  The Home Activity is shown when the


user launches an application.

 Different activities can exhange


information one with each other.

42
• Each activity is independent of the others.
• Each one is implemented as a subclass of the
Activity, now AppCompatActivity base class.
• Typically, one of the activities is marked as the first
one that should be presented to the user when the
application is launched.
• Moving from one activity to another is
accomplished by having the current activity start
the next one.
Windows Components: View

• The visual content of the window is provided by a


hierarchy of views — objects derived from the base
View class.
• Each view controls a particular rectangular space
within the window. Parent views contain and
organize the layout of their children.
• Leaf views (those at the bottom of the hierarchy)
draw in the rectangles they control and respond to
user actions directed at that space.
Android Components: Activities
 Each activity is composed by a list of graphics components.
 Some of these components (also called Views) can interact
with the user by handling events (e.g. Buttons).
 Two ways to build the graphic interface:

PROGRAMMATIC APPROACH

Example:

Button button=new Button (this);


TextView text= new TextView();
text.setText(“Hello world”);

45
Android Components: Activities
DECLARATIVE APPROACH

Example:

< TextView android.text=@string/hello”


android:textcolor=@color/blue
android:layout_width=“fill_parent”
android:layout_height=“wrap_content” />
< Button android.id=“@+id/Button01”
android:textcolor=“@color/blue”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content” />

46
Android Components: Activities
EXAMPLE
- Build the application layout
through XML files (like HTML)
- Define two different XML
layouts for two different
Device 1 Device 2
devices
HIGH screen pixel density LOW screen pixel density - At runtime, Android detects
the current device
Java App Code configuration and loads the
appropriate resources for the
application
- No need to recompile!
- Just add a new XML file if you
XML Layout File XML Layout File need to support a new device
Device 1 Device 2
47
Android Components: Activities
 Android applications typically use both the approaches!

DECLARATIVE APPROACH

Define the Application layouts


XML Code and resources used by the
Application (e.g. labels).

PROGRAMMATIC APPROACH

Manages the events, and


Java Code handles the interaction with
the user.
48
Android Components: Activities
 Views can generate events (caused by human interactions)
that must be managed by the Android-developer.

TextEdit
Button

public void onClick(View arg0) {


if (arg0 == Button) {
// Manage Button events
}
}

49
Android Components: Activities
 The Activity Manager is responsible for
creating, destroying, managing
activities.

 Activities can be on different states:


starting, running, stopped, destroyed,
paused.

 Only one activity can be on the running


state at a time.
 Activities are organized on a stack, and
have an event-driven life cycle (details later
…) 50
Android Components: Activities
 Main difference between Android-programming
and Java (Oracle) -programming:
 Mobile devices have constrained resource capabilities!

 Activity lifetime depends on users’ choice (i.e.


change of visibility) as well as on system
contraints (i.e. memory shortage).

 Developer must implement lifecycle methods to


account for state changes of each Activity …
51
Android Components: Activities
public class MyApp extends Called when the Activity
Activity { is created the first time.

public void onCreate()


{ ... } Called when the Activity
public void onPause() is partially visible.
{ ... }
public void onStop()
{ ... } Called when the Activity
public void onDestroy() is no longer visible.
{ ... }
….
Called when the Activity
} is dismissed.

52
Android Components: Intents
 Intents: asynchronous messages to activate core
Android components (e.g. Activities).
 Explicit Intent  The component (e.g. Activity1)
specifies the destination of the intent (e.g. Activity 2).

LOGIN Welcome Marco!


marco
Activity1

Activity2
PASSWOR
D
**********

Login Intent
Login

53
Android Components: Intents
 Intents: asynchronous messages to activate core
Android components (e.g. Activities).
 Implicit Intent  The component (e.g. Activity1)
specifies the type of the intent (e.g. “View a video”).

Activity2
Multiple choices

}
might be available
to the user!
Activity1

Intent-
View Filters
Implicit Intent

Activity2
54
Android Components: Services
 Services: like Activities, but run in background and do not
provide an user interface.
 Used for non-interactive tasks (e.g. networking).
 Service life-time composed of 3 states:

Starting Destroyed

onCreate()
onDestroy()
onStart()

Running

(on background)
55
Services
• A service doesn't have a visual user interface, but rather runs
in the background for an indefinite period of time.
• Each service extends the Service base class.
• A good example of a service is a media player playing songs.
One or more player activities would allow the user to choose
songs and start playing them. The music playback itself would
not be handled by an activity (users will expect the music to
keep playing ). The media player activity could start a service
to run in the background.
Services
• It's possible to connect to (bind to) an ongoing service (and
start the service if it's not already running). While connected,
you can communicate with the service through an interface
that the service exposes. For the music service, this interface
might allow users to pause, rewind, stop, and restart the
playback.
• Like activities and the other components, services run in the
main thread of the application process. So that they won't
block other components or the user interface, they often
spawn another thread for time-consuming tasks (like music
playback).
Android Components: Content Providers

 Each Android application has its own private set of data


(managed through files or through SQLite database).
 Content Providers: Standard interface to access and
share data among different applications.

insert()
APP
update()
Content
delete() Provider DB

query() e.g. Photo


Gallery

58
Content providers
• A content provider makes a specific set of the application's
data available to other applications. The data can be stored in
the file system, in an SQLite database, or in any other manner
that makes sense, like firebase.
• The content provider extends the ContentProvider base class
to implement a standard set of methods that enable other
applications to retrieve and store data of the type it controls.
• Applications do not call these methods directly. Rather they
use a ContentResolver object and call its methods instead. A
ContentResolver can talk to any content provider; it
cooperates with the provider to manage any interprocess
communication that's involved.
Android Components: Broadcast Receivers

 Publish/Subscribe
paradigm
 Broadcast Receivers:
An application can
be signaled of
external events.
 Notification types:
Call incoming, SMS
delivery, Wifi
network detected,
60
etc
Broadcast receivers
• A broadcast receiver is a component that does nothing but
receive and react to broadcast announcements.
• Many broadcasts originate in system code — for example,
announcements that the timezone has changed, that the
battery is low, that a picture has been taken, or that the user
changed a language preference.
• Applications can also initiate broadcasts — for example, to let
other applications know that some data has been
downloaded to the device and is available for them to use.
Broadcast Receiver
• An application can have any number of broadcast receivers to
respond to any announcements it considers important. All
receivers extend the BroadcastReceiver base class.
• Broadcast receivers do not display a user interface. However,
they may start an activity in response to the information they
receive, or they may use the NotificationManager to alert the
user.
• Notifications can get the user's attention in various ways —
flashing the backlight, vibrating the device, playing a sound,
and so on. They typically place a persistent icon in the status
bar, which users can open to get the message.
Android Components: Broadcast Receivers
BROADCAST RECEIVER example
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent)
{
String s = new StringBuilder();
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++){
s.append(new Integer(i+1).toString() +
".");
s.append((wifiList.get(i)).toString());
s.append("\\n");
}
mainText.setText(sb);
}
}
63
Android Components: Broadcast Receivers
BROADCAST RECEIVER example

public class WifiTester extends Activity {


WifiManager mainWifi;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
public void onCreate(Bundle savedInstanceState) {

mainWifi = (WifiManager)
getSystemService(Context.WIFI_SERVICE);
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi, new
IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifi.startScan();
}
64
Android Components: System API

 Using the components described so far, Android


applications can then leverage the system API …
SOME EXAMPLEs …

 Telephony Manager data access (call, SMS,


etc)
 Sensor management (GPS, accelerometer, etc)
 Network connectivity (Wifi, bluetooth, NFC, etc)
 Web surfing (HTTP client, WebView, etc)
 Storage management (files, SQLite db, etc)
 …. 65
Android Components: Google API

 … or easily interface with other Google services:

66
Android Application Distribution
 Each Android application is
contained on a single APK file.
APK
FILE  Java Byte-code (compiled for
DalvikVM or ART)

 Resources (e.g. images. videos,


XML layout files)
XML C
Files  Libraries (optimal native C/C++
code)

67
 Each application must be
signed through a key before
being distributed.

 Applications can be distributed


via Web or via Stores.

 Android Play Store: application


store run by Google … but
several other application stores
are available (they are just
normal applications).
68
Android Application Security

 Android applications run with a distinct system identity


(Linux user ID and group ID), in an isolated way.
 Applications must explicitly share resources and data.
They do this by declaring the permissions they need
for additional capabilities.
 Applications statically declare the permissions they require.
 User must give his/her consensus during the installation.

ANDROIDMANIFEST.XML

ses-permission android:name=“android.permission.IACCESS_FINE_LOCATI

ses-permission android:name=“android.permission.INTERNET" />

69
Android Activity Life Cycle
• Each application runs in its own process.
• Each activity of an app is run in the apps process
• Processes are started and stopped as needed to
run an apps components.
• Processes may be killed to reclaim needed
resources.
• Killed apps may be restored to their last state
when requested by the user
70
onCreate()
• onCreate() method is called when activity gets
memory in the OS.
• To use create state we need to override
onCreate(Bundle savedInstanceState) method.
• Bundle is a data repository object that can store any
kind of primitive data and this object will be null until
some data isn’t saved in that.
• When an Activity first call or launched then
onCreate(Bundle savedInstanceState) method is
responsible to create the activity.
onCreate()
• When ever orientation(i.e. from horizontal to vertical
or vertical to horizontal) of activity gets changed or
when an Activity gets forcefully terminated by any
Operating System then savedInstanceState i.e. object
of Bundle Class will save the state of an Activity.
• It is best place to put initialization code.
• Not killable
onStart( )
• onStart() method is called just after onCreate. In other case
Activity can also be started by calling restart method i.e after
activity stop.
• onStart() also gets called by Android OS when user switch
between applications after onRestart().
• For example, if a user was using Application A and then a
notification comes and user clicked on notification and moved
to Application B, in this case Application A will be paused.
• And again if a user again click on app icon of Application A then
Application A which was stopped will again gets started.
• Not killable

74
onRestart()
• Called after the activity has been stopped, just
prior to it being started again.
• Always followed by onStart().
• Not killable.
onResume()
• Activity resumed is that situation when it is
actually visible to user means the data
displayed in the activity is visible to user.
• In lifecycle, it always gets called after activity
start and in most use case after activity
paused (onPause).
• Always followed by onPause().
• Not killable.
onPause()
• Activity is called paused when it’s content is not visible to user,
in most case onPause() method called by Android OS when user
press Home button (Center Button on Device) to make hide.
• Activity also gets paused before stop called in case user press
the back navigation button.
• The activity will go in paused state for these reasons also if a
notification or some other dialog is overlaying any part (top or
bottom) of the activity (screen).
• Similarly, if the other screen or dialog is transparent then user
can see the screen but cannot interact with it.
• For example, if a call or notification comes in, the user will get
the opportunity to take the call or ignore it.
• Killable.
onStop()
• Activity is called stopped when it’s not visible to user.
Any activity gets stopped in case some other activity
takes place of it.
• For example, if a user was on screen 1 and click on
some button and moves to screen 2. In this case
Activity displaying content for screen 1 will be stopped.
• So Activity will be in stopped state when hidden or
replaced by other activities that have been launched or
switched by user.
• In this case application will not present anything useful
to the user directly as it’s going to stop.
• Killable.
onDestroy()
• Called before the activity is destroyed. This is
the final call that the activity will receive.
• It could be called either because the activity is
finishing (someone called finish() on it), or
because the system is temporarily destroying
this instance of the activity to save space.
• Killable.
Killable
• A process is killable if the system can kill the
process hosting the activity at any time after
the method returns, without executing
another line of the activity's code.
• Three methods are killable.
– onPause()
– onStop()
– onDestroy()
Killable
• Because onPause() is the first of the three, it's the
only one that's guaranteed to be called before the
process is killed.
• You should use onPause() to write any persistent data
(such as user edits) to storage.
• An activity is in a killable state from the time
onPause() returns to the time onResume() is called. It
will not again be killable until onPause() again
returns.
• An activity that's not technically "killable" by this
definition might still be killed by the system — but
that would happen only in extreme and dire
circumstances when there is no other recourse.
Lifecycle Activity Methods
Next Kill Description Method
able
?
onStart() No Called when the activity is first onCreate()
created.
onResume() No Called when the activity is onRestart()
or onStop() becoming visible to the user.
onPause() No Called when the activity will start onResume()
interacting with the user.
onResume() Yes Called when the system is about onPause()
or to start resuming a previous
onStop() activity.
onRestart() Yes Called when the activity is no onStop()
or longer visible to the user
onDestroy()
nothing Yes The final call you receive before onDestroy()
your activity is destroyed.

You might also like