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

The following examples show how to use com.google.android.gms.location.ActivityRecognition. 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
private void attachRecorder() {
    if (googleApiClient == null) {
        connectToPlayAPI();
    } else if (googleApiClient.isConnected()) {
        if (isWatchingActivity) { return; }
        startTracking();
        if (mConfig.getStopOnStillActivity()) {
            ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(
                    googleApiClient,
                    mConfig.getActivitiesInterval(),
                    detectedActivitiesPI
            );
            isWatchingActivity = true;
        }
    } else {
        googleApiClient.connect();
    }
}
 
Example #2
Source File: ActivityRecognizer.java    From react-native-activity-recognition with GNU General Public License v2.0 6 votes vote down vote up
public ActivityRecognizer(ReactApplicationContext reactContext) {
    mGoogleApiAvailability = GoogleApiAvailability.getInstance();
    mContext = reactContext.getApplicationContext();
    mReactContext = reactContext;
    connected = false;
    started = false;

    if (checkPlayServices()) {
        mBroadcastReceiver = new ActivityDetectionBroadcastReceiver();
        mGoogleApiClient = new GoogleApiClient.Builder(mContext)
            .addApi(ActivityRecognition.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    }
}
 
Example #3
Source File: ActivityRecognizedService.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public synchronized void start(boolean no_rate_limit) {
    if (Pref.getBoolean("use_remote_motion", false)) {
        Log.d(TAG, "Not starting as we are expecting remote instead of local motion");
        return;
    }
    if ((no_rate_limit) || (JoH.ratelimit("recognizer-start", 60))) {
        release_wl_start();
        wl_start = JoH.getWakeLock("recognizer-start", 60000);
        UserError.Log.e(TAG, "Restarting API");
        mApiClient = new GoogleApiClient.Builder(this)
                .addApi(ActivityRecognition.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mApiClient.connect();
    } else {
        UserError.Log.e(TAG, "Couldn't restart API due to ratelimit");
    }
}
 
Example #4
Source File: ActivityRecognizer.java    From react-native-activity-recognition with GNU General Public License v2.0 6 votes vote down vote up
public void start(long detectionIntervalMillis) {
    if (mGoogleApiClient == null) {
        throw new Error("No Google API client. Your device likely doesn't have Google Play Services.");
    }

    interval = detectionIntervalMillis;
    if (!connected) {
        mGoogleApiClient.connect();
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver, new IntentFilter(DetectionService.BROADCAST_ACTION));
    } else if (!started) {
        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(
            mGoogleApiClient,
            detectionIntervalMillis,
            getActivityDetectionPendingIntent()
        ).setResultCallback(this);
        started = true;
    }
}
 
Example #5
Source File: ActivityRecognizer.java    From react-native-activity-recognition with GNU General Public License v2.0 6 votes vote down vote up
public void stop() {
    if (mGoogleApiClient == null) {
        throw new Error("No Google API client. Your device likely doesn't have Google Play Services.");
    }

    if (started) {
        ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(
            mGoogleApiClient,
            getActivityDetectionPendingIntent()
        ).setResultCallback(this);
        started = false;
    }
    if (connected) {
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
        mGoogleApiClient.disconnect();
        connected = false;
    }
}
 
Example #6
Source File: ActivityRecognizedService.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public synchronized void start(boolean no_rate_limit) {
    if (Pref.getBoolean("use_remote_motion", false)) {
        Log.d(TAG, "Not starting as we are expecting remote instead of local motion");
        return;
    }
    if ((no_rate_limit) || (JoH.ratelimit("recognizer-start", 60))) {
        release_wl_start();
        wl_start = JoH.getWakeLock("recognizer-start", 60000);
        UserError.Log.e(TAG, "Restarting API");
        mApiClient = new GoogleApiClient.Builder(this)
                .addApi(ActivityRecognition.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mApiClient.connect();
    } else {
        UserError.Log.e(TAG, "Couldn't restart API due to ratelimit");
    }
}
 
Example #7
Source File: MotionRecognition.java    From Saiy-PS with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Cancel any future callbacks and disconnect the client.
 */
public void destroy() {

    if (activityClient != null && pendingIntent != null) {

        try {
            ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(activityClient, pendingIntent);
            activityClient.disconnect();
        } catch (final Exception e) {
            if (DEBUG) {
                MyLog.i(CLS_NAME, "destroy: Exception");
                e.printStackTrace();
            }
        }
    }
}
 
Example #8
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
private static void startActivityRecognition(final Context context) {
    if (Util.hasPlayServices(context)) {
        GoogleApiClient gac = new GoogleApiClient.Builder(context).addApi(ActivityRecognition.API).build();
        if (gac.blockingConnect().isSuccess()) {
            Log.i(TAG, "GoogleApiClient connected");
            Intent activityIntent = new Intent(context, BackgroundService.class);
            activityIntent.setAction(BackgroundService.ACTION_ACTIVITY);
            PendingIntent pi = PendingIntent.getService(context, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            boolean still = (prefs.getInt(SettingsFragment.PREF_LAST_ACTIVITY, DetectedActivity.STILL) == DetectedActivity.STILL);
            String setting = (still ? SettingsFragment.PREF_RECOGNITION_INTERVAL_STILL : SettingsFragment.PREF_RECOGNITION_INTERVAL_MOVING);
            String standard = (still ? SettingsFragment.DEFAULT_RECOGNITION_INTERVAL_STILL : SettingsFragment.DEFAULT_RECOGNITION_INTERVAL_MOVING);
            int interval = Integer.parseInt(prefs.getString(setting, standard));

            ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(gac, interval * 1000, pi);
            Log.i(TAG, "Activity updates frequency=" + interval + "s");
        }
    }
}
 
Example #9
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
private static void stopActivityRecognition(final Context context) {
    if (Util.hasPlayServices(context)) {
        GoogleApiClient gac = new GoogleApiClient.Builder(context).addApi(ActivityRecognition.API).build();
        if (gac.blockingConnect().isSuccess()) {
            Log.i(TAG, "GoogleApiClient connected");
            Intent activityIntent = new Intent(context, BackgroundService.class);
            activityIntent.setAction(BackgroundService.ACTION_ACTIVITY);
            PendingIntent pi = PendingIntent.getService(context, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(gac, pi);

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = prefs.edit();
            editor.remove(SettingsFragment.PREF_LAST_ACTIVITY);
            editor.remove(SettingsFragment.PREF_LAST_CONFIDENCE);
            editor.apply();
            Log.i(TAG, "Canceled activity updates");
        }
    }
}
 
Example #10
Source File: BackgroundLocationUpdateService.java    From cordova-background-geolocation-services with Apache License 2.0 6 votes vote down vote up
private void attachDARecorder() {
  if (detectedActivitiesAPI == null) {
      buildDAClient();
  } else if (detectedActivitiesAPI.isConnected()) {
    ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(
                    detectedActivitiesAPI,
                    this.activitiesInterval,
                    detectedActivitiesPI
            );
      if(isDebugging) {
          Log.d(TAG, "- DA RECORDER attached - start recording location updates");
      }
  } else {
    Log.i(TAG, "NOT CONNECTED, CONNECT");
      detectedActivitiesAPI.connect();
  }
}
 
Example #11
Source File: BackgroundLocationUpdateService.java    From cordova-background-geolocation-services with Apache License 2.0 5 votes vote down vote up
private void detatchDARecorder() {
  if (detectedActivitiesAPI == null) {
      buildDAClient();
  } else if (detectedActivitiesAPI.isConnected()) {
    ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(detectedActivitiesAPI, detectedActivitiesPI);
      if(isDebugging) {
          Log.d(TAG, "- Recorder detached - stop recording activity updates");
      }
  } else {
      detectedActivitiesAPI.connect();
  }
}
 
Example #12
Source File: BackgroundLocationUpdateService.java    From cordova-background-geolocation-services with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnected(Bundle bundle) {
    Log.w(TAG, "Activity Client Connected");
    ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(
            detectedActivitiesAPI,
            activitiesInterval,
            detectedActivitiesPI
    );
}
 
Example #13
Source File: BackgroundLocationUpdateService.java    From cordova-background-geolocation-services with Apache License 2.0 5 votes vote down vote up
protected synchronized void buildDAClient() {
  Log.i(TAG, "BUILDING DA CLIENT");
     detectedActivitiesAPI = new GoogleApiClient.Builder(this)
             .addApi(ActivityRecognition.API)
             .addConnectionCallbacks(cb)
             .addOnConnectionFailedListener(failedCb)
             .build();

    detectedActivitiesAPI.connect();
}
 
Example #14
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mApiClient = new GoogleApiClient.Builder(this)
            .addApi(ActivityRecognition.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    mApiClient.connect();
}
 
Example #15
Source File: AndroidActivityRecognitionWrapper.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
private void connectGoogleAPI() {
	mGoogleApiClient = new GoogleApiClient.Builder(context)
			                   .addApi(ActivityRecognition.API)
			                   .addConnectionCallbacks(this)
			                   .addOnConnectionFailedListener(this)
			                   .build();
	mGoogleApiClient.connect();
	Log.d(TAG, "Connected to google API");
}
 
Example #16
Source File: AndroidActivityRecognitionWrapper.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onConnected(Bundle bundle) {
	PendingIntent mActivityReconPendingIntent = PendingIntent
			                                            .getService(context, 0, ActivityRecognitionService.getIntent(), PendingIntent.FLAG_UPDATE_CURRENT);

	Log.d(TAG, "connected to ActivityRecognition");
	ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, 0, mActivityReconPendingIntent);

}
 
Example #17
Source File: PlayServicesLocationApi.java    From patrol-android with GNU General Public License v3.0 5 votes vote down vote up
protected synchronized void buildGoogleApiClient(Context context) {
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .addApi(ActivityRecognition.API)
            .build();
    mGoogleApiClient.connect();
}
 
Example #18
Source File: ActivityRecognitionLocationProvider.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
private void connectToPlayAPI() {
    logger.debug("Connecting to Google Play Services");
    googleApiClient =  new GoogleApiClient.Builder(mContext)
            .addApi(LocationServices.API)
            .addApi(ActivityRecognition.API)
            .addConnectionCallbacks(this)
            //.addOnConnectionFailedListener(this)
            .build();
    googleApiClient.connect();
}
 
Example #19
Source File: ActivityRecognizedService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void requestUpdates(int frequency) {
    try {
        received = 0; // reset
        wl_global = JoH.getWakeLock("motion-wait", frequency * 5); // released later
        if (d) Log.d(TAG, "requestUpdates called: " + frequency);
        incrementInternalPrefsLong(REQUESTED);
        interpretRatio(this);
        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, frequency, get_pending_intent());
    } catch (Exception e) {
        UserError.Log.wtf(TAG, "Got exception starting activity recognition: " + e.toString());
    }
}
 
Example #20
Source File: ActivityRecognitionLocationProvider.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
private void detachRecorder() {
    if (isWatchingActivity) {
        logger.debug("Detaching recorder");
        ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(googleApiClient, detectedActivitiesPI);
        isWatchingActivity = false;
    }
}
 
Example #21
Source File: HARecognizerApiHandler.java    From DataLogger with MIT License 5 votes vote down vote up
/**
 * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the
 * ActivityRecognition API.
 */
private synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(mContext)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(ActivityRecognition.API)
            .build();
}
 
Example #22
Source File: RxLocationBaseOnSubscribe.java    From RxGps with Apache License 2.0 5 votes vote down vote up
protected RxLocationBaseOnSubscribe(@NonNull RxLocation rxLocation, Long timeout, TimeUnit timeUnit) {
    this.ctx = rxLocation.ctx;
    this.services = new Api[]{ LocationServices.API, ActivityRecognition.API };
    this.scopes = null;

    if (timeout != null && timeUnit != null) {
        this.timeoutTime = timeout;
        this.timeoutUnit = timeUnit;
    } else {
        this.timeoutTime = rxLocation.timeoutTime;
        this.timeoutUnit = rxLocation.timeoutUnit;
    }
}
 
Example #23
Source File: ActivityRequestUpdatesSingleOnSubscribe.java    From RxGps with Apache License 2.0 5 votes vote down vote up
@Override
protected void onGoogleApiClientReady(GoogleApiClient apiClient, SingleEmitter<Status> emitter) {
    //noinspection MissingPermission
    setupLocationPendingResult(
            ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(apiClient, detectionIntervalMillis, pendingIntent),
            SingleResultCallBack.get(emitter)
    );
}
 
Example #24
Source File: ActivityRemoveUpdatesSingleOnSubscribe.java    From RxGps with Apache License 2.0 5 votes vote down vote up
@Override
protected void onGoogleApiClientReady(GoogleApiClient apiClient, SingleEmitter<Status> emitter) {
    //noinspection MissingPermission
    setupLocationPendingResult(
            ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(apiClient, pendingIntent),
            SingleResultCallBack.get(emitter)
    );
}
 
Example #25
Source File: MotionRecognition.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onConnected(@Nullable final Bundle bundle) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "onConnected");
    }

    if (activityClient != null && pendingIntent != null) {
        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(activityClient,
                MotionIntentService.UPDATE_INTERVAL, pendingIntent).setResultCallback(this);
    }
}
 
