com.google.android.gms.location.ActivityRecognitionResult Java Examples

The following examples show how to use com.google.android.gms.location.ActivityRecognitionResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ActivityRecognitionLocationProvider.java    From background-geolocation-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
    ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();

    //Find the activity with the highest percentage
    lastActivity = getProbableActivity(detectedActivities);

    logger.debug("Detected activity={} confidence={}", BackgroundActivity.getActivityString(lastActivity.getType()), lastActivity.getConfidence());

    handleActivity(lastActivity);

    if (lastActivity.getType() == DetectedActivity.STILL) {
        showDebugToast("Detected STILL Activity");
        // stopTracking();
        // we will delay stop tracking after position is found
    } else {
        showDebugToast("Detected ACTIVE Activity");
        startTracking();
    }
    //else do nothing
}
 
Example #2
Source File: MainActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
private void listing15_28() {
  // Listing 15-28: Retrieving Snapshot context signal results
  Awareness.SnapshotApi.getDetectedActivity(mGoogleApiClient)
    .setResultCallback(new ResultCallback<DetectedActivityResult>() {
      @Override
      public void onResult(@NonNull DetectedActivityResult detectedActivityResult) {
        if (!detectedActivityResult.getStatus().isSuccess()) {
          Log.e(TAG, "Current activity unknown.");
        } else {
          ActivityRecognitionResult ar = detectedActivityResult.getActivityRecognitionResult();
          DetectedActivity probableActivity = ar.getMostProbableActivity();

          // TODO: Do something with the detected user activity.
        }
      }
    });
}
 
Example #3
Source File: SKActivity.java    From SensingKit-Android with GNU Lesser General Public License v3.0 6 votes vote down vote up
private DetectedActivity getActivity(ActivityRecognitionResult result) {

        // Get the most probable activity from the list of activities in the result
        DetectedActivity mostProbableActivity = result.getMostProbableActivity();

        // If the activity is ON_FOOT, choose between WALKING or RUNNING
        if (mostProbableActivity.getType() == DetectedActivity.ON_FOOT) {

            // Iterate through all possible activities. The activities are sorted by most probable activity first.
            for (DetectedActivity activity : result.getProbableActivities()) {

                if (activity.getType() == DetectedActivity.WALKING || activity.getType() == DetectedActivity.RUNNING) {
                    return activity;
                }
            }

            // It is ON_FOOT, but not sure if it is WALKING or RUNNING
            Log.i(TAG, "Activity ON_FOOT, but not sure if it is WALKING or RUNNING.");
            return mostProbableActivity;
        }
        else
        {
            return mostProbableActivity;
        }

    }
 
Example #4
Source File: BackgroundLocationUpdateService.java    From cordova-background-geolocation-services with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
  ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
  ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();

  //Find the activity with the highest percentage
  lastActivity = Constants.getProbableActivity(detectedActivities);

  Log.w(TAG, "MOST LIKELY ACTIVITY: " + Constants.getActivityString(lastActivity.getType()) + " " + lastActivity.getConfidence());

  Intent mIntent = new Intent(Constants.CALLBACK_ACTIVITY_UPDATE);
  mIntent.putExtra(Constants.ACTIVITY_EXTRA, detectedActivities);
  getApplicationContext().sendBroadcast(mIntent);
  Log.w(TAG, "Activity is recording" + isRecording);

  if(lastActivity.getType() == DetectedActivity.STILL && isRecording) {
      showDebugToast(context, "Detected Activity was STILL, Stop recording");
      stopRecording();
  } else if(lastActivity.getType() != DetectedActivity.STILL && !isRecording) {
      showDebugToast(context, "Detected Activity was ACTIVE, Start Recording");
      startRecording();
  }
  //else do nothing
}
 
Example #5
Source File: SKActivityRecognitionIntentService.java    From SensingKit-Android with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {

    // If the intent contains an update
    if (ActivityRecognitionResult.hasResult(intent)) {

        // Get the update
        ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);

        Intent i = new Intent(BROADCAST_UPDATE);
        i.putExtra(RECOGNITION_RESULT, result);
        LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);
        manager.sendBroadcast(i);
    }

}
 
