onLocationChanged方法在Android中不起作用

onLocationChanged方法在Android中不起作用,android,google-maps,google-maps-android-api-2,Android,Google Maps,Google Maps Android Api 2,我正在尝试获取用户位置并在地图上用标记显示,但方法onLocationChanged不起作用。。该位置只能手动设置,我的意思是,我必须将经度和纬度设置为指定值,但它无法从用户位置获取 以下是logcat屏幕: 这是我的密码 package com.example.user.maps1 import android.content.Context import android.content.pm.PackageManager import android.location.Location im

我正在尝试获取用户位置并在地图上用标记显示,但方法onLocationChanged不起作用。。该位置只能手动设置,我的意思是,我必须将经度和纬度设置为指定值,但它无法从用户位置获取

以下是logcat屏幕:

这是我的密码

package com.example.user.maps1
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.util.Log
import android.widget.Toast

import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps)
    // Obtain the SupportMapFragment and get notified when the map is ready         to be used.
    val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)
    getPermission()
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap

    // Add a marker in Sydney and move the camera
    val sydney = LatLng(-34.0, 151.0)
    mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}

var accessCode = 222
fun getPermission(){
    if(Build.VERSION.SDK_INT >= 23){
        if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            requestPermissions(arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION) , accessCode)
            return
        }
        getUserLocation()
    }

}

fun getUserLocation(){

    var myLocation = mylocationListener()

    var locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager


    if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3, 3f, myLocation)
    }


    var mythread=myThread()
    mythread.start()


}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {

    when(requestCode){

        accessCode->{

            if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
                getUserLocation()
            }else{
                Toast.makeText(this,"We cannot access to your location",Toast.LENGTH_LONG).show()
            }
        }
    }

    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}

