0% found this document useful (0 votes)
73 views

Android Development

This document provides an overview of a mobile application development course. The course will refresh or teach Java programming skills and teach how to develop Android applications using Java. It will cover Java programming fundamentals like object-oriented programming, classes, methods, constructors, variables and data types. It will also cover conditional statements and variable scope. The goal is to learn the skills needed to develop Android apps in Java.

Uploaded by

Mirko Mekonen
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Android Development

This document provides an overview of a mobile application development course. The course will refresh or teach Java programming skills and teach how to develop Android applications using Java. It will cover Java programming fundamentals like object-oriented programming, classes, methods, constructors, variables and data types. It will also cover conditional statements and variable scope. The goal is to learn the skills needed to develop Android apps in Java.

Uploaded by

Mirko Mekonen
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 114

Mobile Application Development

About the course

- Refresh/learn Java programming


- Learn about mobile architecture
- Use Java to develop Android application
Java programming
Intro

Why program in Java?

- Good performance
- Platform independent
- Effectiveness (a lot of powerful features)
- Excellent documentation
- Excellent and free tools
- Object-oriented
Object-oriented Programming

Advantages Example: a contact in your phone


Holds:
- Divide and conquer - Name
- Clean code - Number
- Email
- Easy to expand
- ...
- Most popular trend Possible actions:
- Call
- Email
- Delete
- Edit
- ...
Objects

- Store information in fields To execute action on object in code:


- Can execute actions
object.doSomething();
- Has specific information and actions
Class

- Blueprint of the object public class Car {


- Tells the compiler how to construct object private int tires;
- Class defines which attributes an object has private String licensePlate;
(in this example tires and licensePlate)
public Car() {
- Both object fills in the values
tires = 4;
licensePlate = “ABC-123”;
}

- An object is an instance of a class public void removeTire() {


tires = tires - 1;
}
}
Method

- Defines an action of an object public class Car {


- Can have parameters private int tires;
- Can return a result private String licensePlate;

public Car() {
tires = 4;
licensePlate = “ABC-123”;
In this example: }
Return type = void
public void removeTires(int amount) {
Parameters = amount tires = tires - amount;
}
}
Constructor

- Special method public class Car {


- Creates the object private int tires;
- Sets parameters private String licensePlate;
- Can have parameters
public Car() {
- Does not return anything tires = 4;
licensePlate = “ABC-123”;
}

public void removeTire() {


tires = tires - 1;
}
}
Access modifiers

- Define who can access the method or field public class Car {
- Public: Everyone private int tires;
- Private: only within the same object private String licensePlate;
- Protected: only within same object or
public Car() {
subclasses tires = 4;
licensePlate = “ABC-123”;
}

public void removeTire() {


- Can be used for classes, methods, tires = tires - 1;
constructors and fields }
}
public class Car {

Everything together private int tires;


private String licensePlate;
now private String carColor;

public Car(String color) {


A class is the blueprint of an object tires = 4;
licensePlate = “ABC-123”;
carColor = color;
An object contains a constructor, }
fields and methods
public void removeTire() {
A constructor can have parameters tires = tires - 1;
but does not have a return type }

A method can have parameters and public int getTires() {


return tires;
can have a return type
}

Access modifiers define who can public void setLicensePlate(String plate) {


access a class, method, constructor or licensePlate = plate;
field }
}
Variable types

- String: store text public class Car {


- int: store number without decimals private int tires;
- double: store number with 2 decimals private String licensePlate;
- float: store number with 7 decimals
public Car() {
- boolean: store true or false tires = 4;
- null: contains nothing licensePlate = “ABC-123”;
- Also byte, char, short, long }

public void removeTire() {


Assignment of values: tires = tires - 1;
}
licensePlate = “ABC-123”; }

Where to store What to store


