1
1
package com.github.mrbean355.android.activitycontracts
2
2
3
3
import android.Manifest
4
- import android.content.Intent
5
- import android.content.pm.PackageManager
6
- import android.os.Build
7
4
import android.os.Bundle
5
+ import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
8
6
import androidx.activity.viewModels
9
7
import androidx.appcompat.app.AppCompatActivity
10
- import androidx.core.content.ContextCompat
11
8
import com.github.mrbean355.android.activitycontracts.databinding.ActivityContractsDemoBinding
12
9
13
- private const val REQUEST_CODE_PERMISSION = 123
14
- private const val REQUEST_CODE_CUSTOM = 456
15
-
16
10
class ContractsDemoActivity : AppCompatActivity () {
11
+ private val requestPermission = registerForActivityResult(RequestPermission ()) { granted ->
12
+ viewModel.onPermissionsResult(granted)
13
+ }
14
+ private val customContract = registerForActivityResult(PaymentActivity .Contract ()) { result ->
15
+ viewModel.onCustomContractResult(result)
16
+ }
17
17
private val viewModel: ContractsDemoViewModel by viewModels()
18
18
19
19
override fun onCreate (savedInstanceState : Bundle ? ) {
@@ -26,32 +26,11 @@ class ContractsDemoActivity : AppCompatActivity() {
26
26
}
27
27
28
28
binding.requestPermission.setOnClickListener {
29
- if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .M ) {
30
- if (ContextCompat .checkSelfPermission(this , Manifest .permission.CAMERA ) == PackageManager .PERMISSION_GRANTED ) {
31
- viewModel.onPermissionsResult(true )
32
- } else {
33
- requestPermissions(arrayOf(Manifest .permission.CAMERA ), REQUEST_CODE_PERMISSION )
34
- }
35
- }
29
+ requestPermission.launch(Manifest .permission.CAMERA )
36
30
}
37
31
38
32
binding.customContract.setOnClickListener {
39
- val intent = PaymentActivity .createIntent(this , Payment (" Test User" , 4200 ))
40
- startActivityForResult(intent, REQUEST_CODE_CUSTOM )
41
- }
42
- }
43
-
44
- override fun onRequestPermissionsResult (requestCode : Int , permissions : Array <out String >, grantResults : IntArray ) {
45
- super .onRequestPermissionsResult(requestCode, permissions, grantResults)
46
- if (requestCode == REQUEST_CODE_PERMISSION ) {
47
- viewModel.onPermissionsResult(grantResults.first() == PackageManager .PERMISSION_GRANTED )
48
- }
49
- }
50
-
51
- override fun onActivityResult (requestCode : Int , resultCode : Int , data : Intent ? ) {
52
- super .onActivityResult(requestCode, resultCode, data)
53
- if (requestCode == REQUEST_CODE_CUSTOM ) {
54
- viewModel.onCustomContractResult(PaymentActivity .parseResult(resultCode, data))
33
+ customContract.launch(Payment (" Test User" , 4200 ))
55
34
}
56
35
}
57
36
}
0 commit comments