SlideShare a Scribd company logo
pUp3EkaP
Yarkoni
IronSource
Android Academy
Women Techmakers
~ 1500 members Largest Android Active Community
What Do We Do?
●Android Fundamentals
●Android UI / UX
●Community Hackathon
●Android Performance
●Mentors Program
Online Lessons
Important:
Watch online lesson
before the meetup!
- Our course:
“Developing Android
Apps”
goo.gl/u1pxZv
- Optional: Nano Degree
- Optional: “Android Basics” courses
Lecture #2  threading, networking & permissions final version #2
The Course Plan
- Online lesson @ home
- Lecture @ Campus
- Hands-on @ Campus
- Questions @ Facebook
Yarkoni
Android Leader
Ironsource
Android Academy Staff
Yonatan Levin
Google Developer Expert &
Android @ Gett
Britt Barak
Android Leader
Figure8
Yossi Segev
Android Developer
Crave
Mentors program
Community Mentors
Refael “Hero” Ozeri
Lecture #2: Threads,
Networking & Permissions
Understanding the concept of
Multi Threading
What’s For Today?
● Logging
● Processes
● Threads
● Android Thread Abstractions
● Permissions
Logging
Definition:
A logfile is a file that records either events that occur in an
operating system or other software runs.
Logging
Definition:
A logfile is a file that records either events that occur in an
operating system or other software runs.
*.java
Log.d(“MY-APP’S-TAG”, "message");
Logging
Logging
Why is logging important?
Good Practice.
Constant monitoring.
Helps debug fast without the need for breakpoints.
In the context of this lesson: Thread awareness.
Don’t leave logs open in production.
Logging - Where can I see it?
HERE
Logging - levels
Log levels
verbose (all)
debug
info
warn
error
Great Log Wrapper
Great Log Wrapper
Code with filter !
What’s For Today?
● Logging
● Processes
● Threads
● Android Thread Abstractions
● Permissions
Reminder
Java.
Linux.
Processes
(The app)
Processes - Android Priority
If system is stressed and needs to clear memory - the process will
be killed together with its’ threads.
ProcessProcess
Processes - Android Priority
1.Foreground.
2.Visible.
3.Service.
4.Background.
5.Empty.
Processes - Android Priority
1.Foreground.
2.Visible.
3.Service.
4.Background.
5.Empty.
Processes - Android Priority
1.Foreground.
2.Visible.
3.Service.
4.Background.
5.Empty.
Processes - Android Priority
1.Foreground.
2.Visible.
3.Service.
4.Background.
5.Empty.
Processes - Android Priority
1.Foreground.
2.Visible.
3.Service.
4.Background.
5.Empty.
Processes - Android Priority
1.Foreground.
2.Visible.
3.Service.
4.Background.
5.Empty.
Processes - Android Priority
You’re most important if you are affecting the user’s experience.
You can never be lower than what you are serving.
Processes - CPU Time Split
Foreground & Visible -
90%
Service & Background & Empty -
10%
Threads
Threads
Like Linux a process is created with a single
Thread of execution.
Process
Thread A
Threads - Thread of Execution
Thread of execution.
CPU Core
Thread of execution
Thread A
Thread B
Thread C
Threads - Thread of Execution
Thread of execution.
CPU Core
Thread of execution
Thread A
Thread B
Thread C
Threads - Thread of Execution
Thread of execution.
CPU Core
Thread of execution
Thread A
Thread B
Thread C
Threads
Java & Android Threads
Moderate to large operation.
Not tied to activity lifecycle.
Reusable.
Number 1 cause of memory leak.
Threads
Java & Android Threads
Moderate to large operation.
Not tied to activity lifecycle.
Reusable.
Number 1 cause of memory leak.
I’m
Collector,
Garbage Collector
Never have a Non-Static Inner Class
Always an Inner Class be Static
Processes vs. Threads
Processes
Separate address space.
Communicate via IPC.
Threads
Share address space.
Communicate using handlers.
Processes vs. Threads
Processes
Separate address space.
Communicate via IPC.
Threads
Share address space.
Communicate using handlers.
Threads - Memory
Threading isn’t memory safe.
Thread A
Thread B
Memory
Write
Write
???
Threads - Memory
UI elements are not “Thread Safe”.
Thread A
Thread B
Button Button
Button
Create Update
Update
Start a new Thread and pass it a UI element
Manipulate UI element from off Thread
CRASH
CRASH
What is the Thread for UI elements?
Solution
Main Thread
Main Thread
UI thread responsibilities:
Dispatches events.
Draws on screen.
Handles user input.
Process
What’s On The Main Thread?
Main Thread (UI Thread)
System Event Input Event Service Application UI Drawing
Example: Action lifecycle on UI thread
User presses on a
button
UI Thread
dispatches touch
event to the
widget
Widget sets its
pressed state
Posts an
invalidate to the
request queue on
UI thread
The UI thread
dequeues the
request and
notifies widget to
redraw itself
Reminder - Blocking Action Definition
A Thread that is blocked is waiting for a completion of an operation.
Process
What’s On The Main Thread?
Main Thread (UI Thread)
System
Event
UI
Drawing
Your code!~!!!~!
16ms 16ms 16ms
UI
Drawing
UI
Drawing
16ms 16msDropped Frame
We Have A Winner!
Smooth
Motion
60
No
Difference
60+
Flip Book
12
Movies
Frames Per Second
Fluid Motion
24
+effects
Smooth
Motion
60
Lecture #2  threading, networking & permissions final version #2
What happens if you delay the UI thread for
more than 16ms?
At 60Hz it takes 16.67ms to render a frame
therefore if you take up those 16.67 a frame
will be dropped.
Main Thread - 2 rules
Do not block the UI thread.
Do not access the UI toolkit from non UI thread.
Main Thread
What happens if you block the UI thread for more than 5 seconds?
Main Thread
What happens if the app is slow to respond?
Do you think users will say:
“Oh it’s my slow connection”
“I shouldn’t have scrolled so fast”
“Silly me wanting to see the whole image right when the screen opens”
Lecture #2  threading, networking & permissions final version #2
We’ve established it’s the
developer’s job
to offload long operations from the
Main Thread
to an a Non UI Thread
Off Thread
Off Thread - Usages
Database operations.
Networking operations.
Long running operations.
Android has your back!
Framework Abstractions
AsyncTask
Helps get work off/on the UI thread.
HandlerThread
Dedicated thread for API callbacks.
ThreadPool
Running lots of parallel work.
AsyncTask
AsyncTask
Fit for short operations.
Fit for operations which require UI Manipulation at the end.
Unaware of activity life cycle.
Single time execution.
Serial vs. Concurrent for all AsyncTasks.
Has a state and can be cancelled.
AsyncTask
WorkerThread
doInBackground ()
onPreExecute ()
MainThread
onPostExecute ()
AsyncTask
WorkerThread
doInBackground ()
onPreExecute ()
MainThread
onProgressUpdate ()
onPostExecute ()
publishProgress()
Lecture #2  threading, networking & permissions final version #2
Lecture #2  threading, networking & permissions final version #2
How to Create and Start an AsyncTask
AsyncTask always returns on Main Thread
MainActivity.java
MainActivity.java
MainActivity.java
Lecture #2  threading, networking & permissions final version #2
Before we go let’s see how to get back!
Activity.runOnUiThread(Runnable)
View.post(Runnable)
BroadcastReceiver
Main Thread (UI Thread)
Thread A
Thread B
HandlerThread
Reminder
Main Thread (UI Thread)
Process
System
Event
UI
Drawing
Your code!~!!!~!
16ms 16ms 16ms
UI
Drawing
UI
Drawing
16ms 16msDropped Frame
Worker Thread
We don’t want to block the main thread so we create a worker
thread.
Main Thread (UI Thread)
Thread ATask Task Complete
Worker Thread
Main Thread (UI Thread)
Thread ATask 0 Task Complete
Task 1
Task 2
Task 3
How can we create a thread capable of
handling multiple consecutive tasks?
Worker Thread - Recipe
Handler + Looper + Thread = HandlerThread
Worker Thread - Recipe
1.Create a Thread.
2.Attach a Looper to a Thread.
3.Get the Handler from the Looper.
4.Use Handler to send messages (tasks).
Handlers
Schedule task for the future.
Enqueue task for another thread.
Handlers - Methods
handler.post();
handler.postAtFrontOfQueue();
handler.postDelayed();
handler.postAtTime();
MainActivity.java
MainActivity.java
Looper
Class used to run a message loop for a thread. Threads by default do
not have a message loop associated with them; to create one, call
prepare() in the thread that is to run the loop, and then loop() to have
it process messages until the loop is stopped.
A Deeper Look
Main Thread (UI Thread)
Looper
Message queue
Handler
Handle
MSG
Send
MSG
Process
Lecture #2  threading, networking & permissions final version #2
Lecture #2  threading, networking & permissions final version #2
Sending a message to a Thread
Putting it all together
Threads Handlers and Looper
Handlers
Handlers
Handlers
Handlers
One more thing - Don’t forget to quit!
HandlerThread.quit();
Lecture #2  threading, networking & permissions final version #2
Thread Priority
Thread Priority
THREAD_PRIORITY_LOWEST = 19
THREAD_PRIORITY_BACKGROUND = 10
THREAD_PRIORITY_LESS_FAVORABLE = +1
THREAD_PRIORITY_MORE_FAVORABLE = -1
THREAD_PRIORITY_URGENT_AUDIO = -19
Threads created on foreground inherit foreground priority = -2
Thread Priority - Higher means Lower
Why URGENT_AUDIO is the highest priority (-
19)?
Sound delay is even more noticeable than
frame skipping.
Does this mean I should handle all the
priorities of every Thread created?
Thread Pool Executor
Thread Pool executor
Handles Spinning.
Handles Load Balancing.
Handles killing Threads when they are idle.
Thread Pool executor
BlockingQueue
Thread A
Thread B
Thread C
ThreadPool
Thread Pool executor
BlockingQueue
Thread A
Thread B
Thread C
ThreadPool
Thread Pool executor
BlockingQueue
Thread A
Thread B
Thread C
ThreadPool
Thread Pool executor
BlockingQueue
Thread A
Thread B
Thread C
ThreadPool
Thread Pool executor
BlockingQueue
Thread A
Thread B
Thread C
ThreadPool
Thread Pool executor
BlockingQueue
Thread A
Thread B
Thread C
ThreadPool
Thread Pool executor
BlockingQueue
Thread A
Thread B
Thread C
ThreadPool
Thread Pool executor
BlockingQueue
Thread A
Thread C
ThreadPool
Thread Pool Executor
How many threads is a good number of threads?
So if I want to get more work done I should
create more threads.
By induction: Infinite Threads!
Thread Pool executor
Adjust to number of cores.
64kb per thread.
ThreadPool Implementation
Passing a Task to the ThreadPool
Lecture #2  threading, networking & permissions final version #2
IntentService
Example
Intent
-?-
Hard work
Intent Hard work
Intent Hard work
IntentService
Extends Service.
Is killed by System when queue is empty.
Can’t be interrupted.
Systrace
What’s For Today?
● Logging
● Processes
● Threads
● Android Thread Abstractions
● Permissions
Content
It’s everything the user sees and interacts.
Where can we get content?
Static content.
Locally on the phone.
Remote server.
Content
It’s everything the user sees and interacts.
Where can we get content?
Static content.
Locally on the phone.
Remote server.
Top apps examples: FB, SnapChat, Instagram.
Reminder
Database operations.
Networking operations.
Long running operations.
Reminder
Database operations.
Networking operations.
Long running operations.
Networking requests
Require the following permission:
Cannot be done on the MainThread:
Permissions
Permissions
Android is a privilege-separated operating system, in which each
application runs with a distinct system identity (Linux user ID and
group ID). Parts of the system are also separated into distinct
identities. Linux thereby isolates applications from each other and
from the system.
Androidmanifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<!-- external storage for saving downloaded files -->
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- for performing installing/uninstalling apps -->
<uses-permission
android:name="android.permission.INSTALL_PACKAGES"/>
Permissions - Level
Protection level
Normal - (flashlight, internet, NFC)
Dangerous - (Read / write external storage)
Signature - (defined per use case)
SigantureOrSystem - (Install 3rd party applications)
Application defined permission.
Permissions - Normal vs. Dangerous
Normal: Bluetooth, Internet, NFC.
Dangerous: read/write external storage, contacts, location.
What is the key difference?
Permissions - Android 6.0
TargetSDKVersion
If you wrote 24 you will crash if not handled.
If you wrote <24 you will be spared.
Permissions - Android 6.0
Still define permissions in AndroidManifest.xml
protectionLevel = normal are granted by default.
protectionLevel = Dangerous require you
ask at runtime.
Request 1 time without consequence.
Permissions - Android 6.0
Still define permissions in AndroidManifest.xml
protectionLevel = normal are granted by default.
protectionLevel = Dangerous require you
ask at runtime.
Request 1 time without consequence.
Permissions - Vertical & Horizontal views
Auditing vertically/Horizontally.
MainActivity.xml
MainActivity.xml
Network Requests
(Connecting to the Cloud)
Network requests
Android include many network programming classes.
java.net (socket, URL, etc.)
org.apache (HttpRequest, HttpResponse, etc.)
android.net (AndroidHTTPClient, URI, AudioStream, etc.)
Network requests
Under the hood Android’s HTTP libraries use java socket API.
Socket definition: a software endpoint that can create a bi-directional
communication link between software processes.
Socket SocketTCP/IP
Network requests - InputStream
Network requests - InputStreamReader
Network requests - BufferedStreamReader
Network requests - HttpURLConnection
What is the connection?
build.gradle
build.gradle
MainActivity.java
Homework:
1.Go over AsyncTask, IntentServices,
Handlers, Threads code.
2.Watch “Create New Activities and
Navigate Apps with Intents”
3.Start developing Sunshine.
34th floor
Drive home safe
See you next Sunday!