var location:Location?=null
inner class mylocationListener: LocationListener {

    constructor(){
        location= Location("Start")
        //location!!.longitude=0.0
        //location!!.latitude=0.0
    }
    override fun onLocationChanged(p0: Location?) {
        location=p0
    }

    override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onProviderEnabled(p0: String?) {
        // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onProviderDisabled(p0: String?) {
        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

}
inner class myThread:Thread{

    constructor():super(){}

    override fun run(){

            try {
                runOnUiThread {

                    mMap!!.clear()

                    // show me
                    val sydney = LatLng(location!!.latitude/*55.7558*/, location!!.longitude/*37.6173*/)
                    mMap!!.addMarker(MarkerOptions()
                            .position(sydney)
                            .title("Hello WOOORLD")
                            .snippet(" here is my location")
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.mario)))
                    mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 12f))

                }

                Thread.sleep(10000)

            }catch (ex:Exception){
                Log.e("00000000000000",ex.message.toString())
                //println(ex.message.toString())
            }


    }

}


}
package com.example.user.maps1
导入android.content.Context
导入android.content.pm.PackageManager
导入android.location.location
导入android.location.LocationListener
导入android.location.LocationManager
导入android.os.Build
导入android.support.v7.app.AppActivity
导入android.os.Bundle
导入android.support.v4.app.ActivityCompat
导入android.util.Log
导入android.widget.Toast
导入com.google.android.gms.maps.CameraUpdateFactory
导入com.google.android.gms.maps.GoogleMap
导入com.google.android.gms.maps.OnMapReadyCallback
导入com.google.android.gms.maps.SupportMapFragment
导入com.google.android.gms.maps.model.BitmapDescriptorFactory
导入com.google.android.gms.maps.model.LatLng
导入com.google.android.gms.maps.model.MarkerOptions
类MapsActivity:AppCompatActivity(),OnMapReadyCallback{
私有lateinit var mMap:GoogleMap
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity\u映射)
//获取SupportMapFragment,并在地图准备好使用时收到通知。
val mapFragment=supportFragmentManager
.findFragmentById(R.id.map)作为SupportMapFragment
getMapAsync(此)
getPermission()
}
/**
*一旦可用,就可以操纵贴图。
*当映射准备好使用时,将触发此回调。
*这是我们可以添加标记或线条、添加侦听器或移动摄影机的地方。在这种情况下,
*我们只是在澳大利亚悉尼附近加了一个标记。
*如果设备上未安装Google Play服务,系统将提示用户安装
*它位于SupportMapFragment内。此方法仅在用户
*已安装Google Play服务并返回应用程序。
*/
在mapready上覆盖乐趣(谷歌地图:谷歌地图){
mMap=谷歌地图
//在Sydney添加一个标记并移动相机
val sydney=LatLng(-34.0151.0)
mMap.addMarker(MarkerOptions().position(sydney).title(“sydney中的标记”))
mMap.moveCamera(CameraUpdateFactory.newLatLng(悉尼))
}
var accessCode=222
fun getPermission(){
如果(Build.VERSION.SDK_INT>=23){
if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予){
requestPermissions(arrayOf(android.Manifest.permission.ACCESS\u FINE\u LOCATION)、accessCode)
返回
}
getUserLocation()
}
}
有趣的getUserLocation(){
var myLocation=mylocationListener()
var locationManager=getSystemService(Context.LOCATION\u服务)作为locationManager
if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS\u FINE\u LOCATION)==PackageManager.permission\u已授予){
locationManager.RequestLocationUpdate(locationManager.GPS_提供程序,3,3f,myLocation)
}
var mythread=mythread()
mythread.start()
}
重写onRequestPermissionsResult(请求代码:Int,权限:Array,GrantResult:IntArray){
何时(请求代码){
访问代码->{
if(grantResults[0]==已授予PackageManager.权限){
getUserLocation()
}否则{
Toast.makeText(这是“我们无法访问您的位置”,Toast.LENGTH\u LONG.show())
}
}
}
super.onRequestPermissionsResult(请求代码、权限、GrantResult)
}
变量位置:位置?=null
内部类mylocationListener:LocationListener{
构造函数(){
位置=位置(“开始”)
//位置!!经度=0.0
//位置!!纬度=0.0
}
更改了位置(p0:位置?){
位置=p0
}
重写状态更改(p0:String?,p1:Int,p2:Bundle?){
//TODO(“未实现”)//要更改已创建函数的主体,请使用文件|设置|文件模板。
}
覆盖已提供已启用的乐趣(p0:字符串?){
//TODO(“未实现”)//要更改已创建函数的主体,请使用文件|设置|文件模板。
}
已禁用override fun onProviderDisabled(p0:字符串?){
//TODO(“未实现”)//要更改已创建函数的主体,请使用文件|设置|文件模板。
}
}
内部类:线程{
构造函数():super(){}
覆盖趣味跑(){
试一试{
runOnUiThread{
mMap!!.clear()
//给我看看
val sydney=LatLng(位置!!.lation/*55.7558*/,位置!!.longitude/*37.6173*/)
mMap!!.addMarker(MarkerOptions()
.职位(悉尼)
.title(“你好,WOOORLD”)
.snippet(“这是我的位置”)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mario)))
mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(悉尼,12f))
}
线程。睡眠(10000)
}捕获(例如:异常){
Log.e(“00000000000000”,例如message.toString())
//println(例如message.toString())
}
}
}
}

如果您需要一次定位,可以使用下面的类。你只需要这样称呼它

SingleShotLocationProvider.requestSingleUpdate(context, this);
阶级

public class SingleShotLocationProvider {
public static interface LocationCallback {
    public void onNewLocationAvailable(GPSCoordinates location);
}

// calls back to calling thread, note this is for low grain: if you want higher precision, swap the
// contents of the else and if. Also be sure to check gps permission/settings are allowed.
// call usually takes <10ms
public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
    final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (isNetworkEnabled) {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, 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;
        }
        locationManager.requestSingleUpdate(criteria, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        }, null);
    } else {
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (isGPSEnabled) {
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            locationManager.requestSingleUpdate(criteria, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
                }

                @Override public void onStatusChanged(String provider, int status, Bundle extras) { }
                @Override public void onProviderEnabled(String provider) { }
                @Override public void onProviderDisabled(String provider) { }
            }, null);
        }
    }
}


// consider returning Location instead of this dummy wrapper class
public static class GPSCoordinates {
    public float longitude = -1;
    public float latitude = -1;

    public GPSCoordinates(float theLatitude, float theLongitude) {
        longitude = theLongitude;
        latitude = theLatitude;
    }

    public GPSCoordinates(double theLatitude, double theLongitude) {
        longitude = (float) theLongitude;
        latitude = (float) theLatitude;
    }
}
}
公共类SingleShotLocationProvider{
公共静态接口位置回调{
公共位置无效(GPS协调位置);
}
//回调调用线程,注意这是针对低粒度的:如果您想要更高的精度,请交换
//else和if的内容。同时确保检查gps权限/设置是否允许。
//