我使用gms.location.LocationListener(Google Play服务)来获取用户的位置。它运行良好,但我想检测用户何时禁用或启用他/她的GPS。就像这张图片中所示。
当我打开/关闭位置时,没有任何方法被调用。
当我切换应用程序并返回到我的应用程序时,将调用这些方法:
- onStart - onResume - onConnected
但是我需要在用户打开/关闭位置时调用该事件,我列出的那些事件不会被调用。
注意:使用Android API,我能够通过onProviderEnabled和onProviderDisabled获取这些事件,我的问题在于在使用GoogleApiClient后这些事件不再被调用。参见图片2和3。
之后,onProviderEnabled和onProviderDisabled不再被调用,这是另一个问题,我希望解决这两个问题。
- onStart - onResume - onConnected
但是我需要在用户打开/关闭位置时调用该事件,我列出的那些事件不会被调用。
注意:使用Android API,我能够通过onProviderEnabled和onProviderDisabled获取这些事件,我的问题在于在使用GoogleApiClient后这些事件不再被调用。参见图片2和3。
![Use location Window](https://istack.dev59.com/5u8iH.webp)
![Use location window](https://istack.dev59.com/tcLOa.webp)
- Android Studio 1.5.1
- 在 Galaxy Note 3 (SM-N900W8 Android 5.0, API 21) 中进行测试
我的代码:
package facilito.codigo.app.dflores.com.myapplicationcf;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.location.Location;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationListener;//android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
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.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import org.json.JSONObject;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import Beans.Usuario;
import Beans.Utiles;
public class Mapa extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private GoogleMap mMap;
private double lat = 0.0;
private double lon = 0.0;
PolygonOptions comunidad = new PolygonOptions();
protected GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
Location mLastLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
createLocationRequest();
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, 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:
// All location settings are satisfied. The client can
// initialize location requests here.
Log.d("BUHOO", "case success :::::::::::>>>>>>>>>>>");
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
Log.d("BUHOO", "case RESOLUTION_REQUIRED :::::::::::>>>>>>>>>>>");
status.startResolutionForResult(Mapa.this, 1000);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.d("BUHOO", "case SETTINGS_CHANGE_UNAVAILABLE :::::::::::>>>>>>>>>>>");
// Location settings are not satisfied. However, we have no way
// to fix the settings so we won't show the dialog.
break;
}
}
});
SharedPreferences pref = getSharedPreferences("BUHOO_APP", MODE_PRIVATE);
Usuario usuario = new Usuario(pref.getInt("ID_USUARIO", 0), pref.getString("NOMBRE_USUARIO", null));
int idComu = pref.getInt("ID_COMUNIDAD", 0);
String server = getResources().getString(R.string.ip_server);
String servicio = "http://"+server+"/buhoo/intranet/mi_comunidad/getComunidadByPersona_Service?id_persona="+usuario.getIdUsuario()+"&id_comunidad="+idComu;
Log.d("BUHOO", "servicioservicioservicio:::::: "+servicio);
new llamarServicio().execute(servicio);
// 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);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@Override
public void onConnected(Bundle bundle) {
Log.d("BUHOO", ":::: onConnected ::::");
try {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
} catch(SecurityException e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
Log.d("BUHOO", " ERROR onLocationChanged "+errors.toString());
}
//if (mRequestingLocationUpdates) {
startLocationUpdates();
//}
}
@Override
public void onConnectionSuspended(int i) {
Log.d("BUHOO", ":::: onConnectionSuspended ::::");
}
protected void onStart() {
Log.d("BUHOO", ":::: onStart ::::");
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
Log.d("BUHOO", ":::: onStop ::::");
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
protected void onPause() {
Log.d("BUHOO", ":::: onPause ::::");
super.onPause();
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
@Override
public void onResume() {
Log.d("BUHOO", ":::: onResume ::::");
super.onResume();
if (mGoogleApiClient.isConnected() /*&& !mRequestingLocationUpdates*/) {
startLocationUpdates();
}
}
protected void startLocationUpdates() {
try {
Log.d("BUHOO", ":::: startLocationUpdates ::::");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} catch(SecurityException e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
Log.d("BUHOO", " ERROR onLocationChanged "+errors.toString());
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("BUHOO", ":::: onConnectionFailed ::::");
}
@Override
public void onLocationChanged(Location location) {
Log.d("BUHOO", "onLocationChanged:::::: "+location.getLatitude()+" longitud: "+location.getLongitude());
lat = location.getLatitude();
lon = location.getLongitude();
onMapReady(mMap);
}
/*
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Log.d("BUHOO", ":::: onProviderEnabled ::::");
}
@Override
public void onProviderDisabled(String provider) {
Log.d("BUHOO", ":::: onProviderDisabled ::::");
}*/
private class llamarServicio extends AsyncTask<String, Void, String> {
Utiles utiles = new Utiles();
protected String doInBackground(String... urls) {
return utiles.readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
Log.d("BUHOO", "result:::::: "+result);
JSONObject mainResponseObject = new JSONObject(result);
try {
String error = mainResponseObject.getString("error");
if("0".equals(error)) {
JSONObject polyObj = new JSONObject(mainResponseObject.getString("poligono"));
String puntos = polyObj.getString("puntos");
List<String> puntosList = Arrays.asList(puntos.split(","));
for(Iterator it = puntosList.iterator(); it.hasNext(); ) {
String str = (String) it.next();
String[] latlon = str.split(" ");
double lati = Double.parseDouble(latlon[0].replaceAll("\"", ""));
double longi = Double.parseDouble(latlon[1].replaceAll("\"", ""));
comunidad.add(new LatLng(lati, longi));
//Log.d("BUHOO", "lati:::::: "+lati+" ... "+longi);
}
Log.d("BUHOO"," onPostExecute cantidad latlongs: "+comunidad.getPoints().size());
onMapReady(mMap);
} else {
Log.d("CREATION", " ---- error inesperdo: " );
}
} catch (Exception e) {
e.printStackTrace();
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
Log.d("CREATION", "tratando el JSON: "+errors.toString());
}
} catch (Exception e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
Log.d("CREATION", "errorrrr onPostExecute: "+errors.toString());
}
}
}
/**
* 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;
// Add a marker in Sydney and move the camera
if(lat != 0.0 && lon != 0.0) {
LatLng myPos = new LatLng(lat, lon);
mMap.clear();
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.addMarker(new MarkerOptions().position(myPos).title("MI POSICION ACTUAL"));
float zoomLevel = 17; //This goes up to 21
//Polygon polygon = mMap.addPolygon(comunidad);
Log.d("BUHOO"," PINTANDO MAPA cantidad latlongs: "+comunidad.getPoints().size());
if(comunidad.getPoints().size() > 0) {
mMap.addPolygon(comunidad/*.fillColor(Color.BLUE)*/);
}
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myPos, zoomLevel));
} else {
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
Log.d("BUHOO", "PINTO SYDNEY");
}
}
public static class GPSCheck extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.d("BUHOO", " :D IS ON!!!!!!!!!!!!!!!!!!!");
} else {
Log.d("BUHOO", " :( GPS TURNED OFF !!!!!!!!!!!!!!!!!!!");
}
}
}
}