More Related Content

PDF
10 ways to improve your Android app performance
PDF
Asynchronous Programming in Android
PDF
Learn java in one day and learn it well 2016 jamie chan
PDF
Lecture #0 Intro
PPTX
Lecture #4 activities &amp; fragments
PPTX
Lecture #1 Creating your first android project
PPTX
Advanced #3 threading
PPTX
Efficient Android Threading
10 ways to improve your Android app performance
Asynchronous Programming in Android
Learn java in one day and learn it well 2016 jamie chan
Lecture #0 Intro
Lecture #4 activities &amp; fragments
Lecture #1 Creating your first android project
Advanced #3 threading
Efficient Android Threading

Similar to Lecture #2 threading, networking &amp; permissions final version #2 (20)

ODP
Android App Development - 07 Threading
PPT
Android - Thread, Handler and AsyncTask
PDF
Intake 38 12
PPTX
Advanced #2 threading
PDF
Multithreading Introduction and Lifecyle of thread
PPT
Tech talk
PPTX
Thread_Handlers_and_Executors_Presentation.pptx
PDF
[Android] Multiple Background Threads
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
PPTX
Threads in Mobile Application Development.pptx
PDF
Internals of AsyncTask
PPTX
Introduction to Android - Session 3
PPT
Java Multithreading
PPT
Java multithreading
PDF
Android Threading
PDF
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
PPTX
Performance #6 threading
PPT
PPTX
Android Thread
PDF
Android concurrency
Android App Development - 07 Threading
Android - Thread, Handler and AsyncTask
Intake 38 12
Advanced #2 threading
Multithreading Introduction and Lifecyle of thread
Tech talk
Thread_Handlers_and_Executors_Presentation.pptx
[Android] Multiple Background Threads
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Threads in Mobile Application Development.pptx
Internals of AsyncTask
Introduction to Android - Session 3
Java Multithreading
Java multithreading
Android Threading
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Performance #6 threading
Android Thread
Android concurrency
Ad

