我正在尝试在android中实现地理围栏,添加了地理围栏,但是以某种方式从未触发过地理围栏接收器。 我已经在清单中添加了文件。正确添加了初始触发器,但仍然不起作用。在日志中,它显示已添加地理围栏。位置更新工作正常。我正在使用Google Play服务版本15.0.1
public class HomeActivity extends AppCompatActivity {
public static boolean geofencesAlreadyRegistered = false;
private String receiver;
private String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
SimpleGeofenceStore.getInstance().addGeofence("Home",
new LatLng(28.6893456, 77.29197569999997));
SimpleGeofenceStore.getInstance().addGeofence("Office",
new LatLng(28.68825426975649, 77.29288238399204));
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
1);
}
startService(new Intent(this, LocationUpdateService.class));
}}
'
public class LocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, OnCompleteListener<Void> {
public static final int FASTEST_INTERVAL = 1000 * 2;
public static final int INTERVAL = 1000 * 2;
private PendingIntent mPendingIntent;
protected GoogleApiClient mGoogleApiClient;
private GeofencingClient client;
private LocationCallback locationCallback;
private FusedLocationProviderClient locationClient = MyApp.getLocationClient();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("manu", "Location update Service started");
mPendingIntent = requestPendingIntent();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return Service.START_STICKY;
}
Log.d("manu", "CP1");
buildGoogleApiClient();
mGoogleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create()
.setInterval(INTERVAL)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setFastestInterval(FASTEST_INTERVAL);
Log.d("manu", "CP2");
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (android.location.Location location : locationResult.getLocations()) {
if (location != null) {
if (!HomeActivity.geofencesAlreadyRegistered) {
registerGeofences();
}
}
}
}
};
Log.d("manu", "CP3");
client = LocationServices.getGeofencingClient(this);
locationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
return Service.START_STICKY;
}
protected void registerGeofences() {
Log.d("manu", "RG");
if (HomeActivity.geofencesAlreadyRegistered) {
return;
}
HashMap<String, SimpleGeofence> geofences = SimpleGeofenceStore.getInstance().getSimpleGeofences();
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_DWELL);
for (Map.Entry<String, SimpleGeofence> item : geofences.entrySet()) {
SimpleGeofence sg = item.getValue();
builder.addGeofence(sg.toGeofence());
}
GeofencingRequest geofencingRequest;
try {
geofencingRequest = builder.build();
} catch (Exception e) {
return;
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
client.addGeofences(geofencingRequest, mPendingIntent).addOnCompleteListener(this);
Log.d("manu", "AG");
HomeActivity.geofencesAlreadyRegistered = true;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onConnected(@Nullable Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onDestroy() {
super.onDestroy();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
locationClient.removeLocationUpdates(locationCallback);
}
private PendingIntent requestPendingIntent() {
if (null != mPendingIntent) {
return mPendingIntent;
} else {
Intent intent = new Intent(MyApp.getContext(), GeofenceReceiver.class);
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
public static String getErrorString(int errorCode) {
switch (errorCode) {
case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE:
return "Geofence not available";
case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES:
return "Too many geofences";
case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS:
return "Too many geofence pending intents";
default:
return "Unknown geofence error";
}
}
@Override
public void onComplete(@NonNull Task<Void> task) {
}}
'
public class SimpleGeofence {
private final String id;
private final double latitude;
private final double longitude;
private final float radius;
private long expirationDuration;
private int transitionType;
private int loiteringDelay = 60000;
public SimpleGeofence(String geofenceId, double latitude, double longitude,
float radius, long expiration, int transition) {
this.id = geofenceId;
this.latitude = latitude;
this.longitude = longitude;
this.radius = radius;
this.expirationDuration = expiration;
this.transitionType = transition;
}
public Geofence toGeofence() {
Geofence g = new Geofence.Builder().setRequestId(getId())
.setTransitionTypes(transitionType)
.setCircularRegion(getLatitude(), getLongitude(), getRadius())
.setExpirationDuration(expirationDuration)
.setLoiteringDelay(loiteringDelay).build();
return g;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public String getId() {
return id;
}
public float getRadius() {
return radius;
}}
'
public class SimpleGeofenceStore {
private static final long GEOFENCE_EXPIRATION_IN_HOURS = 12;
private static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS = GEOFENCE_EXPIRATION_IN_HOURS
* DateUtils.HOUR_IN_MILLIS;
private HashMap<String, SimpleGeofence> geofences = new HashMap<>();
private static SimpleGeofenceStore instance = new SimpleGeofenceStore();
public static SimpleGeofenceStore getInstance() {
return instance;
}
public void addGeofence(String key, LatLng latLng) {
geofences.put(key, new SimpleGeofence(key, latLng.latitude, latLng.longitude,
100, GEOFENCE_EXPIRATION_IN_MILLISECONDS,
Geofence.GEOFENCE_TRANSITION_ENTER
| Geofence.GEOFENCE_TRANSITION_DWELL
| Geofence.GEOFENCE_TRANSITION_EXIT));
}
public HashMap<String, SimpleGeofence> getSimpleGeofences() {
return this.geofences;
}}
'
public class GeofenceReceiver extends IntentService {
public GeofenceReceiver() {
super("GeofenceReceiver");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("manu", "GeofenceReceiver");
GeofencingEvent geoEvent = GeofencingEvent.fromIntent(intent);
if (geoEvent.hasError()) {
Log.d("manu", "Error GeofenceReceiver.onHandleIntent");
} else {
Log.d("manu", "GeofenceReceiver : Transition -> "
+ geoEvent.getGeofenceTransition());
int transitionType = geoEvent.getGeofenceTransition();
if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER
|| transitionType == Geofence.GEOFENCE_TRANSITION_DWELL
|| transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
List<Geofence> triggerList = geoEvent.getTriggeringGeofences();
for (Geofence geofence : triggerList) {
SimpleGeofence sg = SimpleGeofenceStore.getInstance()
.getSimpleGeofences().get(geofence.getRequestId());
String transitionName = "";
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_DWELL:
transitionName = "dwell";
Log.d("manu", "dwell");
break;
case Geofence.GEOFENCE_TRANSITION_ENTER:
transitionName = "enter";
Log.d("manu", "enter");
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
transitionName = "exit";
Log.d("manu", "exit");
break;
}
}
}
}
}}
任何帮助将不胜感激。