Example #6
Source File: DetectedActivitiesIntentService.java    From location-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Handles incoming intents.
 * @param intent The Intent is provided (inside a PendingIntent) when requestActivityUpdates()
 *               is called.
 */
@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();

    PreferenceManager.getDefaultSharedPreferences(this)
            .edit()
            .putString(Constants.KEY_DETECTED_ACTIVITIES,
                    Utils.detectedActivitiesToJson(detectedActivities))
            .apply();

    // Log each activity.
    Log.i(TAG, "activities detected");
    for (DetectedActivity da: detectedActivities) {
        Log.i(TAG, Utils.getActivityString(
                        getApplicationContext(),
                        da.getType()) + " " + da.getConfidence() + "%"
        );
    }
}
 
Example #7
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void detectActivity() {
    Awareness.SnapshotApi.getDetectedActivity(mGoogleApiClient)
            .setResultCallback(new ResultCallback<DetectedActivityResult>() {
                @Override
                public void onResult(@NonNull DetectedActivityResult detectedActivityResult) {
                    ActivityRecognitionResult result = detectedActivityResult.getActivityRecognitionResult();
                    Log.e("Tuts+", "time: " + result.getTime());
                    Log.e("Tuts+", "elapsed time: " + result.getElapsedRealtimeMillis());
                    Log.e("Tuts+", "Most likely activity: " + result.getMostProbableActivity().toString());

                    for( DetectedActivity activity : result.getProbableActivities() ) {
                        Log.e("Tuts+", "Activity: " + activity.getType() + " Liklihood: " + activity.getConfidence() );
                    }
                }
            });
}
 
Example #8
Source File: ActivityRecognitionIntentService.java    From android-notification-log with MIT License 5 votes vote down vote up
@Override
protected void onHandleIntent(@Nullable Intent intent) {
	if(intent == null) {
		return;
	}

	ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);

	ArrayList<DetectedActivity> detectedActivities = (ArrayList<DetectedActivity>) result.getProbableActivities();

	ArrayList<String> activities = new ArrayList<>();
	ArrayList<Integer> confidences = new ArrayList<>();

	for(DetectedActivity activity : detectedActivities) {
		activities.add(getActivityString(activity.getType()));
		confidences.add(activity.getConfidence());
	}

	JSONObject json = new JSONObject();
	String str = null;
	try {
		long now = System.currentTimeMillis();
		json.put("time", now);
		json.put("offset", TimeZone.getDefault().getOffset(now));
		json.put("activities", new JSONArray(activities));
		json.put("confidences", new JSONArray(confidences));
		str = json.toString();
	} catch (JSONException e) {
		if(Const.DEBUG) e.printStackTrace();
	}

	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
	sp.edit().putString(Const.PREF_LAST_ACTIVITY, str).apply();
}
 
Example #9
Source File: BackgroundService.java    From GeoLog with Apache License 2.0 5 votes vote down vote up
private void processActivity(Intent intent) {
	if (handler != null) {
		final DetectedActivity activity = ActivityRecognitionResult.extractResult(intent).getMostProbableActivity();
		if (Database.isDetectedActivityValid(activity)) {
			wakelock.acquire();
			handler.post(new Runnable() {					
				@Override
				public void run() {
					setActivity(Database.activityFromDetectedActivity(activity), activity.getConfidence());
					wakelock.release();
				}
			});
		}
	}			
}
 
Example #10
Source File: BackgroundService.java    From GeoLog with Apache License 2.0 5 votes vote down vote up
public boolean processIntent(Intent intent) {
	if (intent == null) return false;
	
	if (ActivityRecognitionResult.hasResult(intent)) {
		processActivity(intent);
		return true;
	} else if (intent.hasExtra(EXTRA_ALARM_CALLBACK)) {
		processAlarmCallback(intent);
		return true;
	}			
	
	return false;
}
 
Example #11
Source File: ActivityRecognitionIntentServiceTest.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
private void startWithType(int activityType) throws InterruptedException {
    DetectedActivity activity = new DetectedActivity(activityType,1);
    ActivityRecognitionResult result = new ActivityRecognitionResult(activity,1000,1000);

    Intent startIntent = new Intent();
    startIntent.putExtra(ActivityRecognitionResult.EXTRA_ACTIVITY_RESULT,result);
    startIntent.setClass(getSystemContext(), ActivityRecognitionIntentService.class);

    startService(startIntent);
}
 
