@@ -18,19 +18,16 @@ package com.example.bluetoothlechat.bluetooth
18
18
import android.Manifest
19
19
import android.content.pm.PackageManager
20
20
import android.os.Bundle
21
- import android.util.Log
22
21
import android.view.LayoutInflater
23
22
import android.view.View
24
23
import android.view.ViewGroup
24
+ import androidx.activity.result.contract.ActivityResultContracts
25
25
import androidx.core.content.ContextCompat
26
26
import androidx.fragment.app.Fragment
27
27
import androidx.navigation.fragment.findNavController
28
28
import com.example.bluetoothlechat.R
29
29
import com.example.bluetoothlechat.databinding.FragmentLocationRequiredBinding
30
30
31
- private const val TAG = " LocationRequiredFrag"
32
- private const val LOCATION_REQUEST_CODE = 0
33
-
34
31
// Fragment responsible for checking if the app has the ACCESS_FINE_LOCATION permission.
35
32
// This permission is required when using the BLE APIs so the user must grant permission
36
33
// to the app before viewing the BluetoothChatFragment or DeviceListFragment
@@ -44,7 +41,7 @@ class LocationRequiredFragment : Fragment() {
44
41
inflater : LayoutInflater ,
45
42
container : ViewGroup ? ,
46
43
savedInstanceState : Bundle ?
47
- ): View ? {
44
+ ): View {
48
45
_binding = FragmentLocationRequiredBinding .inflate(inflater, container, false )
49
46
50
47
// hide the error messages while checking the permissions
@@ -64,25 +61,14 @@ class LocationRequiredFragment : Fragment() {
64
61
checkLocationPermission()
65
62
}
66
63
67
- override fun onRequestPermissionsResult (
68
- requestCode : Int ,
69
- permissions : Array <out String >,
70
- grantResults : IntArray
71
- ) {
72
- super .onRequestPermissionsResult(requestCode, permissions, grantResults)
73
- Log .d(TAG , " onRequestPermissionsResult: " )
74
- when (requestCode) {
75
- LOCATION_REQUEST_CODE -> {
76
- if (grantResults.isNotEmpty() &&
77
- grantResults[0 ] == PackageManager .PERMISSION_GRANTED ) {
78
- // Navigate to the chat fragment
79
- findNavController().navigate(R .id.action_start_chat)
80
- } else {
81
- showError()
82
- }
64
+ private val startForResultRequestPermission =
65
+ registerForActivityResult(ActivityResultContracts .RequestPermission ()) {
66
+ if (it) {
67
+ findNavController().navigate(R .id.action_start_chat)
68
+ } else {
69
+ showError()
83
70
}
84
71
}
85
- }
86
72
87
73
private fun showError () {
88
74
binding.locationErrorMessage.visibility = View .VISIBLE
@@ -99,10 +85,7 @@ class LocationRequiredFragment : Fragment() {
99
85
// Navigate to the chat fragment
100
86
findNavController().navigate(R .id.action_start_chat)
101
87
} else {
102
- requestPermissions(
103
- arrayOf(Manifest .permission.ACCESS_FINE_LOCATION ),
104
- LOCATION_REQUEST_CODE
105
- )
88
+ startForResultRequestPermission.launch(Manifest .permission.ACCESS_FINE_LOCATION )
106
89
}
107
90
}
108
91
}
0 commit comments