【问题标题】:How to create a location request?如何创建位置请求?
【发布时间】:2022-11-29 05:18:37
【问题描述】:

大家好,我是这个游戏的新手,目前正在尝试为我的投资组合开发一个天气应用程序,但是我遇到了一些问题。显然 locationrequest 方法已被弃用,我想知道如何替代地请求它。不幸的是,我找不到任何具体的内容,因为 LocationRequest.create().apply 也已弃用,取而代之的是 LocationRequest.Builder() 。但是,我无法从谷歌的指南中弄清楚。

到目前为止,这是我的代码(请随时纠正我,我很乐意听到反馈):

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()
            }
        }
    }
}

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    我已经很长时间没有使用位置服务了,所以我只是查看 documentation for 'LocationRequest.Builder` 并猜测您的等效代码,因为它看起来不言自明。构建器是一种常见的模式,在像这样的基于 Java 的 API 中比在纯 Kotlin API 中更常用。您可以查找“java builder pattern”来了解它。

    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())
    }
    

    仅供参考,因为您正在处理投资组合:

    • Kotlin 中的函数名称按照惯例以动词和小写字母开头。或者,如果它返回一个对象的修改副本,您可以使用过去分词代替以动词开头的短语。例如,我会将 NewLocation() 重命名为类似 beginLocationRequest() 的名称。

    • mSomething变量命名模式(在变量名前加缩写)被称为匈牙利符号. m 代表“成员”,但 Kotlin 属性甚至不称为成员变量。我以前从未见过在 Kotlin 中使用匈牙利表示法,在 Java 中也很少使用。它被广泛认为会降低代码的可读性,尤其是对于现代 IDE。我建议不要在投资组合项目中使用它,因为它更有可能损害你想要给人的印象而不是帮助,特别是如果你不一致地使用它。

    【讨论】:

      猜你喜欢
      • 2022-10-07
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多