Skip to content

Commit

Permalink
Implement minor changes based on the discussion on Github
Browse files Browse the repository at this point in the history
  • Loading branch information
cagryInside committed Jul 3, 2019
1 parent 3866e3a commit a1c2754
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 82 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ public class TravelBehaviorConstants {

public static final String PARTICIPANT_SERVICE_RESULT = "STATUS OK";

public static final String REQUEST_CODE = "tbRequestCode";
public static final String LOCATION_REQUEST_CODE = "tbRequestCode";

public static final String RECOGNITION_REQUEST_CODE = "tbRecognitionRequestCode";

public static final String TRIP_PLAN_COUNTER = "tripPlanCounter";

Expand All @@ -39,7 +41,7 @@ public class TravelBehaviorConstants {

public static final String DESTINATION_REMINDER_COUNTER = "destinationReminderCounter";

public static final String FIREBASE_ACTIVITY_TRANSITION_FOLDER = "activity-transitions/";
public static final String FIREBASE_ACTIVITY_TRANSITION_FOLDER = "activity-transitions";

public static final String FIREBASE_ARRIVAL_AND_DEPARTURE_FOLDER = "arrival-and-departures";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import org.onebusaway.android.travelbehavior.TravelBehaviorManager;
import org.onebusaway.android.travelbehavior.constants.TravelBehaviorConstants;
import org.onebusaway.android.travelbehavior.io.TravelBehaviorFileSaverExecutorManager;
import org.onebusaway.android.travelbehavior.utils.TravelBehaviorFirebaseIOUtils;

import android.content.Context;
import android.net.Uri;
Expand Down Expand Up @@ -60,7 +61,7 @@ public ListenableFuture<Result> startWork() {

private void registerUser() {
FirebaseAuth auth = FirebaseAuth.getInstance();
Log.d(TAG, "Initializing anonymous firebase user");
Log.d(TAG, "Initializing anonymous Firebase user");
TravelBehaviorFileSaverExecutorManager manager =
TravelBehaviorFileSaverExecutorManager.getInstance();
auth.signInAnonymously()
Expand All @@ -69,8 +70,8 @@ private void registerUser() {
Log.d(TAG, "Firebase user init success ID: " + auth.getUid());
saveEmailAddress(auth.getUid());
} else {
Log.d(TAG, "Firebase user init failed:" + task.getException().getMessage());
task.getException().printStackTrace();
TravelBehaviorFirebaseIOUtils.logErrorMessage(task.getException(),
"Firebase user init failed: ");
mFuture.set(Result.failure());
}
});
Expand All @@ -92,7 +93,7 @@ private void saveEmailAddress(String uid) {
}
} catch (IOException e) {
Log.e(TAG, e.toString());
Result.failure();
mFuture.set(Result.failure());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,24 @@ public class DeviceInformation {

public Integer googlePlayServicesLib;

public Long regionId;

public DeviceInformation(String appVersion, String deviceModel, String sdkVersion,
Integer sdkVersionInt, String googlePlayServicesApp,
Integer googlePlayServicesLib) {
Integer googlePlayServicesLib, Long regionId) {
this.appVersion = appVersion;
this.deviceModel = deviceModel;
this.sdkVersion = sdkVersion;
this.sdkVersionInt = sdkVersionInt;
this.googlePlayServicesApp = googlePlayServicesApp;
this.googlePlayServicesLib = googlePlayServicesLib;
this.regionId = regionId;
}

@Override
public int hashCode() {
return new HashCodeBuilder().append(appVersion).append(deviceModel).append(sdkVersion)
.append(sdkVersionInt).append(googlePlayServicesApp).append(googlePlayServicesLib)
.toHashCode();
.append(regionId).toHashCode();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,19 @@ public class LocationBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
if (location != null) {
String recordId = intent.getStringExtra(TravelBehaviorConstants.RECORD_ID);
String uid = PreferenceUtils.getString(TravelBehaviorConstants.USER_ID);
TravelBehaviorFirebaseIOUtils.saveLocation(location, uid, recordId);
Log.d(TAG, "Location provider: " + location.getProvider());
if (intent.getExtras() == null) {
Log.d(TAG, "Intent.getExtras is null");
} else {
Log.d(TAG, "Location provider is null");
Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
if (location != null) {
String recordId = intent.getStringExtra(TravelBehaviorConstants.RECORD_ID);
String uid = PreferenceUtils.getString(TravelBehaviorConstants.USER_ID);
TravelBehaviorFirebaseIOUtils.saveLocation(location, uid, recordId);
Log.d(TAG, "Location provider: " + location.getProvider());
} else {
Log.d(TAG, "Location provider is null");
}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,11 @@

import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

import org.onebusaway.android.travelbehavior.constants.TravelBehaviorConstants;
import org.onebusaway.android.travelbehavior.model.TravelBehaviorInfo;
import org.onebusaway.android.travelbehavior.utils.TravelBehaviorFirebaseIOUtils;
import org.onebusaway.android.travelbehavior.utils.TravelBehaviorUtils;
import org.onebusaway.android.util.PreferenceUtils;

Expand All @@ -39,8 +35,6 @@
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;

public class RecognitionBroadcastReceiver extends BroadcastReceiver {

private static final String TAG = "ActivityRecognition";
Expand Down Expand Up @@ -70,55 +64,46 @@ public void onReceive(Context context, Intent intent) {

private void readActivitiesByRecordId(String recordId) {
String uid = PreferenceUtils.getString(TravelBehaviorConstants.USER_ID);
FirebaseFirestore db = FirebaseFirestore.getInstance();

StringBuilder pathBuilder = new StringBuilder();
pathBuilder.append("users/").append(uid).append("/").
append(TravelBehaviorConstants.FIREBASE_ACTIVITY_TRANSITION_FOLDER);

DocumentReference document = db.collection(pathBuilder.toString()).document(recordId);
document.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()) {
Log.d(TAG, "Read document successful RecognitionBroadcastReceiver");
TravelBehaviorInfo tbi = documentSnapshot.toObject(TravelBehaviorInfo.class);
DocumentReference document = TravelBehaviorFirebaseIOUtils.
getFirebaseDocReferenceByUserIdAndRecordId(uid, recordId,
TravelBehaviorConstants.FIREBASE_ACTIVITY_TRANSITION_FOLDER);
document.get().addOnSuccessListener(documentSnapshot -> {
if(documentSnapshot.exists()) {
Log.d(TAG, "Read document successful RecognitionBroadcastReceiver");
TravelBehaviorInfo tbi = documentSnapshot.toObject(TravelBehaviorInfo.class);
if (tbi != null) {
updateTravelBehavior(tbi, recordId);
} else {
Log.d(TAG, "Read document FAILED RecognitionBroadcastReceiver");
Log.d(TAG, "TravelBehaviorInfo is null");
}
} else {
Log.d(TAG, "Read document FAILED RecognitionBroadcastReceiver");
}
});
}

private void updateTravelBehavior(TravelBehaviorInfo tbi, String recordId) {
String uid = PreferenceUtils.getString(TravelBehaviorConstants.USER_ID);
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference document = TravelBehaviorFirebaseIOUtils.
getFirebaseDocReferenceByUserIdAndRecordId(uid, recordId,
TravelBehaviorConstants.FIREBASE_ACTIVITY_TRANSITION_FOLDER);

StringBuilder pathBuilder = new StringBuilder();
pathBuilder.append("users/").append(uid).append("/").append("activity-transitions");

DocumentReference document = db.collection(pathBuilder.toString()).document(recordId);
List<Map<String,Object>> list=new ArrayList<>();
for (TravelBehaviorInfo.TravelBehaviorActivity tba: tbi.activities) {
Integer confidence = mDetectedActivityMap.get(tba.detectedActivity);
tba.confidenceLevel = confidence;
tba.confidenceLevel = mDetectedActivityMap.get(tba.detectedActivity);;
Map<String, Object> updateMap = new HashMap();
updateMap.put("detectedActivity", tba.detectedActivity);
updateMap.put("detectedActivityType", tba.detectedActivityType);
updateMap.put("confidenceLevel", tba.confidenceLevel);
list.add(updateMap);
}

document.update("activities", list).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Update travel behavior successful.");
} else {
Log.d(TAG, "Update travel behavior failed: " + task.getException().getMessage());
task.getException().printStackTrace();
}
document.update("activities", list).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Log.d(TAG, "Update travel behavior successful.");
} else {
TravelBehaviorFirebaseIOUtils.logErrorMessage(task.getException(),
"Update travel behavior failed: ");
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;

import org.onebusaway.android.app.Application;
import org.onebusaway.android.travelbehavior.constants.TravelBehaviorConstants;
Expand Down Expand Up @@ -117,23 +116,20 @@ private void saveTravelBehavior() {
}

private void saveTravelBehavior(TravelBehaviorInfo tbi) {
StringBuilder pathBuilder = new StringBuilder();
pathBuilder.append("users/").append(mUid).append("/").append(
TravelBehaviorConstants.FIREBASE_ACTIVITY_TRANSITION_FOLDER);
long riPrefix = PreferenceUtils.getLong(TravelBehaviorConstants.RECORD_ID, 0);
mRecordId = riPrefix++ + "-" + UUID.randomUUID().toString();
PreferenceUtils.saveLong(TravelBehaviorConstants.RECORD_ID, riPrefix);
pathBuilder.append(mRecordId);

DocumentReference document = FirebaseFirestore.getInstance().document(pathBuilder.toString());
DocumentReference document = TravelBehaviorFirebaseIOUtils.
getFirebaseDocReferenceByUserIdAndRecordId(mUid, mRecordId,
TravelBehaviorConstants.FIREBASE_ACTIVITY_TRANSITION_FOLDER);

document.set(tbi).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Log.d(TAG, "Activity transition document added with ID " + document.getId());
} else {
Log.d(TAG, "Activity transition document failed to be added: " +
task.getException().getMessage());
task.getException().printStackTrace();
TravelBehaviorFirebaseIOUtils.logErrorMessage(task.getException(),
"Activity transition document failed to be added: ");
}
});
}
Expand Down Expand Up @@ -180,7 +176,9 @@ private void requestActivityRecognition() {
Intent intent = new Intent(mContext, RecognitionBroadcastReceiver.class);
intent.putExtra(TravelBehaviorConstants.RECORD_ID, mRecordId);

PendingIntent pi = PendingIntent.getBroadcast(mContext, 100, intent, PendingIntent.FLAG_ONE_SHOT);
int reqCode = PreferenceUtils.getInt(TravelBehaviorConstants.RECOGNITION_REQUEST_CODE, 0);
PendingIntent pi = PendingIntent.getBroadcast(mContext, reqCode++, intent, PendingIntent.FLAG_ONE_SHOT);
PreferenceUtils.saveInt(TravelBehaviorConstants.RECOGNITION_REQUEST_CODE, reqCode);
client.requestActivityUpdates(TimeUnit.SECONDS.toMillis(10), pi);
}

Expand Down Expand Up @@ -212,16 +210,18 @@ private void requestGPSNetworkLocation() {
LocationManager lm = (LocationManager) Application.get().getBaseContext()
.getSystemService(Context.LOCATION_SERVICE);

if (lm == null) return;

List<String> providers = lm.getProviders(true);
for (String provider : providers) {
if (LocationManager.PASSIVE_PROVIDER.equals(provider)) continue;

int reqCode = PreferenceUtils.getInt(TravelBehaviorConstants.REQUEST_CODE, 0);
int reqCode = PreferenceUtils.getInt(TravelBehaviorConstants.LOCATION_REQUEST_CODE, 0);
Intent intent = new Intent(mContext, LocationBroadcastReceiver.class);
intent.putExtra(TravelBehaviorConstants.RECORD_ID, mRecordId);
PendingIntent pi = PendingIntent.getBroadcast(mContext, reqCode++, intent, PendingIntent.FLAG_ONE_SHOT);
lm.requestLocationUpdates(provider, 0, 0, pi);
PreferenceUtils.saveInt(TravelBehaviorConstants.REQUEST_CODE, reqCode);
PreferenceUtils.saveInt(TravelBehaviorConstants.LOCATION_REQUEST_CODE, reqCode);
}
}

Expand All @@ -247,7 +247,8 @@ private void saveDeviceInformation() {

DeviceInformation di = new DeviceInformation(obaVersion, Build.MODEL, Build.VERSION.RELEASE,
Build.VERSION.SDK_INT, googlePlayServicesAppVersion,
GoogleApiAvailability.GOOGLE_PLAY_SERVICES_VERSION_CODE);
GoogleApiAvailability.GOOGLE_PLAY_SERVICES_VERSION_CODE,
Application.get().getCurrentRegion().getId());

int hashCode = di.hashCode();
int mostRecentDeviceHash = PreferenceUtils.getInt(TravelBehaviorConstants.DEVICE_INFO_HASH,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ private static String buildDocumentPathByUid(String uid, String folder) {
return pathBuilder.toString();
}

private static DocumentReference getFirebaseDocReferenceByUserIdAndRecordId(String userId,
public static DocumentReference getFirebaseDocReferenceByUserIdAndRecordId(String userId,
String recordId,
String folder) {
String path = TravelBehaviorFirebaseIOUtils.buildDocumentPathByUid(userId, folder);
Expand All @@ -65,9 +65,7 @@ public static void saveLocation(Location location, String userId, String recordI
Log.d(TAG, "Location update saved with provider: " +
location.getProvider());
} else {
Log.d(TAG, "Location update failed: " +
task.getException().getMessage());
task.getException().printStackTrace();
logErrorMessage(task.getException(), "Location update failed: ");
}
});
}
Expand All @@ -84,9 +82,8 @@ public static void saveArrivalsAndDepartures(List<ArrivalAndDepartureInfo.Arriva
Log.d(TAG, "Arrivals and departure are saved with ID: " +
document.getId());
} else {
Log.d(TAG, "Arrivals and departure are failed to be saved " +
task.getException().getMessage());
task.getException().printStackTrace();
logErrorMessage(task.getException(),
"Arrivals and departure are failed to be saved ");
}
});
}
Expand All @@ -103,9 +100,8 @@ public static void saveTripPlans(List<TripPlanInfo.TripPlanData> tripPlanDataLis
Log.d(TAG, "Trip plans are saved with ID: " +
document.getId());
} else {
Log.d(TAG, "Trip plans are failed to be saved " +
task.getException().getMessage());
task.getException().printStackTrace();
logErrorMessage(task.getException(),
"Trip plans are failed to be saved ");
}
});
}
Expand All @@ -122,9 +118,8 @@ public static void saveDestinationReminders(List<DestinationReminderInfo.Destina
Log.d(TAG, "Destination reminders are saved with ID: " +
document.getId());
} else {
Log.d(TAG, "Destination reminders are failed to be saved " +
task.getException().getMessage());
task.getException().printStackTrace();
logErrorMessage(task.getException(),
"Destination reminders are failed to be saved ");
}
});
}
Expand All @@ -140,10 +135,19 @@ public static void saveDeviceInfo(DeviceInformation deviceInformation, String us
Log.d(TAG, "Device Info document added with ID " + document.getId());
PreferenceUtils.saveInt(TravelBehaviorConstants.DEVICE_INFO_HASH, hashCode);
} else {
Log.d(TAG, "Device Info transition document failed to be added: " +
task.getException().getMessage());
task.getException().printStackTrace();
logErrorMessage(task.getException(),
"Device Info transition document failed to be added: ");
}
});
}

public static void logErrorMessage(Exception e, String message) {
if (e != null) {
Log.d(TAG, message +
e.getMessage());
e.printStackTrace();
} else {
Log.d(TAG, message);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,10 @@ public static String toActivityString(int activity) {
return "IN_VEHICLE";
case DetectedActivity.ON_FOOT:
return "ON_FOOT";
case DetectedActivity.ON_BICYCLE:
return "ON_BICYCLE";
default:
return "UNKNOWN";
return "UNKNOWN = " + activity;
}
}

Expand Down

0 comments on commit a1c2754

Please sign in to comment.