More from Vitali Pekelis (20)

PDF
Droidkaigi2019thagikura 190208135940
PDF
Droidkaigi 2019
PPTX
Google i o &amp; android q changes 2019
PPTX
Android Q 2019
PPTX
Advanced #6 clean architecture
PPTX
Advanced #4 GPU & Animations
PDF
Advanced #2 networking
PPTX
Advanced #1 cpu, memory
PPTX
All the support you need. Support libs in Android
PPTX
How to build Sdk? Best practices
PPTX
Di &amp; dagger
PPTX
Android design patterns
PPTX
Mobile ui fruit or delicious sweets
PPTX
Lecture #4 c loaders and co.
PPTX
Session #4 b content providers
PPTX
Advanced #2 - ui perf
PDF
Android meetup
PPTX
Android design lecture #3
PPTX
From newbie to ...
PDF
Working better together designers &amp; developers
Droidkaigi2019thagikura 190208135940
Droidkaigi 2019
Google i o &amp; android q changes 2019
Android Q 2019
Advanced #6 clean architecture
Advanced #4 GPU & Animations
Advanced #2 networking
Advanced #1 cpu, memory
All the support you need. Support libs in Android
How to build Sdk? Best practices
Di &amp; dagger
Android design patterns
Mobile ui fruit or delicious sweets
Lecture #4 c loaders and co.
Session #4 b content providers
Advanced #2 - ui perf
Android meetup
Android design lecture #3
From newbie to ...
Working better together designers &amp; developers
Ad

Recently uploaded (20)

PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Transform Your Business with a Software ERP System
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Essential Infomation Tech presentation.pptx
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Digital Strategies for Manufacturing Companies
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Nekopoi APK 2025 free lastest update
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
AI in Product Development-omnex systems
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
VVF-Customer-Presentation2025-Ver1.9.pptx
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Transform Your Business with a Software ERP System
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Design an Analysis of Algorithms II-SECS-1021-03
wealthsignaloriginal-com-DS-text-... (1).pdf
PTS Company Brochure 2025 (1).pdf.......
Essential Infomation Tech presentation.pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Understanding Forklifts - TECH EHS Solution
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Digital Strategies for Manufacturing Companies
Navsoft: AI-Powered Business Solutions & Custom Software Development
Nekopoi APK 2025 free lastest update
Odoo POS Development Services by CandidRoot Solutions
Which alternative to Crystal Reports is best for small or large businesses.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
AI in Product Development-omnex systems

Lecture #2 threading, networking &amp; permissions final version #2