我使用gms.location.LocationListener(Google Play服务)来获取用户的位置。它工作正常但我想检测用户何时禁用或启用他/她的GPS。 如图所示。
当我打开/关闭位置时,不会调用任何方法。 当我切换应用程序并返回我的应用程序时,会调用此方法:
但是,每当用户打开/关闭位置时,我都需要调用该事件,而我列出的那些事件不会被调用。
注意:使用Android API,我能够通过onProviderEnabled和onProviderDisabled获取这些事件,我的问题是在使用GoogleApiClient后,这些事件不再被调用。见图2和3。 在那之后onProviderEnabled和onProviderDisabled没有得到很好的调用,这是我想要解决的另一个问题。
我的代码:
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 !!!!!!!!!!!!!!!!!!!");
}
}
}
}
答案 0 :(得分:6)
您可以通过设置广播接收器来实现此功能,只要设备的GPS开启/关闭就会被触发
<强>步骤:强>
<强> 1。首先创建一个扩展BroadcastReceiver
的类GPSpublic 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))
{
}
else
{
Toast.makeText(context, "Please switch on the GPS", Toast.LENGTH_LONG).show();
}
}
}
<强> 2。然后在AndroidManifest.xml文件中提及此类
<receiver android:name="com.yourpackagename.example.GPSCheck" >
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
第3。不要忘记添加此权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
答案 1 :(得分:1)
我正在使用此类来收听GPS的变化。
public class GpsReceiver extends BroadcastReceiver {
public interface LocationCallBack {
void turnedOn();
void turnedOff();
}
private final LocationCallBack locationCallBack;
public GpsReceiver(LocationCallBack iLocationCallBack){
this.locationCallBack = iLocationCallBack;
}
@Override
public void onReceive(Context context, Intent intent) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
locationCallBack.turnedOn();
else
locationCallBack.turnedOff();
}
}
并在我的活动的onCreate上注册它。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(new GpsReceiver(new GpsReceiver.LocationCallBack() {
@Override
public void turnedOn() {
Log.e("GpsReceiver","is turned on");
}
@Override
public void turnedOff() {
Log.e("GpsReceiver","is turned off");
}
}), new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
}