Android 使用google play服务获取最后一个已知位置
我一直在浏览android开发者文档,试图找出如何获取当前位置,特别是 当我在android中创建一个新项目并选择Map模板时,onCreate方法中有代码,然后还有onMapReady方法 首先,确认下面的代码是否将地图显示在屏幕上?如果是这样的话,onMapReady仅仅是一种允许操纵地图的方法吗Android 使用google play服务获取最后一个已知位置,android,google-maps,google-play-services,Android,Google Maps,Google Play Services,我一直在浏览android开发者文档,试图找出如何获取当前位置,特别是 当我在android中创建一个新项目并选择Map模板时,onCreate方法中有代码,然后还有onMapReady方法 首先,确认下面的代码是否将地图显示在屏幕上?如果是这样的话,onMapReady仅仅是一种允许操纵地图的方法吗 SupportMapFragment mapFragment = (SupportMapFragment) etSupportFragmentManager() .
SupportMapFragment mapFragment = (SupportMapFragment) etSupportFragmentManager()
.findFragmentById(R.id.map); mapFragment.getMapAsync(this);
在文档re:获取当前位置中,有关于GoogleAppClient的信息re:building,例如
// 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函数仍然是必需的吗?哪里是创建GoogleAppClient实例的最佳位置
在“后续文档”页面上,还提供了有关连接到后获取当前位置设置的信息
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
但我只是不确定应该在哪里定义
最后,在Android Studio中的地图模板中,默认类定义为:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
但在谷歌文档中,它的定义是:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
公共类MainActivity扩展了ActionBarActivity实现
ConnectionCallbacks,OnConnectionFailedListener
类扩展哪个活动重要吗
谢谢。如果您的要求只是获取用户的当前位置,那么您不需要使用MapActivity,您可以依赖LocationServices并请求获取getLastLocation。下面是为您服务的示例代码
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
由于您已经实现了GoogleAppClient的侦听器,因此您可以询问位置,如下代码所示:
@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创建一个locationRequest对象(您在其中创建了GoogleAppClient对象):
以下是更新方法:
protected void startLocationUpdates() {
Log.d(TAG, "startLocationUpdates--> Start Location Updates");
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
我希望这能回答您的问题,如果它能解决您的问题,请将此标记为答案。我使用了预定义的地图活动。您可以通过它获取您最近已知和当前的位置
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清单中的网络状态权限和位置权限谢谢。你能解释一下startLocationUpdates方法是如何实际渲染地图的吗?我假设LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleapClient,mLocationRequest,this);将获得更新的位置,但如何将其放在地图上?嗨,阿维纳什。谢谢你。我的问题是onLocationChanged是否曾经被调用以及从何处被调用。在android文档中,它通过使用LocationManager和LocationListener来实现——但这显然没有在您(或我的)代码中使用。我也不确定这到底在做什么:LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleapClient,mLocationRequest,this);干杯,嗨。谢谢你。我的问题是onLocationChanged是否曾经被调用以及从何处被调用。在安卓文档中有一个章节:Hi Avinash。谢谢你。我的问题是onLocationChanged是否曾经被调用以及从何处被调用。在android文档中,它通过使用LocationManager和LocationListener来实现——但这显然没有在您(或我的)代码中使用。我也不确定这到底在做什么:LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleapClient,mLocationRequest,this);干杯