onLocationChanged不会使用fusedLocationAPI.requestLocationUpdates进行调用 [英] onLocationChanged does not get called using fusedLocationAPI.requestLocationUpdates

查看:185
本文介绍了onLocationChanged不会使用fusedLocationAPI.requestLocationUpdates进行调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用fusedLocationApi来获取我的当前位置。我使用的是带有仿真Nexus 6的android studio。根据在线文档 https://developer.android.com/training/location/receive-location-updates.html?hl=es
我们可以请求位置更新:



FusedLocationApi.requestLocationUpdates



并回调至:

onLocationChanged位置位置)



但是,onLocationChanged根本没有被调用。如果是这样,它会在日志中打印一些东西,因为我在那里放了一条Log.d行。请注意,startLocationUpdates()确实被调用。以下是我的代码。如果有人能够对此有所了解,那将会很棒=)我对Android非常陌生,所以我有点无知。这可能是模拟器(GPS,.. idk)导致这个问题吗?

  public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationListener {

private GoogleMap mMap; //谷歌地图工作得很好,就像默认项目
private GoogleApiClient mGoogleApiClient;
public static final String TAG = MapsActivity.class.getSimpleName();
private LocationRequest mLocationRequest;
private static final int REQUEST_LOCATION = 2;
私人位置位置;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment =(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
。建立();

mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(1000)
.setFastestInterval(100);
}

@Override
public void onConnected(@Nullable Bundle bundle){
if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION)! = PackageManager.PERMISSION_GRANTED
&&& ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String [] {android。 Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(location == null){
startLocationUpdates();
}
else {
handleNewLocation(location);
};



保护无效startLocationUpdates(){
Log.d(TAG,请求位置更新);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
}

@覆盖
public void onLocationChanged(位置位置){
String msg =更新位置:+
Double.toString(位置。 getLatitude())+,+
Double.toString(location.getLongitude());
Log.d(TAG,msg);

manifest.xml

 < uses-permission android:name =android.permission.INTERNET/> 
< uses-permission android:name =android.permission.ACCESS_NETWORK_STATE/>
< uses-permission android:name =android.permission.ACCESS_FINE_LOCATION/>
< uses-permission android:name =android.permission.ACCESS_COARSE_LOCATION/>

Gradle构建:

  dependencies {
compile fileTree(dir:'libs',include:['* .jar'])
testCompile'junit:junit:4.12'
compile'c​​om .android.support:appcompat-v7:24.0.0'
compile'c​​om.google.android.gms:play-services:9.0.0'
}


解决方案

您确定您的GPS已打开吗?您可以尝试通过Google进行此示例项目 Google 在GitHub上。在这个项目中,他们还提供了检查位置服务是否启用的代码。如果他们不是,用户将会收到一条消息,以便他们可以激活他们的位置服务。

  / * 
*版权所有(C)2012 Android开放源码项目
*
*根据Apache许可证版本2.0(许可证)获得许可;
*除遵守许可证外,您不得使用此文件。
*您可以在
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*获得许可证副本根据适用法律要求或书面同意,根据许可分配的软件
*以原样基础,
*分发,不附有任何明示或暗示的担保或条件。
*请参阅许可证以了解许可证下特定语言的管理权限和
*限制。
* /

package com.example.mapdemo;

导入com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;

导入android.Manifest;
导入android.content.pm.PackageManager;
导入android.os.Bundle;
导入android.support.annotation.NonNull;
导入android.support.v4.app.ActivityCompat;
导入android.support.v4.content.ContextCompat;
导入android.support.v7.app.AppCompatActivity;
导入android.widget.Toast;

/ **
*此演示显示如何使用GMS位置检查用户位置的更改。
*我的位置按钮使用GMS位置来设置代表用户位置的蓝点。
* {@link android.Manifest.permission#ACCESS_FINE_LOCATION}的权限在运行
*时被请求。如果权限未被授予,则活动结束并显示一条错误消息。
* /
public class MyLocationDemoActivity extends AppCompatActivity
implements
OnMyLocationButtonClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {

/ * *
*请求位置权限请求的代码。
*
* @see #onRequestPermissionsResult(int,String [],int [])
* /
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

/ **
*表示请求的权限是否在
返回后被拒绝的标志。{@link #onRequestPermissionsResult(int,String [],int [])} 。
* /
private boolean mPermissionDenied = false;

私有GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location_demo);

SupportMapFragment mapFragment =
(SupportMapFragment)getSupportFragmentManager()。findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap map){
mMap = map;

mMap.setOnMyLocationButtonClickListener(this);
enableMyLocation();
}

/ **
*如果已授予罚款位置权限,则启用我的位置图层。
* /
private void enableMyLocation(){
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
/ /访问该位置的权限丢失。
PermissionUtils.requestPermission(this,LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION,true);
} else if(mMap!= null){
//访问位置已被授予应用程序。
mMap.setMyLocationEnabled(true);



@Override
public boolean onMyLocationButtonClick(){
Toast.makeText(this,MyLocation button clicked,Toast.LENGTH_SHORT) 。显示();
//返回false,以便我们不消耗事件并且默认行为仍然发生
//(相机动画到用户的当前位置)。
返回false;


$ b @Override
public void onRequestPermissionsResult(int requestCode,@NonNull String []权限,
@NonNull int [] grantResults){
if(requestCode!= LOCATION_PERMISSION_REQUEST_CODE){
return;
}

if(PermissionUtils.isPermissionGranted(permissions,grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)){
//启用我的位置图层,如果权限有被授予。
enableMyLocation();
} else {
//片段恢复时显示丢失的权限错误对话框。
mPermissionDenied = true; ();
}
}

@Override
保护无效的onResumeFragments(){
super.onResumeFragments();
if(mPermissionDenied){
//权限未被授予,显示错误对话框。
showMissingPermissionError();
mPermissionDenied = false;
}
}

/ **
*显示一个对话框,其中包含错误消息,说明位置权限丢失。
* /
private void showMissingPermissionError(){
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(),dialog);
}

}


I've been trying to use the fusedLocationApi to get my current location. I'm using android studio with an emulated Nexus 6. According to the online documentation https://developer.android.com/training/location/receive-location-updates.html?hl=es we can request location updates using:

FusedLocationApi.requestLocationUpdates

and the callback goes to:

onLocationChanged(Location location)

However, onLocationChanged is not getting called at all. If it did, it would print something in the log cause I put a Log.d line there. Note that startLocationUpdates() does get called. Below is my code. It would be great if someone could shed some light on this =) I'm really new to Android so I'm a bit clueless rn. Could it be something about the emulator (GPS,.. idk) that is causing this issue?

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener {

private GoogleMap mMap; // google map works well just as default project
private GoogleApiClient mGoogleApiClient;
public static final String TAG = MapsActivity.class.getSimpleName();
private LocationRequest mLocationRequest;
private static final int REQUEST_LOCATION = 2;
private Location location;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(1000)
            .setFastestInterval(100);
} 

@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_LOCATION);
    } else {
        location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            startLocationUpdates();
        }
        else {
            handleNewLocation(location);
        };
    }
}

