lecture #2 threading, networking & permissions final version #2

168
pUp3EkaP

Upload: vitali-pekelis

Post on 12-Apr-2017

55 views

Category:

Software


4 download

TRANSCRIPT

Page 1: Lecture #2  threading, networking & permissions final version #2

pUp3EkaP

Page 2: Lecture #2  threading, networking & permissions final version #2

Yarkoni

IronSource

Android AcademyWomen Techmakers

Page 3: Lecture #2  threading, networking & permissions final version #2

~ 1500 members Largest Android Active Community

Page 4: Lecture #2  threading, networking & permissions final version #2

What Do We Do?

●Android Fundamentals

●Android UI / UX

●Community Hackathon

●Android Performance

●Mentors Program●Active community

Page 5: Lecture #2  threading, networking & permissions final version #2

Online Lessons

Important:

Watch online lesson

before the meetup!

- Our course: “Developing

Android Apps”goo.gl/u1pxZv

- Optional: Nano Degree

- Optional: “Android Basics” courses

Page 6: Lecture #2  threading, networking & permissions final version #2
Page 7: Lecture #2  threading, networking & permissions final version #2

The Course Plan

- Online lesson @ home - Lecture @ Campus- Hands-on @ Campus- Questions @ Facebook

Page 8: Lecture #2  threading, networking & permissions final version #2

YarkoniAndroid Leader

Ironsource

Android Academy Staff

Yonatan LevinGoogle Developer

Expert & Android @ Gett

Britt BarakAndroid Leader

Figure8

Yossi SegevAndroid Developer

Crave

Page 9: Lecture #2  threading, networking & permissions final version #2

Mentors program

Page 10: Lecture #2  threading, networking & permissions final version #2

Community Mentors

Refael “Hero” Ozeri

Page 11: Lecture #2  threading, networking & permissions final version #2

Lecture #2: Threads, Networking & Permissions

Understanding the concept of Multi Threading

Page 12: Lecture #2  threading, networking & permissions final version #2

What’s For Today?● Logging● Processes● Threads● Android Thread Abstractions● Permissions● Networking

Page 13: Lecture #2  threading, networking & permissions final version #2

Logging

Definition: A logfile is a file that records either events that occur in an operating system or other software runs.

Page 14: Lecture #2  threading, networking & permissions final version #2

Logging

Definition: A logfile is a file that records either events that occur in an operating system or other software runs.

Page 15: Lecture #2  threading, networking & permissions final version #2

*.java

Log.d(“MY-APP’S-TAG”, "message");

Page 16: Lecture #2  threading, networking & permissions final version #2

Logging

Page 17: Lecture #2  threading, networking & permissions final version #2

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.

Page 18: Lecture #2  threading, networking & permissions final version #2

Logging - Where can I see it?

HERE

Page 19: Lecture #2  threading, networking & permissions final version #2

Logging - levels

Log levelsverbose (all)debuginfo

warn

error

Page 20: Lecture #2  threading, networking & permissions final version #2

Great Log Wrapper

Page 21: Lecture #2  threading, networking & permissions final version #2

Great Log Wrapper

Page 22: Lecture #2  threading, networking & permissions final version #2

Code with filter !

Page 23: Lecture #2  threading, networking & permissions final version #2

What’s For Today?● Logging● Processes● Threads● Android Thread Abstractions● Permissions● Networking

Page 24: Lecture #2  threading, networking & permissions final version #2

Reminder

Java.Linux.

Page 25: Lecture #2  threading, networking & permissions final version #2

Processes(The app)

Page 26: Lecture #2  threading, networking & permissions final version #2

Processes - Android Priority

If system is stressed and needs to clear memory - the process will be killed together with its’ threads.

Process

Process

Page 27: Lecture #2  threading, networking & permissions final version #2

Processes - Android Priority

1.Foreground.2.Visible.3.Service.4.Background.5.Empty.

Page 28: Lecture #2  threading, networking & permissions final version #2

Processes - Android Priority

1.Foreground.2.Visible.3.Service.4.Background.5.Empty.

Page 29: Lecture #2  threading, networking & permissions final version #2

Processes - Android Priority

1.Foreground.2.Visible.3.Service.4.Background.5.Empty.

Page 30: Lecture #2  threading, networking & permissions final version #2

Processes - Android Priority

1.Foreground.2.Visible.3.Service.4.Background.5.Empty.

Page 31: Lecture #2  threading, networking & permissions final version #2

