不知道一週能完成多少呢。
O
回顧Android。
KRs
- Compoments (100 %)
- 機智問答 (80 %)
- Kotlin (80 %)
- Thread (100 %)
Compoments
1 | Activity: 提供UI,有不同狀態,User可以在UI間切換。 |
- 皆開始於 UI thread.
Activity生命週期
- OnCreate: Cold start
- OnStart: Warm start
- OnResume: Hot start
UI components represent individual screens in the app and typically handle user interactions.
1 | onCreate():Activity第一次被創建,初始化Activity的狀態和布局。 |
優化
Startup library: 透過 Content provider 的機制來加速 App 的開啟速度。
Service生命週期
Background components perform long-running operations.
有三種服務,兩種啟動方式
- 前台服務(Foreground Service):不在UI thread,User可見的服務
- 後台服務(Background Service):不在UI thread,User不可見的服務
- 繫結服務(Bound Service):繫結已經存在的服務
1 | public class MyService extends Service { |
onCreate()
Service第一次被創建時調用,如創建線程等。onStartCommand()
啟動Service時調用,執行一些耗時的操作,如網絡請求等。onBind()
繫結Service時調用,返回一個IBinder對象,用於繫結Service和客戶端進行通信。onUnbind()
解除繫結Service,可以在這個方法中釋放一些資源,如註銷Broadcast Receiver等。onDestroy()
Service被銷毀時調用,通常在這個方法中釋放所有的資源。
BroadcastReceiver
Listen for system-wide events or messages and allow the app to respond to these events.
ContentProvider
Provide a consistent data interface to other apps.
程式間互相分享資料 Views System:lists,grids,text boxes,buttons…元件
1 | import android.content.ContentProvider; |
Android Inter-Process Communication (IPC)
Services
Perform long-running operations in the background.Broadcast Receivers
Send and receive system-wide messages or broadcast custom messages.Content Providers
A data repository allow data to be shared between applications.Intents
Send messages between components of the same or different applications.Messenge
A lightweight IPC mechanism, send messages between components.AIDL (Android Interface Definition Language)
A programming language that allows the definition of interfaces between processes.
機智問答
Finally, Final and Finalize
Finally
Used for exception handlingFinal
Variable: constants
Method: prevent overriding
Class: prevent inheritanceFinalize
Used for performing cleanup operations on objects before they are destroyed.
Synchronized and Unsynchronized
Synchronized
Block of code that can be accessed by only one thread until the first thread releases the lock.Unsynchronized
A code didn’t use synchronized keyword.
References
Strong reference
Never GCSoft reference
GC before OutOfMemoryErrorWeak referenc
GC when there is no Strong or Soft
JNI(Java Native Interface)
A framework that allows Java code running in a JVM to call native code and vice versa.
Layouts
1 | LinearLayout:水平/垂直。 |
ListView v.s. RecyclerView
1 | ListView:從上到下顯示佈局。 |
Kotlin
符號
- Type Inference: 型別推斷
val name = “Kotlin” // 型別自動推斷為 String
- Null Safety: ?/!!
1 | val myList: ArrayList<String>? = null // null 時印null |
- Null-Safe Operator: ?. 運算子可以安全地呼叫屬性或方法,如果物件為 null,則返回 null
1 | fun printLength(str: String?) { |
- ::
把方法當參數傳遞
1 | var action: (A, B) -> ReturnType |
- ==/===
1 | 值/位置 |
- Smart Casts: 自動進行型別轉換
1 | fun printLength(obj: Any) { |
- Property Delegates: lazy 初始化、可觀察屬性等
1 | val lazyValue: String by lazy { // lazy 委託:第一次訪問 lazyValue 時才會計算值 |
- 封裝繼承比Java更簡潔,有Coroutines
- lateinit
非null變數,之後再給值
1 | class MyClass { |
- var可賦值,val 不可
- 類型推論(type inferred)
1 | val number = 42 // number is inferred to be an Int |
- Range
1 | val intRange = 1..10 // creates a range from 1 to 10 (inclusive) |
Data Class: 自動生成 equals()、hashCode()、toString() 等方法
data class User(val name: String, val age: Int)
自動生成:equals()、hashCode()、toString()、copy() 等方法。
val user1 = User(“Alice”, 30)
val user2 = User(“Alice”, 30)
println(user1 == user2) // truewhen取代switch
1 | fun describe(obj: Any): String = |
- Support Functional Programming
1 | class Student( |
- Companion Object
Class中方便定義靜態函式
1 | class MyClass { |
- 繼承用:取代extends
1 | open class Animal { |
- 函式擴展:不用繼承而增加methods
1 | fun String.capitalizeFirstLetter(): String { |
interface Moveable {
fun move()
}
class Car : Moveable {
override fun move() {
println(“Driving…”)
}
}
1 |
|
toString()
componentN()
copy()
hashCode()
1 |
|
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
1 |
|
suspend fun getUserData(userId: String): UserData {
return withContext(Dispatchers.IO) {
// perform an expensive I/O operation, such as network call or disk access
// and return the result as a UserData object
}
}
// launch a coroutine to fetch the user data
val job = GlobalScope.launch(Dispatchers.Main) {
val userData = getUserData(“123”)
// update the UI with the user data
}
fun main() = runBlocking {
val job = launch { // launch:啟動一個新的協程
delay(1000L)
println(“World!”)
}
println(“Hello,”)
job.join()
}
1 |
|
map()
val numbers = listOf(1, 2, 3, 4)
val squares = numbers.map { it * it } // [1, 4, 9, 16]
filter()
val numbers = listOf(1, 2, 3, 4)
val evens = numbers.filter { it % 2 == 0 } // [2, 4]
reduce()
val numbers = listOf(1, 2, 3, 4)
val sum = numbers.reduce { acc, n -> acc + n } // 10
fold()
val numbers = listOf(1, 2, 3, 4)
val sum = numbers.fold(0) { acc, n -> acc + n } // 10
forEach()
val numbers = listOf(1, 2, 3, 4)
numbers.forEach { println(it) }
flatMap()
val numbers = listOf(listOf(1, 2), listOf(3, 4))
val flattened = numbers.flatMap { it } // [1, 2, 3, 4]
1 |
|
// binding.xml
// Kotlin code
val binding = ActivityMainBinding.inflate(layoutInflater)
binding.textView.text = “Hello, World!”
```
時程: 2023/4/21- 2023/4/28
如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)