Я работаю над приложением, которое использует распознавание активности (в автомобиле, пешком ...). Я использую это приложение, которое отлично работает. Код URL: https://www.androidhive.info/2017/12/android-user-activity-recognition-still-walking-running-driving-etc/
Но теперь я застрял на нескольких вещах. Приложение должно определить расстояние, которое пользователь превысил, когда оно равно IN_VEHICLE. И он должен работать как на переднем, так и на заднем плане
Я попытался добавить пару строк в IntentService, вот моя работа. Но это не работает. Может ли кто-нибудь объяснить / предложить, как это сделать?
public class DetectedActivitiesIntentService extends IntentService {
private FusedLocationProviderClient client;
protected static final String TAG = DetectedActivitiesIntentService.class.getSimpleName();
private Location previousLocation = null;
private Location newLocation = null;
double totalMilesDriven = 0;
public DetectedActivitiesIntentService() {
// Use the TAG to name the worker thread.
super(TAG);
}
@Override
public void onCreate() {
super.onCreate();
}
@SuppressWarnings("unchecked")
@Override
protected void onHandleIntent(Intent intent) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
// Get the list of the probable activities associated with the current state of the
// device. Each activity is associated with a confidence level, which is an int between
// 0 and 100.
ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();
for (DetectedActivity activity : detectedActivities) {
Log.i(TAG, "Detected activity: " + activity.getType() + ", " + activity.getConfidence());
broadcastActivity(activity);
}
}
private void broadcastActivity(DetectedActivity activity) {
Intent intent = new Intent(Constants.BROADCAST_DETECTED_ACTIVITY);
intent.putExtra("type", activity.getType());
intent.putExtra("confidence", activity.getConfidence());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
if(activity.getConfidence()>60 && (activity.getType()==DetectedActivity.IN_VEHICLE || activity.getType()==DetectedActivity.WALKING)){
getUsersLocation(activity);
}
}
public void getUsersLocation(final DetectedActivity activity) {
client = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
return;
}
client.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location!=null){
if(previousLocation == null){
previousLocation = location;
}else{
newLocation = location;
updateUserDistance();
sendToFirebase(activity, location.getLatitude(), location.getLongitude(), 2 );
}
}else{
}
}
});
}
private void sendToFirebase(DetectedActivity detectedActivity, double lat, double lng, int sifra ){
String userID = SafelyUserManager.getUserID();
if(userID.length()>0) {
final String locationID = FirebaseFirestore.getInstance().collection("users").document(userID).collection("locations").document().getId();
Map<String, Object> mapa = new HashMap<>();
mapa.put("latituda", lat);
mapa.put("longituda", lng);
mapa.put("type", detectedActivity.getType());
mapa.put("date", new Date());
mapa.put("sifra", sifra);
FirebaseFirestore.getInstance().collection("users").document(userID).collection("locations").document(locationID).set(mapa);
}else{
Log.d(TAG, "sendToFirebaseDDDDD: userID:"+userID);
}
}
private void updateUserDistance(){
String userID = SafelyUserManager.getUserID();
FirebaseFirestore.getInstance().collection("users").document(userID).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.get(ConstantsDictionary.totalMilesDriven)!=null){
totalMilesDriven = Double.parseDouble(documentSnapshot.get(ConstantsDictionary.totalMilesDriven).toString());
}
}
});
double distance = newLocation.distanceTo(previousLocation);
double distanceInMiles = convertMetersToMiles(distance);
totalMilesDriven+=distanceInMiles;
newLocation = previousLocation;
FirebaseFirestore.getInstance().collection("users").document(userID).update(ConstantsDictionary.totalMilesDriven, totalMilesDriven);
}
private double convertMetersToMiles(double meters){
return meters*Constants.METERS_TO_MILES;
}
}