组件merge
类名.()
的写法
1 2 3 4 5 6 7 8 9
| inline fun AppCompatActivity.fragmentTransaction(block: FragmentTransaction.() -> Unit): Boolean { kotlin.runCatching { val t = supportFragmentManager.beginTransaction() block.invoke(t) t.commitNowAllowingStateLoss() return true } return false }
|
1 2 3 4
| fun newWorkerThreadCoroutineJob(block: suspend CoroutineScope.() -> Unit): Job { return GlobalScope.launch(context = Dispatchers.IO, block = block) }
|
android-job庫
kotlin基礎
kotlin 携程
- 顶层主协程?
- 协程是轻量级的线程
- delay 是一个特殊的 挂起函数 ,它不会造成线程阻塞,但是会 挂起 协程,并且只能在协程中使用。
1 2 3 4 5 6 7 8 9 10
| import kotlinx.coroutines.*
fun main() { GlobalScope.launch { delay(1000L) println("World!") } println("Hello,") Thread.sleep(2000L) }
|
delay是非阻塞的,sleep是阻塞的
- 抛棄sleep,使用runBlocking與delay
1 2 3 4 5 6 7 8 9 10 11 12
| import kotlinx.coroutines.*
fun main() { GlobalScope.launch { delay(1000L) println("World!") } println("Hello,") runBlocking { delay(2000L) } }
|
1 2 3 4 5 6
| val job = GlobalScope.launch { delay(1000L) println("World!") } println("Hello,") job.join()
|
suspend關鍵字
object關鍵字
能自動實現單例模式的class,不能被賦值
1 2 3
| object Test { val a = 0; }
|
對應的字節碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public final class Test { private static final int a; @NotNull public static final Test INSTANCE;
public final int getA() { return a; }
private Test() { }
static { Test var0 = new Test(); INSTANCE = var0; } }
|
伴生對象
在 JVM 平台,如果使用 @JvmStatic 注解,你可以将伴生对象的成员生成为真正的静态方法和字段。更详细信息请参见Java 互操作性一节 。
handler
讓子綫程結束后的結果傳遞給主綫程, 給主綫程更新界面
handler異步通信系統:Handler
,message
,Looper, MessageQueue
Looper:主綫程不斷從消息隊列中拿消息的東西
子綫程
–拿到主綫程的handler,sendMessage–>
主綫程的Handler系統
–從消息隊列中拿到消息,交給主綫程,handleMessage–>
主綫程