Processes - Android Priority

1.Foreground.2.Visible.3.Service.4.Background.5.Empty.

Page 32: Lecture #2  threading, networking & permissions final version #2

Processes - Android Priority

1.Foreground.2.Visible.3.Service.4.Background.5.Empty.

Page 33: Lecture #2  threading, networking & permissions final version #2

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.

Page 34: Lecture #2  threading, networking & permissions final version #2

Processes - CPU Time Split

Foreground & Visible - 90%

Service & Background & Empty - 10%

Page 35: Lecture #2  threading, networking & permissions final version #2

Threads

Page 36: Lecture #2  threading, networking & permissions final version #2

Threads

Like Linux a process is created with a singleThread of execution.

ProcessThread A

Page 37: Lecture #2  threading, networking & permissions final version #2

Threads - Thread of Execution

Thread of execution.

CPU Core

Thread of execution

Thread A

Thread B

Thread C

Page 38: Lecture #2  threading, networking & permissions final version #2

Threads - Thread of Execution

Thread of execution.

CPU Core

Thread of execution

Thread A

Thread B

Thread C

Page 39: Lecture #2  threading, networking & permissions final version #2

Threads - Thread of Execution

Thread of execution.

CPU Core

Thread of execution

Thread A

Thread B

Thread C

Page 40: Lecture #2  threading, networking & permissions final version #2

Threads

Java & Android ThreadsModerate to large operation.Not tied to activity lifecycle.Reusable.Number 1 cause of memory leak.

Page 41: Lecture #2  threading, networking & permissions final version #2

Threads

Java & Android ThreadsModerate to large operation.Not tied to activity lifecycle.Reusable.Number 1 cause of memory leak.

Page 42: Lecture #2  threading, networking & permissions final version #2

I’mCollector,

Garbage Collector

Page 43: Lecture #2  threading, networking & permissions final version #2

Never have a Non-Static Inner Class

Page 44: Lecture #2  threading, networking & permissions final version #2

Always an Inner Class be Static

Page 45: Lecture #2  threading, networking & permissions final version #2

Processes vs. Threads

ProcessesSeparate address space.Communicate via IPC.

ThreadsShare address space.Communicate using handlers.

Page 46: Lecture #2  threading, networking & permissions final version #2

Processes vs. Threads

ProcessesSeparate address space.Communicate via IPC.

ThreadsShare address space.Communicate using handlers.

Page 47: Lecture #2  threading, networking & permissions final version #2

Threads - Memory

Threading isn’t memory safe.Thread A

Thread B

Memory

Write

Write

???

Page 48: Lecture #2  threading, networking & permissions final version #2

Threads - Memory

UI elements are not “Thread Safe”.Thread A

Thread B

Button

Button

Button

Create Update

Update

Page 49: Lecture #2  threading, networking & permissions final version #2

Start a new Thread and pass it a UI element

Page 50: Lecture #2  threading, networking & permissions final version #2

Manipulate UI element from off Thread

Page 51: Lecture #2  threading, networking & permissions final version #2

CRASH

Page 52: Lecture #2  threading, networking & permissions final version #2

CRASH

Page 53: Lecture #2  threading, networking & permissions final version #2

What is the Thread for UI elements?

Page 54: Lecture #2  threading, networking & permissions final version #2

Solution

Page 55: Lecture #2  threading, networking & permissions final version #2

Main Thread

Page 56: Lecture #2  threading, networking & permissions final version #2

Main Thread

UI thread responsibilities:Dispatches events.Draws on screen.Handles user input.

Page 57: Lecture #2  threading, networking & permissions final version #2

Process

What’s On The Main Thread?

Main Thread (UI Thread)System Event

Input Event Service Applicati

onUI Drawing

Page 58: Lecture #2  threading, networking & permissions final version #2

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

Page 59: Lecture #2  threading, networking & permissions final version #2

Reminder - Blocking Action Definition

A Thread that is blocked is waiting for a completion of an operation.

Page 60: Lecture #2  threading, networking & permissions final version #2

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

16ms

Dropped Frame

Page 61: Lecture #2  threading, networking & permissions final version #2

We Have A Winner!

SmoothMotion

60

No Difference

60+

Flip Book

12

Movies

Frames Per Second

Fluid Motion

24+effects

SmoothMotion

60

Page 62: Lecture #2  threading, networking & permissions final version #2
Page 63: Lecture #2  threading, networking & permissions final version #2

