【问题标题】:location updates from an intent service(onLocationChanged is never getting called)来自意图服务的位置更新(永远不会调用 onLocationChanged)
【发布时间】:2013-11-26 16:54:20
【问题描述】:

我的问题和这个一样, Android LocationLister implemented in IntentService never execute the OnLocationChanged() method 但不幸的是我无法理解这一点,我用于从 android 设备获取位置的代码在 Activity 中运行良好,但是当涉及到 Intent 服务时,永远不会调用 onLocationChanged() 方法。

服务的其他部分运行良好,因为我还在同一服务中实现了通知管理器示例以跟踪各种变量的值,但由 onLocationChanged() 修改的变量永远不会被修改,描绘该方法没有被执行。 请帮忙

【问题讨论】:

    标签: android intentservice locationlistener


    【解决方案1】:

    IntentService 不会等待您的 onLocationChangedListener,如果您的 IntentService 的最后一部分是取消注册您的位置更改侦听器,那么这就是您的问题。

    您可以做的是将您的 IntentService 转换为常规服务。检查不同的操作,其中一个是您收到新位置时的下一步。

    private class MyLocationListener implements LocationListener {
        public void onLocationChanged(Location location) {
            Intent intent = new Intent(this,MyService.class);
            intent.setAction("LOCATION_RECEIVED");
            intent.putExtra("locationUpdate",location);
            locationManager.removeUpdates(this);
            this.startService(intent);
        }
        public void onStatusChanged(String s, int i, Bundle bundle) {}
        public void onProviderEnabled(String s) {}
        public void onProviderDisabled(String s) {}
    }
    

    在您的服务上...

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent!=null) {
            String action = intent.getAction();
                if (action!= null) {
                    if (action.equals("LOCATION_RECEIVED")) {
                        Location location = null;
                        if (intent.hasExtra("locationUpdate")) {
                            location = intent.getExtras().getParcelable("locationUpdate");
                            //Process new location updates here
                        }
    

    另一种方法是在 LocationListener 上使用 Pending Intent,但它的效果与上面的代码相同。第三种方法是从 OnLocationChangedListener 向 IntentService 发布一个 runnable(我个人没有尝试过这个。)

    如果您能在这里分享一些代码,我们将不胜感激。如果您还有其他问题。当我从事类似项目时,我可能会有所帮助,从服务获取位置。

    【讨论】:

      【解决方案2】:

      据我所知,位置传感器需要在 UI 线程中运行。一个 Activity 在那里运行,但一个 Service 在后台运行。

      在您的代码中添加一些密集的日志记录和异常处理以找出答案。

      如果这是原因,那么有一种方法可以创建和注册Looper。告诉我,我可以去我的代码中搜索

      【讨论】:

      • 我在 stackoverflow 上的某处读到我的代码可能太快以至于 onLocationChanged() 方法可能从未返回,因此服务在它之前被破坏,但我得到了我需要的东西,我从 getLastKnownLocation() 检索到最后的位置更新,现在我的应用程序运行良好,谢谢!
      猜你喜欢
      • 2011-11-06
      • 2023-03-18
      • 2012-02-18
      • 2013-01-02
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多