我希望每次用户移动时检索设备位置,但onLocationChanged回调不起作用。有人可以帮帮我吗?这是我管理谷歌地图的活动代码。请注意,我使用了Google库com.google.android.gms.location.LocationListener中的onLocationChanged
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.annotation.TargetApi;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.LocationCallback;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.proper_international.properinternationnal.R;
import com.proper_international.properinternationnal.activity.customer.BookingProviderActivity;
import com.proper_international.properinternationnal.activity.menus.HamburgerMenuProviderActivity;
import com.proper_international.properinternationnal.entities.Nettoyeur;
import com.proper_international.properinternationnal.miscs.UserEnum;
import com.proper_international.properinternationnal.miscs.Utilities;
import com.proper_international.properinternationnal.services.ActionAPIService;
import com.proper_international.properinternationnal.services.FCMNotificationService;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class ProviderToCustomerMapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private Button btnAccept, btnDecline;
FusedLocationProviderClient mFusedLocationClient;
SharedPreferences sharedpreferences;
String latLong, idReserve, from, login;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
LocationRequest mLocationRequest;
Marker mCurrLocationMarker;
private LatLng equipierPosition;
private LocationManager locationManager;
static int MY_REQUEST_CODE = 225;
private String provider_info;
boolean isGPSEnabled, isNetworkEnabled;
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_provider_to_customer_maps);
btnAccept = (Button) findViewById(R.id.btnAccept);
btnDecline = (Button) findViewById(R.id.btnDecline);
sharedpreferences = getSharedPreferences(Utilities.MY_PREFERENCE, Context.MODE_PRIVATE);
if (getIntent() != null) {
latLong = getIntent().getStringExtra("latLng");
idReserve = getIntent().getStringExtra("idReserve");
from = getIntent().getStringExtra("from");
login = getIntent().getStringExtra("login");
}
// 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);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
runOnClick();
if (!sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Provider.toString())) {
btnDecline.setVisibility(View.INVISIBLE);
btnAccept.setText("Consulter son profile.");
}
btnDecline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String result = new declinerReservation().execute().get();
if (result.equals("true"))
Toast.makeText(ProviderToCustomerMapsActivity.this, "Merci!", Toast.LENGTH_LONG).show();
finish();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
btnAccept.setOnClickListener(new View.OnClickListener() {
@SuppressLint("MissingPermission")
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onClick(View v) {
if (!sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Customer.toString())) {
try {
String result = new assignerReservation().execute().get();
if (result.equals("true")) {
String latLng = mLastLocation.getLatitude() + "," + mLastLocation.getLongitude();
String title = "Reservation A.";
String body = "Un Eest prêt à vous R.";
//Notification PUSH
boolean notSend = false;
while (notSend == false) {
notSend = new FCMNotificationService().execute(from, title, body, latLng, idReserve, sharedpreferences.getString(Utilities.EXTRA_LOGIN, "")).get();
}
startActivity(new Intent(ProviderToCustomerMapsActivity.this, HamburgerMenuProviderActivity.class));
finish();
} else {
Toast.makeText(ProviderToCustomerMapsActivity.this, "Dommage! Un autre Ea décroché cette O.", Toast.LENGTH_LONG).show();
finish();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
Intent intent = new Intent(ProviderToCustomerMapsActivity.this, BookingProviderActivity.class);
String[] chaine = idReserve.split(",");
intent.putExtra("idReserver", chaine[0]);
intent.putExtra("login", chaine[1]);
startActivity(intent);
}
}
});
}
@TargetApi(Build.VERSION_CODES.M)
public void runOnClick() {
// mGoogleApiClient = this;
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(ProviderToCustomerMapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(ProviderToCustomerMapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_REQUEST_CODE);
}
}
if (ActivityCompat.checkSelfPermission(ProviderToCustomerMapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(ProviderToCustomerMapsActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
}
}
mFusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Last known location. In some rare situations, it can be null.
if (location != null) {
// Logique pour gérer l'objet d'emplacement
mLastLocation = location;
}
}
});
mFusedLocationClient.getLastLocation().addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
Log.e("getLastLocation", "onFailure: "+ex.getMessage());
}
}
);
}
private boolean isGooglePlayServicesAvailable() {
int status = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GoogleApiAvailability.getInstance().getErrorDialog(this, status, 0).show();
return false;
}
}
/**
* 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.
*/
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_REQUEST_CODE);
}
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
}
}
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
if (sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Customer.toString())) {
btnAccept.setText("Ma liste de R");
btnAccept.setVisibility(View.INVISIBLE);
//String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
String userId = login;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("EDisponible");
GeoFire geoFire = new GeoFire(ref);
geoFire.setLocation(userId.replaceAll(".", "_"), new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
String[] ll = latLong.split(",");
double latitude = Double.parseDouble(ll[0]);
double longitude = Double.parseDouble(ll[1]);
equipierPosition = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position de l'e."));
geoFire.getLocation(userId.replaceAll(".", "_"), new LocationCallback() {
@Override
public void onLocationResult(String key, GeoLocation location) {
if (location != null) {
System.out.println(String.format("L'emplacement de la clé %s est [%f,%f]", key, location.latitude, location.longitude));
equipierPosition = new LatLng(location.latitude, location.longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position de l'équipier."));
} else {
Log.d("Pas d'emplacement", String.format("Il n'y a pas d'emplacement pour la clé %s dans GeoFire", key));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Erreur produite", "Une erreur s'est produite lors de l'obtention de l'emplacement GeoFire: " + databaseError);
}
});
} else {
String userIds = login;
DatabaseReference refs = FirebaseDatabase.getInstance().getReference("ClientDisponible");
String[] ll = latLong.split(",");
double latitude = Double.parseDouble(ll[0]);
double longitude = Double.parseDouble(ll[1]);
GeoFire geoFire = new GeoFire(refs);
geoFire.setLocation(userIds.replaceAll(".", "_"), new GeoLocation(latitude, longitude));
equipierPosition = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position 0."));
geoFire.getLocation(userIds.replaceAll(".", "_"), new LocationCallback() {
@Override
public void onLocationResult(String key, GeoLocation location) {
if (location != null) {
System.out.println(String.format("L'emplacement de la clé %s est [%f,%f]", key, location.latitude, location.longitude));
equipierPosition = new LatLng(location.latitude, location.longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position 1."));
} else {
Log.d("Pas d'emplacement", String.format("Il n'y a pas d'emplacement pour la clé %s dans GeoFire:" + key));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Erreur obtention", databaseError.getMessage());
}
});
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Now user should be able to use camera
} else {
// Your app will not have this permission. Turn off all functions
// that require this permission or it will force close like your
// original question
}
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
@Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
// LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
com.google.android.gms.location.LocationCallback mLocationCallback = new com.google.android.gms.location.LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
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("Position actuelle");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
};
};
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onResume() {
super.onResume();
runOnClick();
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
String userId = login;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("EDisponible");
GeoFire geoFire = new GeoFire(ref);
geoFire.setLocation(userId.replaceAll(".","_"), new GeoLocation(location.getLatitude(), location.getLongitude()));
}
@Override
protected void onStop() {
super.onStop();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
String userId = login.replaceAll(".","_");
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("EDisponible");
if (!sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Customer.toString()))
ref = FirebaseDatabase.getInstance().getReference("ClientDisponible");
GeoFire geoFire = new GeoFire(ref);
geoFire.removeLocation(userId);
}
}
}
答案 0 :(得分:0)
我能够通过在onConnected方法中添加以下代码来解决我的问题:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
我没有使用LocationServices,因为不推荐使用FusedLocationApi。