Mobile Apps 2023W Lecture 7

From Soma-notes

Notes

Lecture 7
---------

For next time: doing HTTP requests & getting responses, working with REST APIs in Android and Kotlin

Today: Processes & Threads in Android

A process is a running program on UNIX/Linux (and Windows)
 - has its own share of memory and CPU resources
 - isolated from the rest of the system (cannot see the memory of other processes)

The CPU runs a process for a while then switches to running other processes
  - the OS scheduler in the kernel chooses which process to run next
  - a process can make a request that causes it to be paused (a system call)
  - or a process runs for too long and a timer goes off and it is interrupted

A thread is part of a process, it is a CPU context
 - basically, the state associated with running the program
 - we can have just one thread, which is what we have with a standard sequential program
 - or we can have a multi-threaded process, with multiple CPU contexts
   (so logically it is doing more than one thing at the same time)

So an app is running in at least one process, but an app can have multiple processes
 - and apps can even share processes in some situations (but they have to all
   be created by the same developer)

In Android, there is the concept of a "UI thread"
 - so in the main app's process, the UI thread is the one interacting with the user, controlling the visible activities
 - you can have other threads, but they will be worker threads and may not manipulate the interface
    - they must send requests to the UI thread, it will then update the screen

If you do time-intensive operations in the UI thread, the UI thread will block and so the interface will freeze until the operations finish

So why not always put things in threads, why would we use separate processes for an activity, app, or background service?
  - threads share all memory
  - so if you're doing something dangerous or unsafe, or something that just should be separate, you want to do it in a separate process
     - processing user input is in general unsafe, so often good to segregate it

Modern web browsers are multi-process precisely because of this
 - web page content isn't trusted, could be malicious, so is put into a separate process to keep it from messing with info in other tabs/windows

See https://developer.android.com/guide/components/processes-and-threads
for background

Multithreaded programming in C is a real pain
but it isn't so bad in Kotlin/Java, things stay separate in a nice way for the most part

We really need to make our app concurrent so it can deal with a user, the network, storage (files, databases) and processing data all at the same while keeping the interface responsive