我建立了一个系统,该系统基于动态跟踪用户在位置周围移动时的当前位置。该系统可以正常运行,并不断地将用户的当前位置更新到Firebase数据库中。但是,当应用程序最小化并再次恢复到相同的活动(当然是地图)时,它仅显示用户的位置,而不会在基础数据库中更新用户。现在我知道该活动再次从OnResume()方法开始,我已经尝试了几件事,但是每次我尝试做某事时,大多数时候都说googleapiClient未连接,然后立即崩溃。在不操纵onResume的情况下,该应用程序可以正常运行,但是当最小化该应用程序并从onResume方法重新打开该应用程序时,该应用程序不会将用户位置更新为火力源。我应该对onResume()方法执行什么操作,它开始将用户动态位置发送到Firebase中??? 我在下面发布了我的代码。任何帮助将不胜感激,谢谢。
public class RequestLocationMap extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks
, GoogleApiClient.OnConnectionFailedListener
, LocationListener {
private static final String TAG = "RequestLocationMap";
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
public static final int Request_User_Location_Code = 99;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request_location_map);
Log.d(TAG, "onCreate: called");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkUserLocationPermission();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady: called");
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public boolean checkUserLocationPermission() {
Log.d(TAG, "checkUserLocationPermission: called");
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
return false;
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: here");
switch (requestCode) {
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (googleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Application requires location permission", Toast.LENGTH_SHORT).show();
}
}
}
protected synchronized void buildGoogleApiClient() {
Log.d(TAG, "buildGoogleApiClient: called");
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.d(TAG, "onConnected: called");
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(
RequestLocationMap.this, 1000);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged: called");
lastLocation = location;
if (currentUserLocationMarker != null) {
currentUserLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
currentUserLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14f));
DatabaseReference myTracking = FirebaseDatabase.getInstance().getReference().child("MyTracking");
GeoFire geoFire = new GeoFire(myTracking);
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(location
.getLatitude(), location.getLongitude()));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult: called");
switch (requestCode) {
case 1000:
switch (resultCode) {
case Activity.RESULT_OK: {
break;
}
case Activity.RESULT_CANCELED: {
// The user was asked to change settings, but chose not to
Toast.makeText(RequestLocationMap.this, "App required location permission", Toast.LENGTH_LONG).show();
finish();
break;
}
default: {
break;
}
}
break;
}
}
@Override
protected void onStop() {
Log.d(TAG, "onStop: called");
super.onStop();
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
DatabaseReference myTracking = FirebaseDatabase.getInstance().getReference().child("MyTracking");
GeoFire geoFire = new GeoFire(myTracking);
geoFire.removeLocation(FirebaseAuth.getInstance().getCurrentUser().getUid());
}
@Override
protected void onResume() {
Log.d(TAG, "onResume: called");
super.onResume();
}
}
答案 0 :(得分:0)
应用程序的问题是,在生命周期方法 onStop()中,您请求停止从FusedLocation API接收位置更新,而在 onResume()的倒数方法中
强>。您从不要求位置更新。此外,即使您确实在onResume()内注册了位置更新,代码的结构方式仍然会给GoogleClient API带来麻烦,因为它可能不会(很可能不是)通过 onResume()被执行的时间。我建议您从onResume而不是onCreate()调用方法 buildGoogleApiClient()(仍然执行权限检查)。这样,在恢复活动的同时始终会连接GoogleClient API。请记住在onPause()内的GoogleClient API上调用“断开连接”。在位置侦听器回调方法内部,您应该对GoogleMap引用执行null检查,以防止出现任何NP异常。在 onLocationChanged(Location)的前几次执行期间,GoogleMaps可能为null,因为与从FusedLocation API接收第一次位置更新相比,初始化MapFragment可能花费更多时间。我已经看到位置API在请求更新后数毫秒内就会提供位置更新。
此外,作为一种好的做法,您应该将生命周期方法与它们的倒数配对:
当您希望发生事前发生的关系时,例如混合和匹配的生命周期回调可能会使您陷入困境,例如在应用程序暂停和恢复时注册和注销位置更新。