Example #26
Source File: ActivityRecognizedService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void requestUpdates(int frequency) {
    try {
        received = 0; // reset
        wl_global = JoH.getWakeLock("motion-wait", frequency * 5); // released later
        if (d) Log.d(TAG, "requestUpdates called: " + frequency);
        incrementInternalPrefsLong(REQUESTED);
        interpretRatio(this);
        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, frequency, get_pending_intent());
    } catch (Exception e) {
        UserError.Log.wtf(TAG, "Got exception starting activity recognition: " + e.toString());
    }
}
 
Example #27
Source File: ActivityRecognizedService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void stopUpdates() {
    try {
        if (d) Log.d(TAG, "stopUpdates called");
        ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(mApiClient, get_pending_intent());
        if (wl_global != null) {
            if (d) Log.d(TAG, "release wl_global");
            JoH.releaseWakeLock(wl_global);
            wl_global = null;
        }
    } catch (Exception e) {
        UserError.Log.wtf(TAG, "Got exception stopping activity recognition: " + e.toString());
    }
}
 
Example #28
Source File: ActivityRecognizedService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void stopUpdates() {
    try {
        if (d) Log.d(TAG, "stopUpdates called");
        ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(mApiClient, get_pending_intent());
        if (wl_global != null) {
            if (d) Log.d(TAG, "release wl_global");
            JoH.releaseWakeLock(wl_global);
            wl_global = null;
        }
    } catch (Exception e) {
        UserError.Log.wtf(TAG, "Got exception stopping activity recognition: " + e.toString());
    }
}
 