protected void startLocationUpdates() {
    Log.d(TAG, "Requesting location updates");
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}    

@Override
public void onLocationChanged(Location location) {
    String msg = "Updated Location: " +
            Double.toString(location.getLatitude()) + "," +
            Double.toString(location.getLongitude());
    Log.d(TAG, msg);
}

manifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Gradle build:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.google.android.gms:play-services:9.0.0'
}

解决方案

Are you sure your GPS is turned on? You can try going through this sample project by Google Google on GitHub. In this project they have also provided code for checking if Location services are enabled. If they are not, user will be given a message so they can activate their location services.

/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.mapdemo;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

/**
 * This demo shows how GMS Location can be used to check for changes to the users location.  The
 * "My Location" button uses GMS Location to set the blue dot representing the users location.
 * Permission for {@link android.Manifest.permission#ACCESS_FINE_LOCATION} is requested at run
 * time. If the permission has not been granted, the Activity is finished with an error message.
 */
public class MyLocationDemoActivity extends AppCompatActivity
        implements
        OnMyLocationButtonClickListener,
        OnMapReadyCallback,
        ActivityCompat.OnRequestPermissionsResultCallback {

    /**
     * Request code for location permission request.
     *
     * @see #onRequestPermissionsResult(int, String[], int[])
     */
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

    /**
     * Flag indicating whether a requested permission has been denied after returning in
     * {@link #onRequestPermissionsResult(int, String[], int[])}.
     */
    private boolean mPermissionDenied = false;

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_location_demo);

        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {
        mMap = map;

        mMap.setOnMyLocationButtonClickListener(this);
        enableMyLocation();
    }

    /**
     * Enables the My Location layer if the fine location permission has been granted.
     */
    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission to access the location is missing.
            PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                    Manifest.permission.ACCESS_FINE_LOCATION, true);
        } else if (mMap != null) {
            // Access to the location has been granted to the app.
            mMap.setMyLocationEnabled(true);
        }
    }

    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
        // Return false so that we don't consume the event and the default behavior still occurs
        // (the camera animates to the user's current position).
        return false;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }

        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Enable the my location layer if the permission has been granted.
            enableMyLocation();
        } else {
            // Display the missing permission error dialog when the fragments resume.
            mPermissionDenied = true;
        }
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (mPermissionDenied) {
            // Permission was not granted, display error dialog.
            showMissingPermissionError();
            mPermissionDenied = false;
        }
    }

    /**
     * Displays a dialog with error message explaining that the location permission is missing.
     */
    private void showMissingPermissionError() {
        PermissionUtils.PermissionDeniedDialog
                .newInstance(true).show(getSupportFragmentManager(), "dialog");
    }

}

这篇关于onLocationChanged不会使用fusedLocationAPI.requestLocationUpdates进行调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