What happens if you delay the UI thread for more than 16ms?

Page 64: Lecture #2  threading, networking & permissions final version #2

At 60Hz it takes 16.67ms to render a frame therefore if you

take up those 16.67 a frame will be dropped.

Page 65: Lecture #2  threading, networking & permissions final version #2

Main Thread - 2 rules

Do not block the UI thread.Do not access the UI toolkit from non UI thread.

Page 66: Lecture #2  threading, networking & permissions final version #2

Main Thread

What happens if you block the UI thread for more than 5 seconds?

Page 67: Lecture #2  threading, networking & permissions final version #2

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”

Page 68: Lecture #2  threading, networking & permissions final version #2
Page 69: 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

Page 70: Lecture #2  threading, networking & permissions final version #2

Off Thread

Page 71: Lecture #2  threading, networking & permissions final version #2

Off Thread - Usages

Database operations.Networking operations.Long running operations.

Page 72: Lecture #2  threading, networking & permissions final version #2

Android has your back!

Page 73: Lecture #2  threading, networking & permissions final version #2

Framework Abstractions

AsyncTaskHelps get work off/on the UI thread.

HandlerThreadDedicated thread for API callbacks.

ThreadPoolRunning lots of parallel work.

IntentServiceHelps get intents off the UI thread.

Page 74: Lecture #2  threading, networking & permissions final version #2

AsyncTask

Page 75: Lecture #2  threading, networking & permissions final version #2

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.Always returns on the Main Thread.

Page 76: Lecture #2  threading, networking & permissions final version #2

AsyncTask WorkerThread

doInBackground ()

onPreExecute ()

MainThread

onPostExecute ()

Page 77: Lecture #2  threading, networking & permissions final version #2

AsyncTask WorkerThread

doInBackground ()

onPreExecute ()

MainThread

onProgressUpdate ()

onPostExecute ()

publishProgress()

Page 78: Lecture #2  threading, networking & permissions final version #2
Page 79: Lecture #2  threading, networking & permissions final version #2
Page 80: Lecture #2  threading, networking & permissions final version #2

How to Create and Start an AsyncTask

Page 81: Lecture #2  threading, networking & permissions final version #2

AsyncTask always returns on Main Thread

Page 82: Lecture #2  threading, networking & permissions final version #2

MainActivity.java

Page 83: Lecture #2  threading, networking & permissions final version #2

MainActivity.java

Page 84: Lecture #2  threading, networking & permissions final version #2

MainActivity.java

Page 85: Lecture #2  threading, networking & permissions final version #2
Page 86: 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

Page 87: Lecture #2  threading, networking & permissions final version #2

HandlerThread

Page 88: Lecture #2  threading, networking & permissions final version #2

Reminder

Main Thread (UI Thread)

Process

System Event

UI Drawing

Your code!~!!!~!

16ms

16ms

16ms

UI Drawing

UI Drawing

16ms

16ms

Dropped Frame

Page 89: Lecture #2  threading, networking & permissions final version #2

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

Page 90: Lecture #2  threading, networking & permissions final version #2

Worker Thread

Main Thread (UI Thread)

Thread ATask 0 Task Complete

Task 1

Task 2

Task 3

Page 91: Lecture #2  threading, networking & permissions final version #2

How can we create a thread capable of handling multiple

consecutive tasks?

Page 92: Lecture #2  threading, networking & permissions final version #2

Worker Thread - Recipe

Handler + Looper + Thread = HandlerThread

Page 93: Lecture #2  threading, networking & permissions final version #2

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).

Page 94: Lecture #2  threading, networking & permissions final version #2

Handlers

Schedule task for the future.Enqueue task for another thread.

Page 95: Lecture #2  threading, networking & permissions final version #2

Handlers - Methods

handler.post();handler.postAtFrontOfQueue();handler.postDelayed();handler.postAtTime();

Page 96: Lecture #2  threading, networking & permissions final version #2

MainActivity.java

Page 97: Lecture #2  threading, networking & permissions final version #2

MainActivity.java

Page 98: Lecture #2  threading, networking & permissions final version #2

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.

Page 99: Lecture #2  threading, networking & permissions final version #2

A Deeper Look

Main Thread (UI Thread)

Looper Message queue

HandlerHandle MSG

SendMSG

Process

Page 100: Lecture #2  threading, networking & permissions final version #2
Page 101: Lecture #2  threading, networking & permissions final version #2
Page 102: Lecture #2  threading, networking & permissions final version #2

