FusedLocationProviderClient with Hilt

35 Views Asked by At

I'd like to get location of the mobile device, but I'm kinda lost. I probably should make this logic inside of the ViewModel, to not burden the Activity/View class itself.

The problem is, I need Context, to check the permissions. As far as I know, it is bad practice to pass Context to ViewModel, as it could case memory leaks.

How I should I implement it then? Should I ask for permissions in View class? Here's some very basic code:

Location module

@Module
@InstallIn(SingletonComponent::class)
class LocationClient {

    @Singleton
    @Provides
    fun provideFusedLocationClient(
        @ApplicationContext context: Context
    ): FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context)
}

ViewModel

@HiltViewModel
class MyViewModel@Inject constructor(
    private val client: FusedLocationProviderClient
) : ViewModel() {

    fun retrieveLocation() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return
        }
        client.getLastLocation().addOnSuccessListener { location ->
            println(location.longitude)
            println(location.latitude)
        }
    }
}
0

There are 0 best solutions below