【问题标题】:How to get Android current location "only on demand" using Location Manager but without Location Listener?如何使用位置管理器但没有位置监听器“仅按需”获取 Android 当前位置?
【发布时间】:2016-03-09 16:52:26
【问题描述】:

我的应用不需要即时位置更新。只有在(1)应用程序启动时才需要位置; (2)打开特定的活动/片段; (3)用户点击“获取我的位置”按钮。

标准是:当需要时,位置必须快速到达,即使它是粗略的(如果可能的话)最低电池消耗。我打算使用以下方法:

public void getLocation() {
        LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        Location location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

        if(location != null) {
            //save the location to shared prefs to use when needed
            return;
        }

        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        if(location != null) {
            //save the location to shared prefs to use when needed
            return;
        }

        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if(location != null) {
            //save the location to shared prefs to use when needed
            return;
        }

        // if reached that point the location cannot be got!!
    }

计划是在每次应用启动、特定页面被激活或用户想要获取当前位置时调用该方法。除非这些操作触发位置更新,否则旧位置或无位置就足够了。这种方法有意义吗?我可以在不实现位置侦听器和/或调用方法“requestLocationUpdates()”的情况下做到这一点吗?我担心的是“getLastKnownLocation()”在调用时可能不会给出当前位置,因为我不确定来自提供商的“最后已知位置”更新的频率或条件。

非常感谢任何建议和cmets。

【问题讨论】:

  • 将位置存储在共享首选项中并在必要时检索它们似乎是个好主意

标签: android location


【解决方案1】:

使用以下代码通过 Google 位置服务 API 获取当前和最后已知位置

//Global Variable
Location location;
public class MainActivity extends ActionBarActivity implements
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

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

    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds

   @Override
protected void onResume() {
    super.onResume();
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onConnected(Bundle bundle) {
    location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    } else {
        handleNewLocation(location);
    }
}

  @Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    } else {
        Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

AnyActivity.class

MainActivity main = new MainActivity();
Location location = main.location;

【讨论】:

  • 感谢您的快速回答。您的代码似乎在不断地收听位置更新。我不喜欢那样。有多个片段和活动。我需要一个全局方法,只要我需要从应用程序中的任何活动或片段中获取位置,我就可以调用它。除非我调用该方法,否则不需要更新。
  • 在应用程序首次运行时运行此代码,然后将其存储在 Shared Prefs 中。创建一个全局变量来存储位置,您可以从您需要的任何活动或片段中请求该变量
  • 这是有道理的。只有在打开主要活动时才会更新位置。如果用户在没有关闭应用程序或打开主要活动的情况下更改了她/他的位置怎么办?假设用户在公共汽车/火车上并启动应用程序(主要活动)并获取位置,然后切换到另一个活动,当这个新活动打开时,车辆行驶 20 英里。那时位置已更新,但我们仍然拥有旧位置。如果用户切换到他需要当前位置的第三个页面,他仍然拥有旧页面。那么我们是否需要为所有活动设置监听器?
  • Thats very good! I will certainly consider it. I wonder, though, what is wrong with my approach of doing all that without a listener since I dont 需要位置更新,除非用户采取行动?
  • 我会为你的好建议投赞成票,但你的回答没有回答我原来的问题。可能其他人会提供另一种解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 2013-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多