我正在创建使用TimeFences和LocationFence组合的应用程序(Foot of Fence在Google的Awareness API下可用。但是每次创建Fence并进行注册时,它始终处于FALSE状态,甚至不在时间窗内由TimeFence定义。 就像我在星期一,星期二和星期五为每天创建3个TimeFences一样,我有LocationFence,现在我想获取结果,例如用户是否位于TimeFence的指定时间的3天中的任何一天,它应该返回TRUE,但是即使用户不在时间跨度中也始终为false 我在这里附加了Helper类和Triggered Service类, 感谢任何帮助
//Class for registering to the Fence
public class AutoAttendanceHelper {
public static final String KEY_PRE_SUBJECT_FENCE = "KEY_OF_SUBJECT_FENCE";
public static final double RADIUS_OF_FENCE = 100.0;
private PendingIntent mPendingIntent;
private final Context context;
private final long dwellTime = TimeUnit.MINUTES.toMillis(2);
private AwarenessFence mLocationFence;
public AutoAttendanceHelper(Context context) {
this.context = context;
}
private PendingIntent getPendingIntent() {
if (mPendingIntent == null) {
Intent intent = new Intent(context, FenceAutoAttendanceIntentService.class);
mPendingIntent = PendingIntent.getService(context, Constants.RC_SEND_FENCE_BROADCAST, intent, 0);
}
return mPendingIntent;
}
public void updateOrRemoveFenceForSubject(boolean isToRegister, String subject, double longitude, double latitude) {
LiveData<List<TimetableEntry>> fullTimetable = TimetableDatabase.getInstance(context).timetableDao().getTimetableForSubject(subject);
fullTimetable.observeForever(new Observer<List<TimetableEntry>>() {
@Override
public void onChanged(List<TimetableEntry> timetableEntries) {
fullTimetable.removeObserver(this);
Dexter.withActivity((Activity) context)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
@SuppressLint("MissingPermission")
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
List<AwarenessFence> timeFences = new ArrayList<>();
for (TimetableEntry x :
timetableEntries) {
long start = TimeUnit.MINUTES.toMillis(x.getTimeStart());
long end = start + TimeUnit.MINUTES.toMillis(5);
if ("Monday".equals(x.getDay())) {
timeFences.add(TimeFence.inIntervalOfDay(TimeFence.DAY_OF_WEEK_MONDAY, TimeZone.getDefault(), start, end));
Logger.d("Fence Added for Constraint: Day(Monday) :: Time: " + start + " to " + end + " :: Timezone: " + TimeZone.getDefault().getDisplayName());
} else if ("Tuesday".equals(x.getDay())) {
timeFences.add(TimeFence.inIntervalOfDay(TimeFence.DAY_OF_WEEK_TUESDAY, TimeZone.getDefault(), start, end));
Logger.d("Fence Added for Constraint: Day(Tuesday) :: Time: " + start + " to " + end + " :: Timezone: " + TimeZone.getDefault().getDisplayName());
} else if ("Wednesday".equals(x.getDay())) {
timeFences.add(TimeFence.inIntervalOfDay(TimeFence.DAY_OF_WEEK_WEDNESDAY, TimeZone.getDefault(), start, end));
Logger.d("Fence Added for Constraint: Day(Wednesday) :: Time: " + start + " to " + end + " :: Timezone: " + TimeZone.getDefault().getDisplayName());
} else if ("Thursday".equals(x.getDay())) {
timeFences.add(TimeFence.inIntervalOfDay(TimeFence.DAY_OF_WEEK_THURSDAY, TimeZone.getDefault(), start, end));
Logger.d("Fence Added for Constraint: Day(Thursday) :: Time: " + start + " to " + end + " :: Timezone: " + TimeZone.getDefault().getDisplayName());
} else if ("Friday".equals(x.getDay())) {
timeFences.add(TimeFence.inIntervalOfDay(TimeFence.DAY_OF_WEEK_FRIDAY, TimeZone.getDefault(), start, end));
Logger.d("Fence Added for Constraint: Day(Friday) :: Time: " + start + " to " + end + " :: Timezone: " + TimeZone.getDefault().getDisplayName());
}
}
mLocationFence = null;
mLocationFence = LocationFence.in(latitude, longitude, RADIUS_OF_FENCE, dwellTime);
if (mLocationFence != null) {
Logger.d("Location Fence is Created Successfully");
} else {
Logger.d("Location Fence is not Created Successfully,Error Occurred");
Toast.makeText(context, "Location Fence is not Created Successfully", Toast.LENGTH_SHORT).show();
return;
}
AwarenessFence finalFence = AwarenessFence.and(AwarenessFence.or(timeFences), mLocationFence);
String key = KEY_PRE_SUBJECT_FENCE + subject;
Awareness.getFenceClient(context)
.updateFences(getFenceUpdateRequest(key, finalFence, isToRegister))
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
if (isToRegister) {
Toast.makeText(context, "Fence Registered successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Fence Removed successfully", Toast.LENGTH_SHORT).show();
}
Logger.d("Fence Action Successful for Subject : " + subject + " :: Action: " + (isToRegister ? "Registered" : "Removed"));
} else {
Logger.d("Registration/Removal Unsuccessful for Fence Generation for Subject : " + subject);
Toast.makeText(context, "Fence Registration/removal unsuccessful", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(context, "Location Permission Denied!", Toast.LENGTH_SHORT).show();
Logger.d("Location Permission Denied for creating LocationFence");
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest
permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
}
private FenceUpdateRequest getFenceUpdateRequest(String key, AwarenessFence finalFence, boolean isToRegister) {
FenceUpdateRequest.Builder builder = new FenceUpdateRequest.Builder();
if (isToRegister) {
builder.addFence(key, finalFence, getPendingIntent());
} else {
builder.removeFence(key);
}
return builder.build();
}
}
//栅栏触发的服务类别
public class FenceAutoAttendanceIntentService extends IntentService {
public static final String SERVICE_AUTO_ATENDANCE_FENCE_RUN = "com.pranav.vyas.FenceAutoAttendanceIntentService";
public FenceAutoAttendanceIntentService() {
super(SERVICE_AUTO_ATENDANCE_FENCE_RUN);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Logger.addLogAdapter(new AndroidLogAdapter());
FenceState fenceState = FenceState.extract(intent);
SetUpProcessRepository repository = new SetUpProcessRepository(getApplicationContext());
String subjectNameFromFence = fenceState.getFenceKey().substring(AutoAttendanceHelper.KEY_PRE_SUBJECT_FENCE.length());
for (String x :
repository.getSubjectList()) {
if (x.equals(subjectNameFromFence)) {
checkFenceState(fenceState, getApplicationContext(), x);
}
}
}
void checkFenceState(FenceState fenceState, Context context, String subject) {
switch (fenceState.getCurrentState()) {
case FenceState.TRUE:
Logger.d("Fence Detected : " + Constants.KEY_FENCE_LOCATION);
Toast.makeText(context, "You are in the Fence of Subject :" + subject, Toast.LENGTH_SHORT).show();
sendNotification("Callback!", "Fence Available", "Just Received True callback from subject :" + subject);
break;
case FenceState.FALSE:
Logger.d("Fence is Not Detected : " + Constants.KEY_FENCE_LOCATION);
sendNotification("Callback!", "Fence UnAvailable", "Just Received False callback from subject :" + subject);
break;
case FenceState.UNKNOWN:
Logger.d("Fence Detected : " + Constants.KEY_FENCE_LOCATION + " is in unknown state");
sendNotification("Callback!", "Fence Unknown", "Just Received Unknown callback from subject :" + subject);
break;
}
}
private PendingIntent getContentIntent() {
Intent intent = new Intent(getApplicationContext(), SignInActivity.class);
return PendingIntent.getActivity(getApplicationContext(), Constants.SHOW_NOTIFICATION_RC_CONTENT_INTENT, intent, 0);
}
private NotificationCompat.Action getOpenAppAction() {
Intent openAppIntent = new Intent(getApplicationContext(), SignInActivity.class);
PendingIntent openAppFromNotification = PendingIntent.getActivity(getApplicationContext(), Constants.SHOW_NOTIFICATION_RC_OPEN_APP, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT);
return (new NotificationCompat.Action.Builder(R.drawable.logo_forground, "Open App Now", openAppFromNotification).build());
}
@SuppressWarnings("SameParameterValue")
private void sendNotification(String title, String message, String bigText) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), MainApp.NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.logo_forground)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(getContentIntent())
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(bigText))
.addAction(getOpenAppAction())
.setAutoCancel(true);
NotificationManagerCompat.from(getApplicationContext()).notify(Constants.FENCE_CALLBACK_NOTIFICATION, notificationBuilder.build());
}
}