使用 fusedLocationAPI.requestLocationUpdates 不会调用 onLocationChanged

2023-12-27

我一直在尝试使用 fusedLocationApi 来获取我当前的位置。我正在使用带有模拟 Nexus 6 的 android studio。根据在线文档https://developer.android.com/training/location/receive-location-updates.html?hl=es 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; // 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);
}

清单文件

<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" />

摇篮构建:

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'
}

您确定您的 GPS 已打开吗?您可以尝试通过 Google 浏览此示例项目Google https://github.com/googlesamples/android-play-location/blob/master/LocationUpdates/app/src/main/java/com/google/android/gms/location/sample/locationupdates/MainActivity.java在 GitHub 上。在此项目中,他们还提供了用于检查位置服务是否已启用的代码。如果没有,用户将收到一条消息,以便他们可以激活其定位服务。

/*
 * 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");
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 fusedLocationAPI.requestLocationUpdates 不会调用 onLocationChanged 的相关文章

  • 嵌套枚举是静态的吗?

    读书时这个问题 https stackoverflow com questions 25011061 why can enum implementations not access private fields in the enum cl
  • 如何使用 JAVA 和 ADB 命令检查 Appium 中键盘是否打开

    我正在尝试检查 Android 默认键盘是否打开 我没有找到任何可以在 Appium 中使用 JAVA 和 ADB 命令检查键盘的内容 我发现这个 ADB 命令可以检查键盘是否打开 adb shell dumpsys input metho
  • EditText 的高度不会扩展到其父级的高度

    我在滚动视图中放置了编辑文本 高度 match parent并期望它的高度等于滚动视图 但事实并非如此 它的高度就像wrap content这意味着如果 EditText 中没有文本 我必须将光标指向要弹出的软键盘的第一 行 我想要的是我可
  • 找不到资源矢量绘图的异常

    我将在某些设备上运行我的应用程序 其崩溃日志如下 01 04 16 54 02 206 7466 7466 com lawnmowers E AndroidRuntime FATAL EXCEPTION main Process com l
  • Tomcat JDBC 池中没有足够的空闲连接

    给定以下 Tomcat JDBC 连接设置
  • 如何加快 jar 签名者的速度?

    我使用 ant 来签署我的 jars 以进行网络启动部署 Ant signjar 在 Web 启动签名时非常慢 如何加快签名过程 我找到了一种可能的解决方案 早些时候 在构建脚本 ant signjar 中 按顺序调用所有 jar 我们使用
  • Ubuntu 的打包 - Web 应用程序

    Web 应用程序没有与 C 或类似文件不同的 make 文件 但是 它需要放置在特定的目录中 例如 var www 我是 Linux 打包新手 所以我的问题是 如何将我的应用程序打包到 deb 中 以便在安装时将其放入 etc myprog
  • 使用java读取Excel工作表的单列

    我有一张 Excel 表格 我想编写一个方法 该方法将参数作为要读取的列号 并返回一个由该列中的所有数据组成的数组 然后将该列元素放置在 xml 工作表中 我怎样才能编写一个方法来做到这一点 使用 Apache POI 您可以在他们的使用页
  • 从 AlertDialog 返回值

    我想构建一个函数来创建 AlertDialog 并返回用户输入的字符串 这是我用于创建对话框的函数 如何返回该值 String m Text private String openDialog String title AlertDialo
  • Restful WS 中的 WSDL 等价物是什么?如果没有,消费者如何生成所需的客户端类?

    比如说 我在java中有生产者 在 net中有消费者 生产者有一个方法 需要 员工作为方法参数并在数据库中创建员工 对于基于 SOAP 的 ws dot net 客户端将调用 WSDL 并创建存根 包括 dot net 中的员工数据表示 现
  • jsf 中的类型未找到属性

    我正在尝试调用 jsf 中使用 primefaces 的属性 但我有错误 500 在托管bean PersonelBean 类型上找不到 我正在使用 hibernate jsf 和 spring PersonelBean java Mana
  • 如何强制初始化 Hibernate JPA 代理以在 JSON 调用中使用它

    我有一个 Spring 3 JPA 2 0 应用程序 在我的 Controller我需要一个初始化的对象 但我有代理 我需要能够以编程方式初始化它 我需要类似的功能org hibernate Hibernate initialize Obj
  • 如何映射 Map

    I tried ManyToMany cascade CascadeType ALL Map
  • Exif 方向标签返回 0

    我正在开发一个自定义相机应用程序 我面临以下问题 当我尝试使用检索方向时ExifInterface 它总是返回 0 ORIENTATION UNDEFINED 这使我无法将图像旋转到正确的状态 从而无法正确显示 我使用示例代码来设置相机旋转
  • Web服务连接超时和请求超时之间的区别

    WebClientTestService service new WebClientTestService int connectionTimeOutInMs 5000 Map
  • 使用 Tomcat 和 gradle 进行休眠

    免责声明 我是 Java 新手 我正在尝试使用 Tomcat 和 Gradle 设置 Hibernate 构建运行正确 但看起来像persistence xml文件未被读取 我的项目结构如下 build gradle src main ja
  • Web 应用程序似乎启动了名为 [22] 的线程,但未能停止它。这很可能造成内存泄漏

    我有一个 Web 应用程序 后端有 Servlet 部署在 tomcat 上 该应用程序是简单的java应用程序 我经常在服务器日志中看到此错误 严重 Web 应用程序似乎启动了一个名为 22 但未能阻止它 这很有可能 造成内存泄漏 是否存
  • Admob - 没有广告可显示

    你好 我尝试制作一些在 Android 手机上显示广告的示例程序 并尝试在 v2 2 的模拟器上测试它 代码中的一切似乎都很好 但调试器中的 AdListener 表示 响应消息为零或空 onFailedToReceiveAd 没有广告可显
  • iOS 版 Google 地图 sdk 中折线的轮廓

    我的要求是在地图上显示一条绿色折线 但当地图切换到卫星视图时 绿色折线变得不清楚 我无法改变折线的颜色 因此 为了将折线与背景 地图的卫星视图 区分开来 我需要为折线绘制白色轮廓 我浏览了 GMSPolyline 类的文档 但找不到任何可以
  • SambaFileInputStream 和 FileInputStream 有什么不同?

    我需要从 samba 服务器流式传输视频 并且我使用 nanohttpd 在我的项目中创建简单的服务器 当我使用本地文件中的 fileinputstream 时 视频视图可以按设置播放视频 http localhost 8080 publi

随机推荐

  • 如何在颤动的滚动视图中将容器或任何其他小部件固定在应用栏下方

    我希望在滚动屏幕时将小部件放置在应用程序下方 屏幕包含一个具有灵活空间的浮动应用程序栏 sliverappbar 其下方是一个具有任何容器或选项卡视图的容器 链接中的视频是我想要的效果的示例 好吧 我想我现在明白你了 您需要实现 Custo
  • 订阅类别流,事件永远不会出现在订阅客户端中

    第一次使用获取事件存储 http geteventstore com阅读文档后 我遇到了一个问题 事件永远不会出现在我的订阅客户端上 由于我错过了一个配置步骤 这是可能的 拥有这个控制台应用程序客户端 public class EventS
  • 是否有 .NET 4.5 相当于:Storagefile.Openasync

    我爱上了异步和等待 但是我无法弄清楚如何在不使用 Task Run 的情况下等待文件打开 似乎有一个WRT 中的 API http msdn microsoft com en us library windows apps windows
  • 错误处理(向客户端发送 ex.Message)

    我有一个 ASP NET Core 1 0 Web API 应用程序 并试图弄清楚如果我的控制器调用的函数出错 如何将异常消息传递给客户端 我尝试了很多东西 但没有任何实现IActionResult 我不明白为什么这不是人们需要的常见东西
  • AWS 上的 Kubernetes PVC 与 ReadWriteMany

    我想在 AWS 上设置 PVC 我需要ReadWriteMany作为访问模式 不幸的是 EBS仅支持ReadWriteOnce 我该如何解决这个问题 我看到 AWS EFS 有一个测试版提供商 它支持ReadWriteMany 但正如所说
  • 如何强制我想要的任何显示分辨率/时间?

    我无法找到一种方法来在我的 C 程序中强制执行我想要的任何显示分辨率 计时 我运行的是带有 GeForce 210 显卡的 Windows 7 我当前实现这些自定义分辨率的方法是使用驱动程序 GUI 手动添加自定义分辨率 然后使用 Wind
  • Eclipse 找不到 std c++ 库

    我有一台Windows8机器 mingw安装在c mingw Eclipse 确实成功编译了程序 但它认为包含错误的行在编译时没有问题 Eclipse 本身没有找到库 当我第一次在 Eclipse 中构建一个安装了 CDT 组件的项目时 它
  • this 指针不能在构造函数中使用别名:

    我正在学习 C 中的继承 我遇到了以下情况陈述 https en cppreference com w cpp language this 换句话说 this 指针不能在构造函数中使用别名 extern struct D d struct
  • 访问 ASP.Net MVC 中的“Application”对象来存储应用程序范围的变量

    如何在 ASP net MVC 中存储应用程序范围内的变量或对象 在常规 ASP 中 您有 Application 对象 显然在 ASP net 中也是如此 我正在使用 ASP net MVC 2 在控制器中 您应该能够执行以下操作 thi
  • 更改 Woocommerce 3 中的订单商品价格

    我需要更改 woocommerce 订单中的商品价格 但我发现的所有内容都是更改购物车中的价格 但这不是我需要的 因为我需要在结帐过程后进行更改 有人可以告诉我如何做到这一点吗 你需要使用新的CRUD 设置器方法 https github
  • 如何将值添加到地图内的集合? [关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我有这张地图Map
  • 为什么我不能打开一个类,对枚举进行一次隐式转换

    我想知道为什么到枚举值的单个隐式转换的工作方式与转换到系统类型时的工作方式不同 我看不出任何技术原因 但也许比我聪明的人可以为我提供一些启示 以下无法编译 A value of an integral type expected and C
  • Clojure 中可以创建循环引用吗?

    忽略本机互操作和瞬态 是否可以在 Clojure 中创建任何包含直接循环引用的数据结构 看起来不可变的数据结构只能包含对自身先前版本的引用 是否有任何 Clojure API 可以创建一个引用自身的新数据结构 Scheme 具有 letre
  • 关于SQL查询的问题

    我正在做一个涉及oracle数据库的小项目 我有下表 CUSTOMER Cid CName City Discount PRODUCT Pid PName City Quantity Price ORDERS OrderNo Month C
  • 计算从左上角到右下角任意方向移动的移动次数

    我在面试中遇到了一个问题 这是我发现的类似问题 所以我想在这里问 问题是 有一个机器人位于 N X N 网格中的 1 1 处 机器人可以向左 右 上 下任意方向移动 我还得到了一个整数 k 它表示路径中的最大步数 我必须计算以 k 或更少的
  • OverflowError Python int 太大,无法转换为 C long

    usr bin python import sys math n input enter a number to find the factors j flag b 0l False 0l for b in xrange 1 n 1 a n
  • 如何在android中设置ListView所选项目交替文本颜色

    我有一个带有图像视图和文本视图的自定义列表视图 我希望当用户选择一个项目时 文本视图颜色应该改变 而所有其他文本视图应该保持默认 这是我的 xml 列表视图 xml
  • 带代理的 Selenium 返回空网站

    我无法通过代理从使用 selenium 的网站获取页面源 HTML 这是我的代码 from selenium webdriver chrome options import Options from selenium import webd
  • VS 2008 Intellisense 右键单击​​时挂起

    我在 Visual Studio 2008 SP1 中有一个相当大的 C 解决方案 当我右键单击时 我在状态栏中看到更新的智能感知 整个工作室冻结了几分钟 2005 年右键单击效果很好 有什么解决方法吗 在大型项目上更新智能感知只会降低生产
  • 使用 fusedLocationAPI.requestLocationUpdates 不会调用 onLocationChanged

    我一直在尝试使用 fusedLocationApi 来获取我当前的位置 我正在使用带有模拟 Nexus 6 的 android studio 根据在线文档https developer android com training locati