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

Preview:

Citation preview

pUp3EkaP

Yarkoni

IronSource

Android AcademyWomen Techmakers

~ 1500 members Largest Android Active Community

What Do We Do?

●Android Fundamentals

●Android UI / UX

●Community Hackathon

●Android Performance

●Mentors Program●Active community

Online Lessons

Important:

Watch online lesson

before the meetup!

- Our course: “Developing

Android Apps”goo.gl/u1pxZv

- Optional: Nano Degree

- Optional: “Android Basics” courses

The Course Plan

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

YarkoniAndroid Leader

Ironsource

Android Academy Staff

Yonatan LevinGoogle Developer

Expert & Android @ Gett

Britt BarakAndroid Leader

Figure8

Yossi SegevAndroid 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● Networking

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 levelsverbose (all)debuginfo

warn

error

Great Log Wrapper

Great Log Wrapper

Code with filter !

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

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.

Process

Process

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 singleThread of execution.

ProcessThread 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 ThreadsModerate to large operation.Not tied to activity lifecycle.Reusable.Number 1 cause of memory leak.

Threads

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

I’mCollector,

Garbage Collector

Never have a Non-Static Inner Class

Always an Inner Class be Static

Processes vs. Threads

ProcessesSeparate address space.Communicate via IPC.

ThreadsShare address space.Communicate using handlers.

Processes vs. Threads

ProcessesSeparate address space.Communicate via IPC.

ThreadsShare 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 Applicati

onUI 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

16ms

Dropped Frame

We Have A Winner!

SmoothMotion

60

No Difference

60+

Flip Book

12

Movies

Frames Per Second

Fluid Motion

24+effects

SmoothMotion

60

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”

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

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.

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

AsyncTask WorkerThread

doInBackground ()

onPreExecute ()

MainThread

onPostExecute ()

AsyncTask WorkerThread

doInBackground ()

onPreExecute ()

MainThread

onProgressUpdate ()

onPostExecute ()

publishProgress()

How to Create and Start an AsyncTask

AsyncTask always returns on Main Thread

MainActivity.java

MainActivity.java

MainActivity.java

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

16ms

Dropped 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

HandlerHandle MSG

SendMSG

Process

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();

Thread Priority

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

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

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● Networking

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 levelNormal - (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

TargetSDKVersionIf 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.xmlprotectionLevel = 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.xmlprotectionLevel = 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!

Recommended