Android App Development with Java Essentials
Android App Development with Java Essentials
3
OVERVIEW
ANDROID
A complete set of software for mobile devices
an operating system
middleware
key mobile applications
Open
All applications are equal
Boundaries between applications are low
5
ANDROID ARCHITECTURE
6
ANDROID RUNTIME
Dalvik: Android’s custom clean-room implementation virtual machine
Designed for embedded environment
Core APIs for Java language provide a powerful, yet simple and
familiar development platform
Data structures
Utilities
File access
Network Access
Graphics
...
7
SOME ANDROID DEVICES
Intent
Message that triggers Activity, Service, or BroadcastReceiver.
Used to communicate between application parts.
Service
Faceless task that runs in the background.
BroadcastReceiver
Set and respond to notifications or status changes.
Can wake up an application
ContentProvider
Enables applications to share some data
9
APPLICATION MODEL
In Android, there’s NO strong correlation between application image
and the process
Much more fluid borders
10
ACTIVITY AND TASK
Applications and Activities One task as Activity Stack
11
TASK AFFINITIES
Task Affinity is a unique static name for the task that one or more
activities are intended to run in
The default task affinity for an activity is the name of the .apk package name the
activity is implemented in
12
PROCESSES AND THREADS
When the first of an application's components needs to be run, Android starts a
Linux process for it with a single thread of execution
By default, all components of the application run in that process and thread.
components can be arranged to run in other processes
additional threads can be spawned for any process
Since everything, including UI, runs in the main thread, avoid long lasting
operations there
Maintain UI responsive
Launch another thread for the long-lasting operation
Multi-threading and Remote Procedure Calls will be discussed in more detail later
13
SERVICE
Service is an application (or its component) running in the background without
user interaction
Service run on application’s thread
Should launch a dedicated thread for e.g. CPU intensive services
[Link]()
[Link]()
14
CONTENT PROVIDER
Mechanism to share data between applications
Only way to share data between packages
15
BROADCAST RECEIVER
Intent receiver that will react to system-wide messages and events
Not visible, but works on the background like Services
Currently requires application to be started to react to events
Events can be incoming SMS messages, changes in location or status of
available system services, etc.
16
SUMMARY
Android is the first complete, open, and free mobile platform
provided by the Open Handset Alliance
Android is built on the Linux kernel, but Android is not Linux
Application Framework exposes the same APIs to both 3rd party apps
and core components
17
GETTING STARTED WITH
DEVELOPMENT
ANDROID STUDIO
The official IDE for Android
For all device types: Phones, Tablets, Wearables…
Supported platforms
Windows (64 & 32 bit)
MAC
Linux
19
SOME ANDROID STUDIO FEATURES
Code editor – with intellisense
UI Design tools and layout editor
Debugger
Testing tools
Profiler
Instant Run
Emulator
20
INSTALLING ANDROID STUDIO
Installation instructions can be found from:
[Link]
21
DEPLOYING AND TESTING APPS
Apps can be run and debugged within Android Studio by using
Android Emulator
Hardware device via USB (phone, tablet etc.)
If you use a HW device e.g. your phone for debugging, you need to
set the phone into ”developer mode”
Can be done from device settings
Check your phone vendor for detailed instructions
22
ANDROID EMULATOR
23
EMULATING HW FEATURES
The emulator contains many virtualised hardware features for testing
including
Location
HW Sensors
Battery
Networking
Phone & Messaging
24
CREATING AN ANDROID PROJECT
• Select File -> New ->
Android Project
Name of the application
Package namespace
25
SELECT TARGET DEVICES
• Select the device types and
minimum SDK API levels for your
project
26
SELECTING MINIMUM API LEVEL
Select the minimum API level depending on the features and APIs you use
The smaller the level, the more devices you can cover
E.g. 73.9% of devices are capable of running API level 19 (KitKat)
27
ADDING THE FIRST ACTIVITY
There are number of pre-written Activity templates you can start with
We can use Empty Activity for the first HelloWorld
28
ADDING THE FIRST ACTIVITY
”Generate Layout File” generates
an XML file for your Activity UI
With XML layout file, you can use
Android Designer tool and XML to
develop the UI instead of Java or
Kotlin
29
THE STRUCTURE OF ANDROID PROJECT
30
RUNNING (AND BUILDING)
• Select Run -> Run ’App’
• The next step is to select the target Android device to install and run the
application
• Android studio detects all installed Emulator Virtual Machines and real
devices (in developer mode) connected with USB
• New virtual machines can be added (and needs to be added in the first
time) if the app is ran in an emulator
31
ANDROID EMULATOR AND AVD MANAGER
Apps can be tested on you PC without a real device
Runs a full Android system stack (same system image as in your device)
Use same tool chain to work with devices and emulator
You can create different emulator hardware profiles via AVD (Android Virtual
Device) configuration tool
32
ADDING NEW VIRTUAL DEVICES
Create an Android Virtual Device using Android SDK and AVD Manager ( Tools-
>Android->AVD Manager)
33
DEBUGGING
34
UI: JAVA/KOTLIN (CODING) OR XML
(DESIGNER) BASED?
Creating UI:s programmatically in code is the traditional way
Complex UI:s hard to layout in code
Can be challenging to maintain
35
HELLO WORLD! – XML LAYOUT
Create an XML file specifying the layout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=”Hello World!”
/>
36
FINDING RESOURCES IN CODE
• A project's [Link] file is an index into all the resources defined in the
file
Your application is now ready to use the library APIs. All the provided
APIs are available in the [Link] package (for example,
[Link].v4)
MOST IMPORTANT SUPPORT LIBRARY
CLASSES
ConstraintLayout
AppCompatActivity
Fragment
FragmentManager
FragmentTransaction
ListFragment
DialogFragment
LoaderManager
Loader
AsyncTaskLoader
CursorLoader
GRADLE BUILD SYSTEM
Android Studio comes with Gradle build system
Gradle features can be used to
Customize, configure, and extend the build process
Create multiple APKs for your app, with different features using the same project and
modules
Reuse code and resources across sourcesets
40
SUMMARY
SDK installation and upgrade
Development environment
Hello Android! Application
Running on emulator [and on device]
Using the debugger
41
LAB: FIRST ANDROID APP
Create a new HelloWorld project for Android
Verify that everything works
Go through your environment, familiarize yourself with
Project structure and file locations
Emulator controls
Android Studio features
42
APPLICATION UI ESSENTIALS Android Essentials
MODULE CONTENTS
Ui Views
Layouts
Event handling
Resources and localization
44
VIEWS AND VIEW GROUPS
ViewGroup
View
View
View
45
DECLARING THE LAYOUT
Two different ways available:
Declare UI elements in XML.
Instantiate layout elements at runtime.
46
EXAMPLE LAYOUT XML FILE
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
</LinearLayout>
47
Source file
format
Android
WRITE THE XML
<?xml version="1.0" encoding="utf-8"?> namespace
<LinearLayout xmlns:android=
"[Link]
android:orientation="vertical"
android:layout_width="fill_parent" Compiled resource
android:layout_height="fill_parent" datatype
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button android:id="@+id/button" Reference to
android:layout_width="wrap_content" another resource
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>
48
LOAD THE XML RESOURCE
XML layout files are compiled into View resources
load the layout resource from your application code
Implement [Link]() callback, by calling setContentView()
fun onCreate(savedInstanceState:Bundle) {
[Link](savedInstanceState)
setContentView([Link].my_activity)
}
49
ID OF A VIEW
// XML
<Button
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text“
/>
// Java
public void onCreate(Bundle savedInstanceState) {
…
Button myButton = (Button) findViewById([Link].my_button);
}
TUNING THE LAYOUT
XML layout attributes named layout_something define layout
parameters
contains property types that define the size and position for each child view, as
appropriate for the view group
51
SOME COMMON ANDROID VIEWS
Button
TextView
EditText
ListView
ImageView
ProgressBar
CheckBox
RadioButton
CalendarView
DatePicker
52
SOME EXISTING LAYOUTS
LinearLayout – for simple cases
ConstraintLayout – this is the one to use to make responsive UIs!
GridLayout
FrameLayout
DrawerLayout
RelativeLayout
TableLayout
AbsoluteLayout
53
UI EVENTS
Two ways to get informed about user’s actions with UI components
Define an event listener and register it with the View, or
Override an existing callback method for the View
Using listeners:
Register the view to receive events with [Link](),
[Link] () and [Link]()
Implement the callback method, e.g. onClick() for OnClickListener
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tap Me"
android: />
// In your Activity
public void buttonClicked(View view)
[Link]("clicked");
}
COMMON LAYOUT OBJECTS
ConstraintLayout
The latest layout in Android for building responsive UI supporting multiple screen types
LinearLayout
aligns all children in a single direction — vertically or horizontally
TableLayout
positions its children into rows and columns.
does not display border lines for their rows, columns, or cells
AbsoluteLayout
enables child views to specify their own exact x/y coordinates on the screen
Coordinates (0,0) is the upper left corner
RelativeLayout
child views specify their position relative to the parent view or to each other
E.g. two elements by right border, or make one below another, centered in the screen…
58
LAB – DEFINE THE UI
Create a simple user interface for Android application
There should be a UI for a weather application that we’ll develop
during the course
More details from the instructor
59
RESOURCES
Resources are an integral part of Android applications
Application design is clearer – separate logic from definitions
Internationalization becomes easier
60
RESOURCE FOLDERS BY TYPE
res/drawable/ - bitmaps & others types those can be drawn
res/layout/ - UI layout declarations
res/values/ - simple resources, typical files in this folder:
[Link] to define color drawables and color string values
[Link] to define string values
[Link] to define style objects
61
USING A STRING RESOURCE
Simple values, like Strings, are defined in res/values/ folder of the project
In [Link], define all required strings
• Language code follows the two letter ISO 639-1 language code in
lowercase. For example: en, fr, es
• Other qualifiers can be used and chained:
MyApp/
res/
drawable-fi-finger/
drawable-port/
drawable-port-160dpi/
drawable-qwerty/ 63
TESTING LOCALE IN ANDROID EMULATOR
• You can test localized apps
against different locales with
Custom Locale app found in
Android Emulator
64
ANDROID SCREENS
65
LAB – ADDING LOCALIZATION SUPPORT
• Localize your application for at least 2 different languages of
your choice and test it in your device or Android emulator
66
CONSTRAINTLAYOUT
With ConstraintLayout we can create large and complex layouts with
flat view hierarchy
Each view in ConstraintLayout can specify relationships with other
views on the layout
Can easily be used with Android Studio’s layout editor
More info and tutorials at:
[Link]
67
CONSTRAINTLAYOUT
68
69
70
ACTIVITY EXAMPLE
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState); // Activity is being created.
}
protected void onStart() {
[Link](); // Activity is about to become visible.
}
protected void onResume() {
[Link](); // Activity has become visible
}
protected void onPause() {
[Link](); // Another activity is taking focus
}
protected void onStop() {
[Link](); // Activity is no longer visible
}
protected void onDestroy() {
[Link](); // The activity is about to be destroyed.
}
}
71
ACTIVITY STATES
72
SO, HOW DO YOU IMPLEMENT AN ACTIVITY?
Create a public class that extends [Link]
As always, class should be public, with no-args constructor, and it should not be abstract/final
73
WHEN DOES ANDROID KILL YOUR ACTIVITY?
Android system is allowed to kill your application process or destroy
your activity to free memory/other resources if necessary
Android applications don’t typically have ’quit’ or ’exit’ buttons
Applications are in the memory with other apps, killed when resources are needed
elsewhere, and reactivated when user wants to use them
Killing process won’t automatically remove object from memory, but destr ing
application object will clean everything
74
APPLICATION LIFE-CYCLE
Application can be killed anytime after onPause(), onStop(), or onDestroy() is
called
But not after onCreate(), onStart() ,onResume(), or onRestart()
onPause() is good place to write crucial persistent data to storage – since
onStop()/onDestroy() might not be called
When application is used again, Android will call onCreate(), onStart(), and onResume() again
75
SURVIVING DESTRUCTION
Android may destroy your application, removing it from memory if
needed
Android will also destroy and restart your app when screen
orientation changes
If you want transient variable data (member variables) to survive this,
you should implement one more life-cycle method
onSaveInstanceState()
It is called before destroying the application
You get a Bundle object that you can use to store information that should survive
Use methods such as putString() and putInt() to store variable state
When application is recreated, both onCreate() and onRestoreInstanceState() life-
cycle methods will receive same bundle and can use the data in it
If there’s no state information to restore, bundle is null
Remember to always call super() to also store state on View components
76
EXAMPLES ON ONSAVEINSTANCESTATE()
@Override
[Link](savedInstanceState);
[Link]("myDoubleValue", 2.04);
[Link](”myIntegerValue", 1);
// etc.
@Override
[Link](savedInstanceState);
} 77
WHAT HAPPENS WHEN YOU NAVIGATE
FROM ACTIVITY A TO ACTIVITY B?
Activity A's onPause() method executes.
Activity B's onCreate(), onStart(), and onResume() methods execute in
sequence. (Activity B now has user focus.)
Then, if Activity A is no longer visible on screen, its onStop() method
executes.
78
LAB: ACTIVITY LIFE-CYCLE AND STATE
Implement state as member variables and observe how it behaves
when screen orientation changes
Fix the problems using bundle and onSaveInstanceState() method
79
80
INTENTS
INTENTS - MESSAGES
Intent is more or less like an asynchronous message from one part of
application to another
Intent Filter tells that who can handle the message
81
INTENTS
Activity 2
I INTEND to navigate to another view
Service
82
STRUCTURE OF AN INTENT
Intent can contain
Action: a string naming the action to be performed
Data: The URI of the data to be acted on and the MIME type of that data
Alternatively, you can use setComponent(componentName) or setClass(Context, class)
to register specific handler (explicit intent)
83
INTENT RESOLUTION
Two main types of Intents
Explicit – Intent targeted to a specific Activity, used normally only in application’s
internal messaging
Implicit – Intent targeted to any Activity that can handle it, used to activate
components in other applications
84
USING EXPLICIT INTENTS
Explicit intent is specific and will run just that one named intent next,
along with any data you wish to pass
Intent parameters are context (your activity), and target activity/service to invoke
Intent explicitIntent =
new Intent( this, [Link]);
[Link](
"Value1", "This value one for ActivityTwo ");
[Link](
"Value2", "This value two ActivityTwo");
startActivity(explicitIntent);
85
INTENT FILTER
Explicit intents are delivered always, no filters are used
If a component does not define Intent filters, it can only be called by explicit Intents.
86
INTENT MATCHING
All activities that specifies Intents Filters for both
[Link]
[Link]
87
EXAMPLES OF IMPLICIT INTENTS:
public static void invokeWebBrowser(Activity activity) {
Intent intent = new Intent(Intent.ACTION_VIEW);
[Link]([Link]("[Link]
[Link](intent);
}
88
EXAMPLES OF IMPLICIT INTENTS:
public static void call(Activity activity) {
Intent intent = new Intent(Intent.ACTION_CALL);
[Link]([Link]("[Link]
[Link](intent);
}
89
DATA TRANSFER BETWEEN ACTIVITIES
It’s possible to send some data with Intent using
[Link]("MY_VARIABLE_KEY", variableToPass);
90
LAB: USE INTENTS TO NAVIGATE
Create another Activity and use intent to navigate between them
We’ll create a settings view and a forecast view to our weather
application
91
LAB: INTENT FILTERING AND EXISTING
SERVICES
Use intents to trigger existing services
Open web browser to specific address, do a web search with a keyword, open dialer
to dial a number
92
93
NETWORKING – HTTP/JSON
”RAW” HTTP NETWORKING
All networking should be done outside the main GUI thread of an
android application
Using networking in the main thread will cause your app to be
signalled out (killed)
The classical HTTP networking uses Android’s AsyncTask (background
thread) with HttpGetRequest. An example
[Link]
tutorial-6b429d833e28
However, there are better abstractions available like Volley and
Retrofit libraries.
USING VOLLEY FOR HTTP NETWORKING
Volley library is one of the most used abstractions for networking
It implements the state machine for HTTP networking needed by an
app
The complete guide and example:
[Link]
LAB – REQUESTING AND PARSING
HTTP/JSON
Let’s do this in action as an example
We’ll use some open weather API to get the current weather data on
the screen.
© 96
USING DEVICE APIS
MODULE CONTENTS
Accelerometer, Light, Orientation etc. – connect to a system service
WiFi Manager – connect to a system service
Battery Status – register to a Broadcast Intent
HARDWARE SENSORS IN ANDROID
Android SDK provides access to raw data from sensor service via
SensorManager object
© 107
APPLICATION SECURITY
SECURITY AND PERMISSIONS
Android is a multi-process system
each application (and parts of the system) runs in their own processes
Most security between applications and the system is enforced at the process level
through standard Linux facilities, such as user and group IDs that are assigned to
applications
Each Android package (.apk) file installed on the device is given its own unique Linux
user ID, creating a sandbox for it and preventing it from touching other applications
(or other applications from touching it). This user ID is assigned to it when the
application is installed on the device, and remains constant for the duration of its life
on that device.
109
SECURITY ARCHITECTURE
By default, no application has permission to perform any operations
that would adversely impact other applications, the operating system,
or the user
This includes reading or writing the user's private data (such as contacts or e-mails),
reading or writing another application's files, performing network access, keeping the
device awake, etc.
110
REQUESTING PERMISSIONS AT RUN TIME
From Android 6.0 (API 23), permissions are divided into dangerous
and normal permissions
All permissions are listed in project’s manifest file but dangerous
permissions are granted by the user at run-time
Before Android 6.0, all permissions were granted by user at
installation phase only
Operations with dangerous permissions deal somehow with user’s
privacy or private data
© 111
DANGEROUS PERMISSIONS
Permission Group Permissions
CALENDAR •READ_CALENDAR
•WRITE_CALENDAR
CAMERA •CAMERA
CONTACTS •READ_CONTACTS
•WRITE_CONTACTS
•GET_ACCOUNTS
LOCATION •ACCESS_FINE_LOCATION
•ACCESS_COARSE_LOCATION
MICROPHONE •RECORD_AUDIO
PHONE •READ_PHONE_STATE
•CALL_PHONE
•READ_CALL_LOG
•WRITE_CALL_LOG
•ADD_VOICEMAIL
•USE_SIP
•PROCESS_OUTGOING_CALLS
SENSORS •BODY_SENSORS
SMS •SEND_SMS
•RECEIVE_SMS
•READ_SMS
•RECEIVE_WAP_PUSH
•RECEIVE_MMS
STORAGE •READ_EXTERNAL_STORAGE
•WRITE_EXTERNAL_STORAGE
HANDLING RUN-TIME PERMISSIONS IN CODE
Sensitive operations with dangerous permissions should always be
checked (and permission granted) at run-time
Sensitive API call without permission causes SecurityException
Run-time check applies to Android 6.0 (API level 23) onwards
The version can also be checked run-time:
if ([Link].SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission([Link].READ_CALL_LOG) !=
PackageManager.PERMISSION_GRANTED) {
[Link](this,
new String[]{[Link].READ_CALL_LOG}, 0);
return;
}
}
© 113
HANDLING RUN-TIME PERMISSIONS IN CODE
[Link]
© 114
LOCATION API
INTRODUCTION TO LOCATION BASED
SERVICES
Location information is almost a requirement for cell phones these
days
Several different ideas already seen for applications make the
feature exciting
Not only navigation but social applications, security, outdoor activities…
What is not yet invented?
Google has made a large effort on creating not only world wide
maps
Satellite images covering almost the whole globe
Traffic information
Street View
Navigation (currently only in the USA)
Latitude service
USING THE GLOBAL POSITIONING
SERVICES (GPS)
Android SDK provides a way to use GPS as part of application
Optional way of getting more coarse location data exist
Using WiFi and GSM location
Can be battery consuming and slower
<uses-permission
android:name="[Link].ACCESS_FINE_LOCATION" />
<uses-permission
android:name="[Link].ACCESS_COARSE_LOCATION" />
PROVIDE A LOCATIONLISTENER
© 122
TESTING LOCATION WITH EMULATOR