-1

Hi guys I am new to the game and am currently trying to develop a weather app for my portfolio, however I have encountered a few problems. Apparently the locationrequest method is deprecated and I would like to know how to alternatively request that. Unfortunately I couldn't find anything concrete as LocationRequest.create().apply is also deprecated and LocationRequest.Builder() is used for instead. However, I couldn't figure it out how from google's guide.

This is my code so far (feel free to correct me i'd love to hear feedback):

package com.alexplas.weather


import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.*


class SplashScreen : AppCompatActivity() {
    lateinit var mfusedlocation:FusedLocationProviderClient
    private var myRequestCode=1010
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash_screen)

        mfusedlocation= LocationServices.getFusedLocationProviderClient(this)

        getLastLocation()
    }

    @SuppressLint("MissingPermission")
    private fun getLastLocation() {
        if(CheckPermission()) {
            if(LocationEnable()){
                mfusedlocation.lastLocation.addOnCompleteListener{
                        task->
                    var location:Location?=task.result
                    if(location==null)
                    {
                        NewLocation()
                    }else{
                        Handler(Looper.getMainLooper()).postDelayed({
                            val intent= Intent(this,MainActivity::class.java)
                            intent.putExtra("lat",location.latitude.toString())
                            intent.putExtra("long",location.longitude.toString())
                            startActivity(intent)
                            finish()
                        },2000)
                    }
                }
            }else{
                Toast.makeText(this,"Please Turn on your GPS location",Toast.LENGTH_LONG).show()
            }
        }else{
            RequestPermission()
        }
    }

    @SuppressLint("MissingPermission")
    private fun NewLocation() { 
        var locationRequest=LocationRequest()
        locationRequest.priority=Priority.PRIORITY_HIGH_ACCURACY
        locationRequest.interval=0
        locationRequest.fastestInterval=0
        locationRequest.numUpdates=1
        mfusedlocation=LocationServices.getFusedLocationProviderClient(this)
        mfusedlocation.requestLocationUpdates(locationRequest,locationCallback, Looper.myLooper())
    }
    private val locationCallback=object:LocationCallback(){
        override fun onLocationResult(p0: LocationResult) {
            var lastLocation:Location=p0.lastLocation
        }
    }

    private fun LocationEnable(): Boolean {
        var locationManager=getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    }

    private fun RequestPermission() {
        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION),myRequestCode)
    }

    private fun CheckPermission(): Boolean {
        if(
            ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED ||
            ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED
        ){
            return true
        }
        return false
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if(requestCode==myRequestCode)
        {
            if(grantResults.isNotEmpty() && grantResults[0]==PackageManager.PERMISSION_GRANTED)
            {
                getLastLocation()
            }
        }
    }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Alex
  • 1

1 Answers1

0

I haven't used location services in a long, long time, so I'm just looking at the documentation for 'LocationRequest.Builder` and guessing at your equivalent code because it looks self-explanatory. Builders are a common pattern, used more often in Java-based APIs like this one than they are used in pure-Kotlin APIs. You can look up "java builder pattern" to read about it.

private fun NewLocation() { 
    val locationRequest = LocationRequest.Builder()
        .setPriority(Priority.PRIORITY_HIGH_ACCURACY)
        .setIntervalMillis(0L)
        .setMinUpdateIntervalMillis(0L)
        .setMaxUpdates(1)
        .build()
    mfusedlocation = LocationServices.getFusedLocationProviderClient(this)
    mfusedlocation.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
}

FYI since you're working on a portfolio:

  • Function names in Kotlin start with a verb and lower-case letter by convention. Or if it returns a modified copy of an object, you can use a past participle instead of a phrase starting with a verb. For example, I would rename NewLocation() to something like beginLocationRequest().

  • The mSomething pattern of naming variables (putting abbreviations in front of variable names) is called Hungarian notation. m stands for "member", but Kotlin properties are not even called member variables. I've never seen Hungarian notation used in Kotlin before, and it is rarely used in Java. It is widely regarded as making code less readable, especially with modern IDEs. I would advise against using it in a portfolio project as it is more likely to damage the impression you want to give than it is to help, especially if you are using it inconsistently.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • Very good comment. Just regarding your Hungarian notation comment: The location api's Global variable for last location is `mCurrentLocation`. So he can probably be excused for following the Api's convention. – Hmerman6006 Aug 27 '23 at 12:40