Example #29
Source File: MotionRecognition.java    From Saiy-PS with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Prepare the Activity Recognition API for use.
 *
 * @param ctx the application context
 */
public void prepare(@NonNull final Context ctx) {

    final GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
    final int connectionResult = apiAvailability.isGooglePlayServicesAvailable(ctx);

    switch (connectionResult) {

        case ConnectionResult.SUCCESS:

            activityClient = new GoogleApiClient.Builder(ctx).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).addApi(ActivityRecognition.API).build();

            pendingIntent = PendingIntent.getService(ctx, MotionIntentService.REQUEST_CODE,
                    new Intent(ctx, MotionIntentService.class),
                    PendingIntent.FLAG_UPDATE_CURRENT);

            try {

                ProviderInstaller.installIfNeededAsync(ctx, new ProviderInstaller.ProviderInstallListener() {
                    @Override
                    public void onProviderInstalled() {
                        if (DEBUG) {
                            MyLog.i(CLS_NAME, "prepare: play services onProviderInstalled");
                        }
                    }

                    @Override
                    public void onProviderInstallFailed(final int errorCode, final Intent intent) {
                        if (DEBUG) {
                            MyLog.w(CLS_NAME, "prepare: play services onProviderInstallFailed");
                        }

                        if (apiAvailability.isUserResolvableError(errorCode)) {
                            if (DEBUG) {
                                MyLog.w(CLS_NAME, "prepare: play services onProviderInstallFailed");
                            }

                            apiAvailability.showErrorNotification(ctx, errorCode);

                        } else {
                            // TODO - unrecoverable
                        }
                    }
                });
            } catch (final Exception e) {
                if (DEBUG) {
                    MyLog.w(CLS_NAME, "prepare: play services unavailable");
                    e.printStackTrace();
                }
            }

            break;

        default:
            if (DEBUG) {
                MyLog.w(CLS_NAME, "prepare: play services unavailable");
            }
            apiAvailability.showErrorNotification(ctx, connectionResult);
            break;
    }
}
 