Example #12
Source File: ActivityRecognitionIntentService.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
private void logActivity(ActivityRecognitionResult result) {
    Log.d(TAG, "Unknown Activity");
    Log.d(TAG, "Probable Activities");
    for(DetectedActivity activity : result.getProbableActivities()) {
        Log.d(TAG, "Most Probable list: " + result.getMostProbableActivity().getType());
        Log.d(TAG, "Most Probable list: " + result.getMostProbableActivity().toString());
    }
    Log.d(TAG, "Most Probable: " + result.getMostProbableActivity().getType());
    Log.d(TAG, "Most Probable: " + result.getMostProbableActivity().toString());
}
 
Example #13
Source File: ActivityRecognitionIntentService.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    ((PebbleBikeApplication)getApplication()).inject(this);

    if (ActivityRecognitionResult.hasResult(intent)) {
        ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);

        switch(result.getMostProbableActivity().getType()) {

            case DetectedActivity.ON_BICYCLE:
                Log.d(TAG, "ON_BICYCLE");
                sendReply(result.getMostProbableActivity().getType());
                break;
            case DetectedActivity.WALKING:
                Log.d(TAG, "WALKING");
                sendReply(result.getMostProbableActivity().getType());
                break;
            case DetectedActivity.RUNNING:
                Log.d(TAG, "RUNNING");
                sendReply(result.getMostProbableActivity().getType());
                break;
            case DetectedActivity.ON_FOOT:
                Log.d(TAG, "ON_FOOT");
                sendReply(result.getMostProbableActivity().getType());
                break;
            case DetectedActivity.TILTING:
                Log.d(TAG, "TILTING");
                break;
            case DetectedActivity.STILL:
                Log.d(TAG, "STILL");
                sendReply(result.getMostProbableActivity().getType());
                break;
            default:
                logActivity(result);
        }
    }
}
 
Example #14
Source File: AndroidActivityRecognitionWrapper.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void runOnce() {
	if (!isRunning()) {
		disconnectGoogleAPI();
	} else {
		if (mGoogleApiClient == null) {
			connectGoogleAPI();
		}
		updateWrapperInfo();

		if (ActivityRecognitionResult.hasResult(ActivityRecognitionService.getIntent())) {
			// Get the update
			ActivityRecognitionResult result =
					ActivityRecognitionResult.extractResult(ActivityRecognitionService.getIntent());

			DetectedActivity mostProbableActivity
					= result.getMostProbableActivity();

			// Get the confidence % (probability)
			double confidence = mostProbableActivity.getConfidence();

			// Get the type
			double activityType = mostProbableActivity.getType();
	   /* types:
	    * DetectedActivity.IN_VEHICLE
           * DetectedActivity.ON_BICYCLE
           * DetectedActivity.ON_FOOT
           * DetectedActivity.STILL
           * DetectedActivity.UNKNOWN
           * DetectedActivity.TILTING
           */
			StreamElement streamElement = new StreamElement(FIELD_NAMES, FIELD_TYPES,
					                                               new Serializable[]{activityType, confidence});
			postStreamElement(streamElement);
		} else {
			Log.d(TAG, "No results for AndroidActivityRecognition");
		}
	}
}
 
Example #15
Source File: ActivityRecognizedService.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    if(ActivityRecognitionResult.hasResult(intent)) {
        ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
        handleDetectedActivities( result.getProbableActivities() );
    }
}
 
Example #16
Source File: DetectionService.java    From react-native-activity-recognition with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
    ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();

    Log.d(TAG, "Detected activities:");
    for (DetectedActivity da: detectedActivities) {
        Log.d(TAG, getActivityString(da.getType()) + " (" + da.getConfidence() + "%)");
    }

    Intent localIntent = new Intent(BROADCAST_ACTION);
    localIntent.putExtra(ACTIVITY_EXTRA, detectedActivities);
    LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}
 