public class Car {

private tires;
private String licensePlate;
Small test private String carColor;

public Car(String color) {


There are 5 errors in the code on the tires = 4;
licensePlate = “ABC-123”;
right
carColor = color
}

public int removeTire {


tires = tires - 1;
}

public int getTires() {


return tires;
}

public void setLicensePlate(String plate) {


licensePlate = Plate;
}
Arithmetic Operators

int result = 0;
- Example: result = 7 - 2;
+ Example: result = 7 + 2;
/ Example: result = 7 / 2;
* Example: result = 7 * 2;
% Example: result = 7 % 2;

Shorthand notation:
result += 2;
result += 2;
result /= 2;
result *= 2;
result %= 2;
Unary Operators

int result = 0;
- Example: result = result - 2;
+ Example: result = result + 2;
-- Example: result--;
++ Example: result++;

boolean result = false;


! Example: result = !result;

Important: unary operators are executed before arithmetic operators.


String operations

What does this do:

String something;

something += “Hello”;
something += “ world!”;

And this:

something += 7;

Or this:

String something = “Hello” + “ class!” + “ I’m a long string!”;


Conditional statements

What if you want code to run only when a public class Car {
condition is met? ...

→ Use IF-statement public Car() {


...
if(condition) { }
code... public void changeTire() {
} else { if(tires >= 4) {
code… tires = tires - 1;
} } else {
tires++;
}
}
}
Variable scope

A variable only exists within its scope public class Car {

private String licensePlate;


What is scope?
public Car() {
Short answer: between brackets { and } ...
}
→ Local variables
public void changeTire() {
int myTires= 5;
}

public int getTires() {


return myTires;
}
}
Introduction
● Android is the world’s most popular mobile platform. At the last count,
there were over one billion active Android devices worldwide, and that
number is growing rapidly.
● Android is a comprehensive open source platform based on Linux and
championed by Google.
● It’s a powerful development framework that includes everything you need
to build great apps using a mix of Java and XML. What’s more, it enables
you to deploy those apps to a wide variety of devices—phones, tablets and
more.
Android

● It contains a linux-based Operating System, middleware and key mobile


applications.
● It is currently used in various devices such as mobiles, tablets, televisions
etc.
Mobile Architecture
87.7%
87.7% of mobile devices run Android

12.1% of mobile devices run Apple’s iOS

0.2% of mobile devices run a different operating system


Android devices, small computers

- Hardware:
- CPU
- RAM
- GPU
- Storage
- Battery
Android devices, small computers
Android devices, small computers

- Software:
- Let’s have a look!
Android Update
Adoption
● Data from 17/01/2018
● Marshmallow > Nougat > Lollipop
● Oreo: 0.7% !

● ←→ Apple: 59% for IOS11


● Version 9.0pie-28-
● Version 10q- 29
● Version 11R-30

Problem: update flow

● Android creates new version


● Chipmaker and phone manufacturer
adjust custom ROM
● Android checks updates ROM
● Android pushes update
Updated
Distribution
● 23 Nov 2021
● Android 9 pie=18.2%
● Android 8 oreo 13.7%
● Android 7 $7.1 Nougat= 6.3%
● Android 6 Marshmallow =5.1%
● Android 5Lollipop=3.9%
● Android 4.4 kitkat=1.4%
● Android 4.1 jelly bean=0.6%
● Based on the data android
10=runining on 26.5% devices
● Android 11=24.2% devices
Android platform Architecture

● Applications
● Application framework
● Libraries
● Android runtime
● Linux Kernel
Applications

● Android comes with a set of core applications such as Contacts, Calendar,


Maps, and a browser.
Application Framework

● Android framework includes Android API's such Activity, window, content


provider, view sysstem, package, telephony, resource, location, notification
manager
● When you build your apps, you have access to the same APIs used by the
core applications. You use these APIs to control what your app looks like
and how it behaves.
Android runtime

● The Android runtime comes with a set of core libraries that implement
most of the Java programming language. Each Android app runs in its own
process.
● In android runtime, there are core libraries and DVM (Dalvik Virtual
Machine) which is responsible to run android application. DVM is like JVM
but it is optimized for mobile devices. It consumes less memory and
provides fast performance.
Android Emulator

● Android Emulator is used to run, debug and test the android application. If
you don't have the real device, it can be the best way to run, debug and test
the application.
● It uses an open source processor emulator technology called QEMU.
Dalvik Virtual Machine | DVM

● The Dalvik Virtual Machine (DVM) 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 VM. Multiple class files are converted into one dex file.

● The javac tool compiles the java source file into the class file.
● The dx tool takes all the class files of your application and generates a
single .dex file. It is a platform-specific tool.
● The Android Assets Packaging Tool (aapt) handles the packaging process.
Linux Kernel

● Display driver, camera driver, flash memory driver, Binder(IPC) driver,


keypad driver, wifi driver, audio driver, power management
● It is the heart of android architecture that exists at the root of android
architecture.

● Underneath everything else lies the Linux kernel. Android relies on the
kernel for drivers, and also core services such as security and memory
management.
Libraries/Middleware

● Surface manager, media framework, SQlite, openGL, FreeType, webkit, SGL,


SSL, libc
● Underneath the application framework lies a set of C and C++ libraries.
These libraries get exposed to you through the framework APIs.
Layouts

● So what makes up a typical Android app?


● A typical Android app is comprised of one or more screens. You define
what each screen looks like using a layout to define its appearance.
● Layouts are usually defined using XML, and can include GUI components
such as buttons, text fields, and labels.
Cont..

● Layouts only define the appearance of the app. You define what the app
does by writing Java code. A special Java class called an activity decides
which layout to use and tells the app how to respond to the user. As an
example, if a layout includes a button, you need to write Java code in the
activity to define what the button should do when you press it.
● Layouts tell Android what the screens in your app look like and Activities
define what the app should do.
Cont..

● In addition to Java code and layouts, Android apps often need extra
resources such as image files and application data. You can add any extra
files you need to the app. Android apps are really just a bunch of files in
particular directories. When you build your app, all of these files get
bundled together, giving you an app you can run on your device.
Android Updates: Project Treble
Android devices, small computers

The future:
- More processing power
- Smaller
- Cheaper, maybe
Demo: Android Studio
Assignment for tomorrow: revise slides of today, install Android Studio and successfully run a
template project.

1. Install Android Studio (unzip and run)


2. Copy the SDK folder contents to your SDK folder (unzip and copy)
Location: C:\Users\<yourname>\AppData\Local\Android\SDK
3. Unzip gradle in your program files. Run Android Studio and go to File → Settings → Build,
execution and deployment → Gradle. Choose ‘Use local gradle distribution’ and point it to where
you extracted gradle.
4. Take your android phone, go to settings → about phone → tap build number 7 times (no joke)
until you see that you are an android developer.
5. Then on your phone go to settings → Developer options and check USB debugging.
6. Connect your phone to your pc and install your drivers (requires internet)
Mobile Applications
Android apps

What are they made of: |core building blocks


- Activities
- Views
- Intents
- Services
- Content providers
- Fragments and Androidmanifest
Activities

- Fundamental part of app


- Contain the user interface
- Provide logic to UI
- An activity is a class that represents a single screen. It is
like a Frame in AWT.
Activities
Activities
Activities
Resources

- Source files
- Resources
- Drawables
- Layouts
- Mipmaps
- Values
- Menu
- Animations
- Colors
- Fonts
Resources: drawables

- Icons (but not icon of your app)


- Pictures
- Vector images
- Custom shapes
- ...
Resources: layouts

- Filetype: XML
- Key-value pairs
- Important: id
- Anything is possible
Resources: layouts

- Filetype: XML
- Key-value pairs
- Important: id
- Anything is possible
Resources: values

- Filetype: XML
- Example: store predefined
Strings

- Why useful:
- Easy translation
- Easy reuse
- Clean code
Lifecycle
Lifecycle: remember
Lifecycle

- Useful to do certain actions on restart, stop,


pauze…
- Reduce power loss
- Reduce memory leaks
Navigation
Activities

- Backbone of the app


- Contain a layout
- Provide interaction with user
- Provide interaction with back-end
Activities: Java code
Activities: layout
Activities: interaction

How to do something when we press a button?

→ onClick listener
- Listens all the time until the user presses the button
- Run some code when the click is detected
Activities: interaction

onClickListener, 2 ways of defining:


- In code:

- In layout file (XML):

AND
Activities: navigation

How to go from one activity to another?


Activities: navigation

Intents
Cont..

Intent is used to invoke components. It is mainly used to:


● Start the service
● Launch an activity
● Display a web page
● Display a list of contacts
● Broadcast a message
● Dial a phone call etc.
Activities: intents

An intent allows us to:


- Start a new activity
- Open your web browser
- Open your email app
- Open your music player
- Pass data to other activities
Activities: intents

- Implicit
- Android device knows how to handle the
intent, you don’t tell the device what to do
- Example: opening a webpage
- Explicit
- You tell the device what to do
- Example: starting a new activity
Activities: implicit intent
Activities: explicit intent
Activities: intents

In code:
- Explicit intent

- Implicit intent
RecyclerView

● View
A view is the UI element such as button, label, text field etc. Anything that you
see is a view.
- We want to display a very long list of items
- Problem: a lot of memory needed
- Solution: RecyclerView
- Only keeps in memory what is on the screen + some items before and some
after
- Needs an adapter to handle the data
RecyclerView
RecyclerView: adapter

- Handles the information (list)


- Handles the creation of the views of the list items
- Handles the interaction with the user
- Contains ViewHolder
RecyclerView: adapter  ViewHolder

- ViewHolder provides link with layout


Toast

- Easy way to show information for a moment


Service

● Service is a background process that can run for a long time.


● There are two types of services local and remote. Local service is
accessed from within the application whereas remote service is accessed
remotely from other applications running on the same device.
Con. Provider, Frag and androidmanifest

● Content Provider
● Content Providers are used to share data between the applications.
● Fragment
● Fragments are like parts of activity. An activity can display one or more
fragments on the screen at the same time.
● AndroidManifest.xml
● It contains informations about activities, content providers, permissions
etc. It is like the web.xml file in Java EE.
AndroidManifest.xml file in android

● The AndroidManifest.xml file contains information of your package, including components of


the application such as activities, services, broadcast receivers, content providers etc.

It performs some other tasks also:

○ 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 provides profiling and
other informations. These informations are removed just before the application is
published etc.
Option menu

- Provide quick actions


- Part of the toolbar
- Uses a menu.xml file
Option menu

- To create menu in code:


Option menu

- To create menu in code:


Storage
Storage

- OnSaveInstanceState
- Shared Preferences
- Internal Storage
- External Storage
- SQLite Database
- Network Connection
Storage: onSaveInstanceState

● For storing Activity state


● Needs to be put in bundle
● Automatically used on View elements
○ BUT need android:id!
● Can also be used to Store non-View
complex values (e.g. objects)
Storage: onSaveInstanceState

Source: https://inthecheesefactory.com/blog/fragment-state-saving-best-practices/en
Storage: Shared Preferences

- Stored on device
- Public or private
- Key-value pairs
- Read & write
Storage: Shared Preferences

To store a value in Shared Preferences:

1. SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);


