Activity
Activity新增了一個ActivityResultContracts,簡化一些寫法讓程式碼比較簡潔好理解。
registerForActivityResult(ActivityResultContracts):activity註冊將要執行甚麼功能。
ActivityResultContracts.RequestMultiplePermissions():訪問多個權限。
ActivityResultContracts.StartActivityForResult():跳轉頁面並回傳資料。
導入Library
implementation 'androidx.activity:activity-ktx:1.2.0-beta01'
implementation 'androidx.fragment:fragment:1.3.0-beta01'
詢問權限
//設置要訪問的權限的操作
private val multiplePermissions =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { it ->
it.entries.forEach {
when (it.key) {
Manifest.permission.CAMERA -> {
Log.d("GG", "CAMERA ${it.value}")
}
Manifest.permission.READ_EXTERNAL_STORAGE -> {
Log.d("GG", "READ_EXTERNAL_STORAGE ${it.value}")
}
Manifest.permission.READ_CONTACTS -> {
Log.d("GG", "READ_CONTACTS ${it.value}")
}
}
}
}
//調用launch
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
multiplePermissions.launch(
arrayOf(
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.READ_CONTACTS
)
)
}
跳轉頁面
private val toMaMainActivity2 =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
Log.d("GG", "我正確的回來了")
} else {
Log.d("GG", "我不正確的回來了")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
toMaMainActivity2.launch(
Intent(this, MainActivity2::class.java)
)
}