Example #17
Source File: AwarenessImpl.java    From Myna with Apache License 2.0 5 votes vote down vote up
private void handleResult(@NonNull DetectedActivityResult detectedActivityResult){
    ActivityRecognitionResult ar = detectedActivityResult.getActivityRecognitionResult();
    RecognizedActivityResult result = new RecognizedActivityResult();
    List<DetectedActivity> acts = ar.getProbableActivities();
    result.activities = new RecognizedActivity[acts.size()];
    for(int i = 0; i < acts.size(); ++i){
        DetectedActivity act = acts.get(i);
        result.activities[i] = new RecognizedActivity(act.getType(), act.getConfidence());
    }
    resultCallback.onResult(result);
}
 
Example #18
Source File: MotionIntentService.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void onHandleIntent(final Intent intent) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "onHandleIntent");
    }

    if (SPH.getMotionEnabled(getApplicationContext())) {

        if (intent != null) {
            if (DEBUG) {
                examineIntent(intent);
            }

            if (ActivityRecognitionResult.hasResult(intent)) {
                final Motion motion = extractMotion(intent);
                if (motion != null) {
                    MotionHelper.setMotion(getApplicationContext(), motion);
                } else {
                    if (DEBUG) {
                        MyLog.i(CLS_NAME, "onHandleIntent: motion null: ignoring");
                    }
                }
            } else {
                if (DEBUG) {
                    MyLog.i(CLS_NAME, "onHandleIntent: no ActivityRecognition results");
                }
            }
        } else {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "onHandleIntent: intent: null");
            }
        }
    } else {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "onHandleIntent: user has switched off. Don't store.");
        }
    }
}
 
Example #19
Source File: HARecognizerApiIntentService.java    From DataLogger with MIT License 5 votes vote down vote up
@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();

    // Broadcast the list of detected activities.
    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(Constants.BROADCAST_ACTION)
            .putExtra(Constants.DETECTED_ACTIVITIES_INTENT_KEY, detectedActivities)
    );

}
 
Example #20
Source File: GoogleLocationManagerServiceImpl.java    From android_packages_apps_GmsCore with Apache License 2.0 4 votes vote down vote up
@Override
public ActivityRecognitionResult getLastActivity(String packageName) throws RemoteException {
    Log.d(TAG, "getLastActivity");
    PackageUtils.checkPackageUid(context, packageName, Binder.getCallingUid());
    return null;
}
 
Example #21
Source File: ActivityRecognitionIntentService.java    From mytracks with Apache License 2.0 4 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
  if (!ActivityRecognitionResult.hasResult(intent)) {
    return;
  }
  ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
  DetectedActivity detectedActivity = result.getMostProbableActivity();
  if (detectedActivity == null) {
    return;
  }
  if (detectedActivity.getConfidence() < REQUIRED_CONFIDENCE) {
    return;
  }

  long recordingTrackId = PreferencesUtils.getLong(this, R.string.recording_track_id_key);
  if (recordingTrackId == PreferencesUtils.RECORDING_TRACK_ID_DEFAULT) {
    return;
  }
  boolean recordingTrackPaused = PreferencesUtils.getBoolean(
      this, R.string.recording_track_paused_key, PreferencesUtils.RECORDING_TRACK_PAUSED_DEFAULT);
  if (recordingTrackPaused) {
    return;
  }

  int currentType = PreferencesUtils.getInt(this, R.string.activity_recognition_type_key,
      PreferencesUtils.ACTIVITY_RECOGNITION_TYPE_DEFAULT);

  switch (detectedActivity.getType()) {
    case DetectedActivity.IN_VEHICLE:
      if (currentType != DetectedActivity.IN_VEHICLE) {
        PreferencesUtils.setInt(
            this, R.string.activity_recognition_type_key, DetectedActivity.IN_VEHICLE);
      }
      break;
    case DetectedActivity.ON_BICYCLE:
      if (currentType != DetectedActivity.IN_VEHICLE
          && currentType != DetectedActivity.ON_BICYCLE) {
        PreferencesUtils.setInt(
            this, R.string.activity_recognition_type_key, DetectedActivity.ON_BICYCLE);
      }
      break;
    case DetectedActivity.ON_FOOT:
      if (currentType != DetectedActivity.IN_VEHICLE && currentType != DetectedActivity.ON_BICYCLE
          && currentType != DetectedActivity.ON_FOOT) {
        PreferencesUtils.setInt(
            this, R.string.activity_recognition_type_key, DetectedActivity.ON_FOOT);
      }
      break;
    default:
      break;
  }
}
 
