我想每隔500m更改就监听用户的位置。因此,我已经使用了前台服务(由于Oreo的限制)和。从列表上滑动应用程序(杀死)时,我已经开始地理围栏。我看到当前景中的应用程序发生位置更改会触发地理围栏,但是当背景中的应用程序未触发时我正在使用前景服务。代码如下。
private static final int DRIVERSTATUSSERVICE_ID = 201;
private FirebaseDatabase dbInstance;
private DatabaseReference ref;
private ValueEventListener statuEventListener;
private String userName;
private DriverConstants.DriverStatus status;
private static final String CHANNEL = "DRIVERSTATUSSERVICE__CHANNEL";
private static final String GEOFENCE_REQUESTID = "GEOFENCING_REQUESTID.";
private boolean serviceStopped = false;
private FusedLocationProviderClient fusedLocationProviderClient;
private GeofencingClient mGeofencingClient;
private PendingIntent mGeofencePendingIntent;
public static final float GEOFENCING_RADIUS = 500;
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
startNotificationAndForeGround(!MyApplication.driverActivityStarted);
if(userName == null) {
if(UserCognito.getInstance(getApplicationContext()).getUserName() == null) {
getUserSessionInBackground(DriverStatusService.this, new CallBackService() {
@Override
public void onSuccess() {
userName = UserCognito.getInstance(getApplicationContext()).getUserName();
workStartLogics(intent);
}
@Override
public void onFail() {
}
});
}else {
userName = UserCognito.getInstance(getApplicationContext()).getUserName();
workStartLogics(intent);
}
}else {
workStartLogics(intent);
}
return START_REDELIVER_INTENT;
}
@Override
public void onCreate() {
super.onCreate();
initChannels(getApplicationContext());
}
@Override
public void onDestroy() {
super.onDestroy();
if (ref != null) {
ref.removeEventListener(statuEventListener);
ref = null;
}
if(mGeofencingClient != null && mGeofencePendingIntent != null) {
mGeofencingClient.removeGeofences(mGeofencePendingIntent);
}
if (!serviceStopped) { //onTaskRemoved dan sonra burası çalışabilir (bazı caselerde) bazen sadece burası çalışır
stopForeGroundAndSelf();
}
}
private void workStartLogics(Intent intent) {
boolean isFromGecofencing = intent.getBooleanExtra("GEOFENCING",false);
if(isFromGecofencing && !MyApplication.driverActivityStarted) {
getLastLocationAndStartGeofencing();
}
listenDriverStatus(intent);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
MyApplication.driverActivityStarted = false;
if (status == DriverConstants.DriverStatus.WAITING) {
startNotificationAndForeGround(true);
getLastLocationAndStartGeofencing();
} else {
stopForeGroundAndSelf();
}
}
private void getLastLocationAndStartGeofencing() {
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
getFusedLocationProviderClient().getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
sendDriverLocation(task.getResult());
startNewGeofencing(task.getResult());
}
});
}
private void startNewGeofencing(Location lastLocation) {
if(lastLocation == null) {
return;
}
mGeofencingClient = LocationServices.getGeofencingClient(this);
Geofence g = new Geofence.Builder()
.setRequestId(GEOFENCE_REQUESTID)
.setCircularRegion(
lastLocation.getLatitude(),
lastLocation.getLongitude(),
GEOFENCING_RADIUS)
.setLoiteringDelay(0)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT).build();
if (ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mGeofencingClient.addGeofences(getGeofencingRequest(g), getGeofencePendingIntent())
.addOnCompleteListener(this).addOnFailureListener(this);
}
@Override
public void onComplete(@NonNull Task task) {
}
@Override
public void onFailure(@NonNull Exception e) {
}
private GeofencingRequest getGeofencingRequest(Geofence g) {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_EXIT);
builder.addGeofence(g);
return builder.build();
}
private PendingIntent getGeofencePendingIntent() {
if (mGeofencePendingIntent != null) {
mGeofencingClient.removeGeofences(mGeofencePendingIntent);
return mGeofencePendingIntent;
}
Intent intent = new Intent(DriverStatusService.this, GeofenceBroadcastReceiver.class);
mGeofencePendingIntent = PendingIntent.getBroadcast(DriverStatusService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return mGeofencePendingIntent;
}
private void startNotificationAndForeGround(boolean appOnBackground) {
Intent notificationIntent = appOnBackground ? ActivityUtil.getSplashActivityIntent(DriverStatusService.this) : ActivityUtil.getDriverActivityIntent(DriverStatusService.this);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder notificationCompat =
new NotificationCompat.Builder(this.getApplicationContext(), CHANNEL)
.setContentText("Çevredeki müşterilerle eşleşmeye hazırsın")
.setContentIntent(pendingIntent)
.setLocalOnly(true);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationCompat.setSmallIcon(R.drawable.ic_white_icon);
notificationCompat.setColor(getResources().getColor(R.color.appColor));
} else {
notificationCompat.setSmallIcon(R.mipmap.ic_launcher);
}
Notification notification = notificationCompat.build();
startForeground(DRIVERSTATUSSERVICE_ID, notification);
}
public void initChannels(Context context) {
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(CHANNEL, "Foreground channel",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Channel for foreground service");
notificationManager.createNotificationChannel(channel);
}
private void listenDriverStatus(Intent intent) {
if (intent != null) {
dbInstance = FirebaseDatabase.getInstance();
if (ref == null) {
ref = dbInstance.getReference(FIREBASE_TAXI_URI).child(userName).child("st");
statuEventListener = new ValueEventListener() { //daima dinlenecek
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Long st = dataSnapshot.getValue(Long.class);
status = DriverConstants.DriverStatus.getStatusByNumber(st.intValue());
if(status == null) {
return;
}
switch (status) {
case WAITING_TO_ACCEPT: //2 eşleştirme isteği gönderildi
startActivity(ActivityUtil.getDriverActivityIntent(DriverStatusService.this));
break;
default:
break;
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
ref.addValueEventListener(statuEventListener);
}
}
}
private void sendDriverLocation(Location lastLocatio) {
if(lastLocatio == null) {
return;
}
callAwsFunction(new SendLocationRequestDTO(userName,lastLocatio.getLatitude(),lastLocatio.getLongitude(),"T",null), com.example.ahmetvefa53.heremapapp.awsServices.DriverService.class, BaseAwsResponseDTO.class, new ServiceCall<SendLocationRequestDTO, BaseAwsResponseDTO, com.example.ahmetvefa53.heremapapp.awsServices.DriverService>() {
@Override
public BaseAwsResponseDTO callServiceMethod(com.example.ahmetvefa53.heremapapp.awsServices.DriverService myInterface, SendLocationRequestDTO param) {
return myInterface.sendLocation(param);
}
}, new OnSuccess<BaseAwsResponseDTO>() {
@Override
public void OnSuccess(BaseAwsResponseDTO response) {
}
}, new OnFailure() {
@Override
public void onFailure(BaseAwsErrorDTO errorDTO) {
}
});
}
private void stopForeGroundAndSelf() {
serviceStopped = true;
stopForeground(true);
stopSelf();
}
private FusedLocationProviderClient getFusedLocationProviderClient() {
if (fusedLocationProviderClient == null) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(DriverStatusService.this);
}
return fusedLocationProviderClient;
}
GeofenceReceiver是:
@Override
public void onReceive(Context context, Intent intent) {
handleGeofencing(context,intent);
}
private void handleGeofencing(Context context,Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
int errorCode = geofencingEvent.getErrorCode();
Log.e("GEOFENCE_ERROR", GeofenceStatusCodes.getStatusCodeString(errorCode));
}
switch (geofencingEvent.getGeofenceTransition()) {
case Geofence.GEOFENCE_TRANSITION_EXIT:
Intent i = new Intent(context, DriverStatusService.class);
i.putExtra("GEOFENCING",true);
ContextCompat.startForegroundService(context.getApplicationContext(),i);
break;
default:
break;
}
}
注意:当应用程序在后台运行并且我尝试打开google maps应用程序时,它被触发
谁可以帮助我解决这个问题?这是什么问题?
note2:我正在使用仿真器。