2. SharedPreferences.Editor editor = settings.edit();
3. editor.putBoolean("silentMode", mSilentMode); //mSilentMode = boolean
4. editor.apply(); or editor.commit();
Storage: Shared Preferences

To read a value in Shared Preferences:

1. SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);


2. boolean silent = settings.getBoolean("silentMode", false);
Storage: Internal Storage

- Stored on device (Flash memory)


- Public or private
- Files
- Read & write
- Can be used for cache
Storage: Internal Storage

To write to the internal storage:

1. FileOutputStream fos = openFileOutput(FILENAME,


Context.MODE_PRIVATE);
2. fos.write(string.getBytes());
3. fos.close();
Storage: External Storage

- Stored on device (SD card)


- Public or private
- Files
- Read & write
- Can be used for cache
- Needs permission
Storage: External Storage

To write to the external storage:

1. File file = new File(Environment.getExternalStoragePublicDirectory(


Environment.DIRECTORY_PICTURES), mPicture);
Storage: SQLite Database

- Stored on device (databaseName.db)


- Private
- Database records
- Read & write
- Persistency
- New: Room library
Storage: SQL?

SELECT * FROM employees;


SELECT * FROM employees WHERE PersonID = 5;

DELETE FROM employees WHERE LastName LIKE “Anand”;