Example #22
Source File: SnapshotApiActivity.java    From android-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Get current activity of the user. This is under snapshot api category.
 * Current activity and confidence level will be displayed on the screen.
 */
private void getCurrentActivity() {
    Awareness.SnapshotApi.getDetectedActivity(mGoogleApiClient)
            .setResultCallback(new ResultCallback<DetectedActivityResult>() {
                @Override
                public void onResult(@NonNull DetectedActivityResult detectedActivityResult) {
                    if (!detectedActivityResult.getStatus().isSuccess()) {
                        Toast.makeText(SnapshotApiActivity.this, "Could not get the current activity.", Toast.LENGTH_LONG).show();
                        return;
                    }
                    ActivityRecognitionResult ar = detectedActivityResult.getActivityRecognitionResult();
                    DetectedActivity probableActivity = ar.getMostProbableActivity();

                    //set the activity name
                    TextView activityName = (TextView) findViewById(R.id.probable_activity_name);
                    switch (probableActivity.getType()) {
                        case DetectedActivity.IN_VEHICLE:
                            activityName.setText("In vehicle");
                            break;
                        case DetectedActivity.ON_BICYCLE:
                            activityName.setText("On bicycle");
                            break;
                        case DetectedActivity.ON_FOOT:
                            activityName.setText("On foot");
                            break;
                        case DetectedActivity.RUNNING:
                            activityName.setText("Running");
                            break;
                        case DetectedActivity.STILL:
                            activityName.setText("Still");
                            break;
                        case DetectedActivity.TILTING:
                            activityName.setText("Tilting");
                            break;
                        case DetectedActivity.UNKNOWN:
                            activityName.setText("Unknown");
                            break;
                        case DetectedActivity.WALKING:
                            activityName.setText("Walking");
                            break;
                    }

                    //set the confidante level
                    ProgressBar confidenceLevel = (ProgressBar) findViewById(R.id.probable_activity_confidence);
                    confidenceLevel.setProgress(probableActivity.getConfidence());

                    //display the time
                    TextView timeTv = (TextView) findViewById(R.id.probable_activity_time);
                    SimpleDateFormat sdf = new SimpleDateFormat("h:mm a dd-MM-yyyy", Locale.getDefault());
                    timeTv.setText("as on: " + sdf.format(new Date(ar.getTime())));
                }
            });
}
 
Example #23
Source File: MotionIntentService.java    From Saiy-PS with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Store the most recent user activity for use elsewhere in the application.
 *
 * @param intent which should contain an {@link ActivityRecognitionResult}
 * @return a {@link Motion} object
 */
private Motion extractMotion(final Intent intent) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "extractMotion");
    }

    final ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);

    if (result != null) {

        final DetectedActivity detectedActivity = result.getMostProbableActivity();

        if (detectedActivity != null) {
            if (DEBUG) {
                logActivity(detectedActivity);
            }

            final int confidence = detectedActivity.getConfidence();

            if (confidence > Motion.CONFIDENCE_THRESHOLD) {

                switch (detectedActivity.getType()) {

                    case DetectedActivity.WALKING:
                    case DetectedActivity.IN_VEHICLE:
                    case DetectedActivity.ON_BICYCLE:
                    case DetectedActivity.ON_FOOT:
                    case DetectedActivity.RUNNING:
                    case DetectedActivity.STILL:
                        return new Motion(detectedActivity.getType(), confidence, result.getTime());
                    case DetectedActivity.TILTING:
                    case DetectedActivity.UNKNOWN:
                    default:
                        break;
                }

            } else {
                if (DEBUG) {
                    MyLog.v(CLS_NAME, "detectedActivity: ignoring low confidence");
                }
            }
        } else {
            if (DEBUG) {
                MyLog.i(CLS_NAME, "detectedActivity: null");
            }
        }
    } else {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "detectedActivity: ActivityRecognitionResult: null");
        }
    }

    return null;
}
 
Example #24
Source File: ActivityRecognitionResultAssert.java    From assertj-android with Apache License 2.0 4 votes vote down vote up
public ActivityRecognitionResultAssert(ActivityRecognitionResult actual) {
  super(actual, ActivityRecognitionResultAssert.class);
}