Sending a message to a Thread

Page 103: Lecture #2  threading, networking & permissions final version #2

Putting it all together

Page 104: Lecture #2  threading, networking & permissions final version #2

Threads Handlers and Looper

Page 105: Lecture #2  threading, networking & permissions final version #2

Handlers

Page 106: Lecture #2  threading, networking & permissions final version #2

Handlers

Page 107: Lecture #2  threading, networking & permissions final version #2

Handlers

Page 108: Lecture #2  threading, networking & permissions final version #2

Handlers

Page 109: Lecture #2  threading, networking & permissions final version #2

One more thing - Don’t forget to quit!

HandlerThread.quit();

Page 110: Lecture #2  threading, networking & permissions final version #2
Page 111: Lecture #2  threading, networking & permissions final version #2

Thread Priority

Page 112: Lecture #2  threading, networking & permissions final version #2

Thread Priority

THREAD_PRIORITY_LOWEST = 19THREAD_PRIORITY_BACKGROUND = 10THREAD_PRIORITY_LESS_FAVORABLE = +1THREAD_PRIORITY_MORE_FAVORABLE = -1THREAD_PRIORITY_URGENT_AUDIO = -19Threads created on foreground inherit foreground

priority = -2

Page 113: Lecture #2  threading, networking & permissions final version #2

Thread Priority - Higher means Lower

Page 114: Lecture #2  threading, networking & permissions final version #2

Why URGENT_AUDIO is the highest priority (-19)?

Page 115: Lecture #2  threading, networking & permissions final version #2

Sound delay is even more noticeable than frame skipping.

Page 116: Lecture #2  threading, networking & permissions final version #2

Does this mean I should handle all the priorities of every

Thread created?

Page 117: Lecture #2  threading, networking & permissions final version #2

Thread Pool Executor

Page 118: Lecture #2  threading, networking & permissions final version #2

Thread Pool executor

Handles Spinning.Handles Load Balancing.Handles killing Threads when they are idle.

Page 119: Lecture #2  threading, networking & permissions final version #2

Thread Pool executor

BlockingQueue

Thread A

Thread B

Thread C

ThreadPool

Page 120: Lecture #2  threading, networking & permissions final version #2

Thread Pool executor

BlockingQueue

Thread A

Thread B

Thread C

ThreadPool

Page 121: Lecture #2  threading, networking & permissions final version #2

Thread Pool executor

BlockingQueue

Thread A

Thread B

Thread C

ThreadPool

Page 122: Lecture #2  threading, networking & permissions final version #2

Thread Pool executor

BlockingQueue

Thread A

Thread B

Thread C

ThreadPool

Page 123: Lecture #2  threading, networking & permissions final version #2

Thread Pool executor

BlockingQueue

Thread A

Thread B

Thread C

ThreadPool

Page 124: Lecture #2  threading, networking & permissions final version #2

Thread Pool executor

BlockingQueue

Thread A

Thread B

Thread C

ThreadPool

Page 125: Lecture #2  threading, networking & permissions final version #2

Thread Pool executor

BlockingQueue

Thread A

Thread B

Thread C

ThreadPool

Page 126: Lecture #2  threading, networking & permissions final version #2

Thread Pool executor

BlockingQueue

Thread A

Thread C

ThreadPool

Page 127: Lecture #2  threading, networking & permissions final version #2

Thread Pool Executor

How many threads is a good number of threads?

Page 128: Lecture #2  threading, networking & permissions final version #2

So if I want to get more work done I should create more

threads.By induction: Infinite Threads!

Page 129: Lecture #2  threading, networking & permissions final version #2

Thread Pool executor

Adjust to number of cores.64kb per thread.

Page 130: Lecture #2  threading, networking & permissions final version #2

ThreadPool Implementation

Page 131: Lecture #2  threading, networking & permissions final version #2

Passing a Task to the ThreadPool

Page 132: Lecture #2  threading, networking & permissions final version #2
Page 133: Lecture #2  threading, networking & permissions final version #2

IntentService

Page 134: Lecture #2  threading, networking & permissions final version #2

Example

Intent

-?-

Hard work

Intent Hard work

Intent Hard work

Page 135: Lecture #2  threading, networking & permissions final version #2

IntentService

Extends Service.Is killed by System when queue is empty.Can’t be interrupted.

Page 136: Lecture #2  threading, networking & permissions final version #2

Systrace