Example #30
Source File: SettingsFragment.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    running = true;

    addPreferencesFromResource(R.xml.preferences);

    db = new DatabaseHelper(getActivity());

    // Shared geo point
    Uri data = getActivity().getIntent().getData();
    if (data != null && "geo".equals(data.getScheme())) {
        Intent geopointIntent = new Intent(getActivity(), BackgroundService.class);
        geopointIntent.setAction(BackgroundService.ACTION_GEOPOINT);
        geopointIntent.putExtra(BackgroundService.EXTRA_GEOURI, data);
        getActivity().startService(geopointIntent);

        edit_waypoints();
    }

    Bundle extras = getActivity().getIntent().getExtras();
    if (extras != null && extras.containsKey(EXTRA_ACTION)) {
        String action = extras.getString(EXTRA_ACTION);
        if (ACTION_LOCATION.equals(action))
            location_history();
        else if (ACTION_STEPS.equals(action))
            step_history();
        else if (ACTION_WEATHER.equals(action))
            weather_history();
        else if (ACTION_FORECAST.equals(action))
            weather_forecast();
    }

    if (Util.hasPlayServices(getActivity()))
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "Connecting to Play services");
                GoogleApiClient gac = new GoogleApiClient.Builder(getActivity()).addApi(ActivityRecognition.API).build();
                ConnectionResult result = gac.blockingConnect();
                if (result.isSuccess())
                    Log.i(TAG, "Connected to Play services");
                else {
                    Log.w(TAG, "Error connecting to Play services, error=" + result.getErrorMessage() + " resolution=" + result.hasResolution());
                    if (result.hasResolution())
                        try {
                            result.startResolutionForResult(getActivity(), ACTIVITY_PLAY_SERVICES);
                        } catch (IntentSender.SendIntentException ex) {
                            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        }
                    else
                        Util.toast(result.getErrorMessage(), Toast.LENGTH_SHORT, getActivity());
                }
            }
        }).start();
}