【问题标题】:Getting the last known location with google play services使用 google play 服务获取最后一个已知位置
【发布时间】:2017-04-30 13:42:37
【问题描述】:

我一直在阅读 android 开发者文档,试图找出如何获取当前位置,特别是 https://developer.android.com/training/location/retrieve-current.html

当我在 android 中创建一个新项目并选择 Map 模板时,onCreate 方法中有代码,然后还有一个 onMapReady 方法。

首先,确认下面的代码是否将地图显示在屏幕上?如果是这样,onMapReady 只是一种方法,然后允许操纵地图吗?

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

在文档 re:get the current location 中有信息 re:building to the GoogleApiClient eg

// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(LocationServices.API)
        .build();
}

文档中指定的其他方法是 onStart、onStop 和 onConnected。这一切都是有道理的,但要制作一个非常基本的获取当前位置应用程序,我是否仍然使用 SupportMapFragment mapFragment = (SupportMapFragment) .... 从 onCreate 中生成地图?还需要 onMapReady 函数吗?哪里是创建 GoogleApiClient 实例的最佳位置?

在随后的文档页面上,还有关于在连接后获取当前位置设置的信息

 LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
     .addLocationRequest(mLocationRequest);

但我只是不确定应该在哪里定义。

最后在 Android Studio 的 Map 模板中,默认类定义为:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback

但在谷歌文档中它被定义为:

公共类 MainActivity 扩展 ActionBarActivity 实现 ConnectionCallbacks, OnConnectionFailedListener

类扩展哪个 Activity 重要吗?

谢谢。

【问题讨论】:

    标签: android google-maps google-play-services


    【解决方案1】:

    我已经使用了预定义的地图活动。您可以通过它获取您最近的已知位置和当前位置。

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            LocationListener {
    
        private GoogleMap mMap;
        GoogleApiClient mGoogleApiClient;
        Location mLastLocation;
        Marker mCurrLocationMarker;
        LocationRequest mLocationRequest;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);
    
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                checkLocationPermission();
            }
            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }
    
    
        /**
         * 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
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    
            //Initialize Google Play Services
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    buildGoogleApiClient();
                    mMap.setMyLocationEnabled(true);
                }
            }
            else {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        }
    
        protected synchronized void buildGoogleApiClient() {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
        }
    
        @Override
        public void onConnected(Bundle bundle) {
    
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(1000);
            mLocationRequest.setFastestInterval(1000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }
    
        }
    
        @Override
        public void onConnectionSuspended(int i) {
    
        }
    
        @Override
        public void onLocationChanged(Location location) {
    
                mLastLocation = location;
                if (mCurrLocationMarker != null) {
                    mCurrLocationMarker.remove();
                }
    
                //Place current location marker
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title("Current Position");
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
                mCurrLocationMarker = mMap.addMarker(markerOptions);
    
                //move map camera
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    
                //stop location updates
                if (mGoogleApiClient != null) {
                    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                }
    
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
    
        }
    
        public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
        public boolean checkLocationPermission(){
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
    
                // Asking user if explanation is needed
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
    
                    // Show an explanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.
    
                    //Prompt the user once explanation has been shown
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            MY_PERMISSIONS_REQUEST_LOCATION);
    
    
                } else {
                    // No explanation needed, we can request the permission.
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            MY_PERMISSIONS_REQUEST_LOCATION);
                }
                return false;
            } else {
                return true;
            }
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode,
                                               String permissions[], int[] grantResults) {
            switch (requestCode) {
                case MY_PERMISSIONS_REQUEST_LOCATION: {
                    // If request is cancelled, the result arrays are empty.
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                        // permission was granted. Do the
                        // contacts-related task you need to do.
                        if (ContextCompat.checkSelfPermission(this,
                                Manifest.permission.ACCESS_FINE_LOCATION)
                                == PackageManager.PERMISSION_GRANTED) {
    
                            if (mGoogleApiClient == null) {
                                buildGoogleApiClient();
                            }
                            mMap.setMyLocationEnabled(true);
                        }
    
                    } else {
    
                        // Permission denied, Disable the functionality that depends on this permission.
                        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                    }
                    return;
                }
    
                // other 'case' lines to check for other permissions this app might request.
                // You can add here other case statements according to your requirement.
            }
        }
    }
    

    在 Android Manifest 中允许网络状态权限和位置权限

    【讨论】:

    • 嗨。感谢那。我的问题是是否曾经调用过 onLocationChanged 以及从何处调用它。在 android 文档中有一个部分 re:
    • 嗨阿维纳什。感谢那。我的问题是是否曾经调用过 onLocationChanged 以及从何处调用它。在 android 文档developer.android.com/guide/topics/location/strategies.html 中,它使用了 LocationManager 和 LocationListener - 但这显然没有在您(或我的)代码中使用。我也不确定这是在做什么:LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);干杯。
    【解决方案2】:

    如果您的要求只是获取用户的当前位置,那么您不需要使用 MapActivity,您可以依赖 LocationServices 并要求 getLastLocation 。下面是为您服务的示例代码目的。

      // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    }
    

    由于您已经实现了 GoogleApiClient 的侦听器,因此您可以请求位置,如下代码所示:

         @Override
            public void onConnected(Bundle bundle) {
                Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                startLocationUpdates();
            }
    
            protected void startLocationUpdates() {
                Log.d(TAG, "startLocationUpdates--> Start Location Updates");
                LocationServices.FusedLocationApi.requestLocationUpdates(
                        mGoogleApiClient, mLocationRequest, this);
            }
    
            public void stopLocationUpdates() {
                Log.d(TAG,"stopLocationUpdates--> Stop location updates");
                LocationServices.FusedLocationApi.removeLocationUpdates(
                        mGoogleApiClient, this);
                stopService();
            }
    
        @Override
        public void onConnectionSuspended(int i) {
            Log.i(TAG, "Connection suspended");
            mGoogleApiClient.connect();
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " +
                    connectionResult.getErrorCode());
        }
    
        @Override
        public void onLocationChanged(Location location) {
            Log.d(TAG, "onLocationChanged--> Location is " + location.toString());
            mCurrentLocation = location;
        }
    

    此外,如果您想在定期间隔后跟踪位置,您可以从 OnCreate(您创建 GoogleApiClient 对象的位置)创建一个像这样的 locationRequest 对象:

    protected void createLocationRequest() {
        Log.d(TAG,"createLocationRequest--> Create Location Request");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10 * 1000); //UPDATE_INTERVAL_IN_MS
        mLocationRequest.setFastestInterval(5 * 1000); //FASTEST_UPDATE_INTERVAL_IN_MS
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    }
    

    这里是startLocation更新方法:

     protected void startLocationUpdates() {
        Log.d(TAG, "startLocationUpdates--> Start Location Updates");
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }
    

    我希望这能回答您的问题,如果它解决了您的问题,请将此标记为答案。

    【讨论】:

    • 谢谢。您能否解释一下 startLocationUpdates 方法实际上是如何渲染地图的?我假设 LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);将获得更新的位置,但如何将其放在地图上?
    • 嗨阿维纳什。感谢那。我的问题是是否曾经调用过 onLocationChanged 以及从何处调用它。在 android 文档developer.android.com/guide/topics/location/strategies.html 中,它使用了 LocationManager 和 LocationListener - 但这显然没有在您(或我的)代码中使用。我也不确定这是在做什么:LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);干杯。
    猜你喜欢
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多