Page 137: Lecture #2  threading, networking & permissions final version #2

What’s For Today?● Logging● Processes● Threads● Android Thread Abstractions● Permissions● Networking

Page 138: Lecture #2  threading, networking & permissions final version #2

Content

It’s everything the user sees and interacts.Where can we get content?

Static content.

Locally on the phone.

Remote server.

Page 139: Lecture #2  threading, networking & permissions final version #2

Content

It’s everything the user sees and interacts.Where can we get content?

Static content.

Locally on the phone.

Remote server.

Page 140: Lecture #2  threading, networking & permissions final version #2

Top apps examples: FB, SnapChat, Instagram.

Page 141: Lecture #2  threading, networking & permissions final version #2

Reminder

Database operations.Networking operations.Long running operations.

Page 142: Lecture #2  threading, networking & permissions final version #2

Reminder

Database operations.Networking operations.Long running operations.

Page 143: Lecture #2  threading, networking & permissions final version #2

Networking requests

Require the following permission:

Cannot be done on the MainThread:

Page 144: Lecture #2  threading, networking & permissions final version #2

Permissions

Page 145: Lecture #2  threading, networking & permissions final version #2

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.

Page 146: Lecture #2  threading, networking & permissions final version #2

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"/>

Page 147: Lecture #2  threading, networking & permissions final version #2

Permissions - Level

Protection levelNormal - (flashlight, internet, NFC)

Dangerous - (Read / write external storage)

Signature - (defined per use case)

SigantureOrSystem - (Install 3rd party applications)

Application defined permission.

Page 148: Lecture #2  threading, networking & permissions final version #2

Permissions - Normal vs. Dangerous

Normal: Bluetooth, Internet, NFC.

Dangerous: read/write external storage, contacts, location.

What is the key difference?

Page 149: Lecture #2  threading, networking & permissions final version #2

Permissions - Android 6.0

TargetSDKVersionIf you wrote 24 you will crash if not handled.

If you wrote <24 you will be spared.

Page 150: Lecture #2  threading, networking & permissions final version #2

Permissions - Android 6.0

Still define permissions in AndroidManifest.xmlprotectionLevel = normal are granted by default.protectionLevel = Dangerous require you

ask at runtime.Request 1 time without consequence.

Page 151: Lecture #2  threading, networking & permissions final version #2

Permissions - Android 6.0

Still define permissions in AndroidManifest.xmlprotectionLevel = normal are granted by default.protectionLevel = Dangerous require you

ask at runtime.Request 1 time without consequence.

Page 152: Lecture #2  threading, networking & permissions final version #2

Permissions - Vertical & Horizontal views

Auditing vertically/Horizontally.

Page 153: Lecture #2  threading, networking & permissions final version #2

MainActivity.xml

Page 154: Lecture #2  threading, networking & permissions final version #2

MainActivity.xml

Page 155: Lecture #2  threading, networking & permissions final version #2

Network Requests(Connecting to the Cloud)

Page 156: Lecture #2  threading, networking & permissions final version #2

Network requests

Android include many network programming classes.

java.net (socket, URL, etc.)

org.apache (HttpRequest, HttpResponse, etc.)

android.net (AndroidHTTPClient, URI, AudioStream, etc.)

Page 157: Lecture #2  threading, networking & permissions final version #2

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

Page 158: Lecture #2  threading, networking & permissions final version #2

Network requests - InputStream

Page 159: Lecture #2  threading, networking & permissions final version #2

Network requests - InputStreamReader

Page 160: Lecture #2  threading, networking & permissions final version #2

Network requests - BufferedStreamReader

Page 161: Lecture #2  threading, networking & permissions final version #2

Network requests - HttpURLConnection

Page 162: Lecture #2  threading, networking & permissions final version #2

What is the connection?

Page 163: Lecture #2  threading, networking & permissions final version #2

build.gradle

Page 164: Lecture #2  threading, networking & permissions final version #2

build.gradle

Page 165: Lecture #2  threading, networking & permissions final version #2

MainActivity.java

Page 166: Lecture #2  threading, networking & permissions final version #2

Homework:1.Go over AsyncTask,

IntentServices, Handlers, Threads code.

2.Watch “Create New Activities and Navigate Apps

with Intents”3.Start developing Sunshine.

Page 167: Lecture #2  threading, networking & permissions final version #2

34th floor

Page 168: Lecture #2  threading, networking & permissions final version #2

Drive home safe

See you next Sunday!