INSERT INTO employees VALUES (“Geuens”, “Jonas”);

UPDATE employees SET LastName = “Gielis” WHERE PersonID = 2


Storage: SQLite Database

To write to the SQLite database:

Room demo
Storage: Room database

Summary:
- Uses SQLite database
- Reduces code needed
- Limited (for now)
Server

● Cloud Storage (e.g. Firebase)


● Storing data online
● Advantages
○ Data (almost) always recoverable
○ Usable on multiple devices
○ High scalability
Summary: important!
Option Type of data Save duration

OnSaveInstanceState Key/value (complex values) Until app is closed

Shared Preferences Key/values (primitives) Until app uninstalled

SQLite DB Organized, more complex data Until app uninstalled

Internal/external Storage Multimedia/Large files Explicetely removed by user

Server (~Firebase) Data between multiple instances Always


Background Tasks
Threading
Multithreading on Android? Yes Please!

● Why multithreading?
○ Used to divide download/calculation load between threads

○ In Androids: to keep blocking actions from the main thread ( = UI Thread!)

● Common uses: downloading images, lists, users, … Anything really! But be


aware that starting and finishing a thread costs precious time. So be sure
that the time spent on the thread is long enough to compensate.
Demo
Geofences
Geofences
Notifications
Definition

“A notification is a message that Android displays outside your


app's UI to provide the user with reminders, communication
from other people, or other timely information from your app. “
Anatomy
1. Small icon: This is required and set with
setSmallIcon().
2. App name: This is provided by the system.
3. Time stamp: This is provided by the system but
you can override with setWhen() or hide it with
setShowWhen(false).
4. Large icon: This is optional (usually used only
for contact photos; do not use it for your app
icon) and set with setLargeIcon().
5. Title: This is optional and set with s
etContentTitle().
6. Text: This is optional and set with
setContentText().
Customizable

Actions, expandable, groupable, …

See developer.android.com/guide/topics/ui/notifiers/notifications.html
for more information
Set a notification channel
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel("my_channel_01",
"Channel1",NotificationManager.IMPORTANCE_LOW);
// Configure the notification channel.
mChannel.setDescription("These are the main notifications");
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setLightColor(Color.RED);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
Showing a basic notification

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,


"my_channel_01") .setSmallIcon(R.drawable.ic_notification_icon)
.setContentTitle("Hello Class")
.setContentText("This is the content")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);


// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, mBuilder.build());

You might also like