【问题标题】:Start Gps Tracking again when the android application On-Resumes()当android应用程序On-Resumes()时再次启动Gps Tracking
【发布时间】:2019-01-22 14:38:25
【问题描述】:

我已经构建了一个系统,该系统基于在用户四处移动时动态跟踪用户当前位置。该系统运行良好,并一次又一次地将用户的当前位置更新到 firebase 数据库中。但是,当应用程序被最小化并再次恢复到相同的活动(当然是地图)时,它只显示用户的位置,但不会在 fire-base 数据库中更新它。现在我知道活动再次从 OnResume() 方法开始,我尝试了几件事,但每次我尝试做某事时,它大多数时候都说 googleapiClient 未连接,然后立即崩溃。在不操作 onResume 的情况下,应用程序可以完美运行,但是当应用程序被最小化并从 onResume 方法重新打开时,它不会将用户位置更新到火基中。我应该对它开始将用户动态位置发送到火力基地的 onResume() 方法做什么??? 下面我发布了我的代码。任何帮助将不胜感激谢谢。

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(); 



}
  }

【问题讨论】:

  • 当您的活动停止时,您请求停止从 FusedLocationAPI 接收位置更新。在 onResume(...) 中,您永远不会请求再次开始接收位置更新
  • @WadeWilson 我试过了,它仍然抛出一个错误,说 googleApIClient 尚未连接
  • 您只需要在您的 googleAPIClient 实例上调用 connect 即可。我建议从 onResume() 调用“buildGoogleApiClient()”,这样您就可以在活动恢复时随时请求位置更新。然后检查您的 GoogleMap 引用是否在“onLocationChanged”内不为空。如果 MapFragment 的设置时间比 FusedLocationAPI 长,则可能会发生这种情况。
  • @WadeWilson 绝对有效。我只需将 buildGoogleApiClient() 从 onMapReady 移动到 Onresume 并开始检测用户位置。谢谢你
  • 没问题。我会把答案写出来供其他人使用。

标签: java android firebase google-maps gps


【解决方案1】:

您的应用程序的问题在于,在生命周期方法 onStop() 中,您请求停止从 FusedLocation API 接收位置更新,但在 onResume() 的互惠方法中强>。您从不要求位置更新。此外,即使您确实在 onResume() 中注册了位置更新,您的代码的结构方式也会遇到 GoogleClient API 的问题,因为它可能没有(很可能没有)通过onResume() 被执行的时间。

我建议您从 onResume 而不是 onCreate() 调用方法 buildGoogleApiClient()(仍然执行权限检查)。这样,当活动恢复时,GoogleClient API 始终保持连接。请记住在 onPause() 内部的 GoogleClient API 上调用“断开连接”。在位置侦听器回调方法中,您应该对 GoogleMap 引用执行空检查以防止任何 NP 异常。在 onLocationChanged(Location) 的前几次执行期间,GoogleMaps 可能为空,因为初始化 MapFragment 所需的时间可能比从 FusedLocation API 接收第一个位置更新所需的时间更长。我已经看到位置 API 在我请求更新后的几毫秒内提供了位置更新。

另外,你应该将生命周期方法与其倒数配对:

  1. onCreate() -> onDestroy()
  2. onStart() -> onStop()
  3. onResume -> onPause()

当您期望发生之前的关系时,混合和匹配生命周期回调可能会让您陷入困境,例如在应用暂停和恢复时注册和取消注册位置更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    相关资源
    最近更新 更多