The motto here is calling the Service 'ActivityTrackerService' when I say requestActivityUpdates() using the GoogleApiClient's ActivityRecognition.ActivityRecognitionApi as shown in the code below when googleApiClient.connect() is called. After the api is connected the onConnected callback executes and activity updates are requested. The code runs perfectly fine as in the result call back i get a success. But some how Service class onHandleIntent is not called. I am not sure if the service has started working or not.

Service Provider Class:

public class ActivityServiceProvider {
    private Context context;
    private GoogleApiClient googleApiClient;
    private PendingIntent mActivityRecognitionPendingIntent;

    public ActivityServiceProvider(Context context) {
        this.context = context;
        createGoogleLocationServiceClient();
    }

    private void createGoogleLocationServiceClient() {
        googleApiClient = new GoogleApiClient.Builder(context).addApi(ActivityRecognition.API)
                .addConnectionCallbacks(new ConnectionCallbacks() {

                    @Override
                    public void onConnectionSuspended(int arg0) {
                        Log.d(ActivityUtils.APPTAG, "GoogleApiClient Suspended");
                    }

                    @Override
                    public void onConnected(Bundle arg0) {
                        Log.d(ActivityUtils.APPTAG, "GoogleApiClient Connected Now");
                        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(googleApiClient,
                                ActivityUtils.DETECTION_INTERVAL_MILLISECONDS, getPendingIntent()).setResultCallback(
                                new ResultCallback<Status>() {

                                    @Override
                                    public void onResult(Status arg0) {
                                        if (arg0.isSuccess()) {
                                            Log.d(ActivityUtils.APPTAG, "Updates Requested Successfully");
                                        } else {
                                            Log.d(ActivityUtils.APPTAG, "Updates could not be requested");
                                        }
                                    }
                                });
                    }
                }).addOnConnectionFailedListener(new OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(ConnectionResult arg0) {
                        Log.d(ActivityUtils.APPTAG, "GoogleApiClient Connection Failed");
                    }
                }).build();
    }

    public PendingIntent getRequestPendingIntent() {
        return mActivityRecognitionPendingIntent;
    }

    public void setRequestPendingIntent(PendingIntent intent) {
        mActivityRecognitionPendingIntent = intent;
    }

    private PendingIntent getPendingIntent() {
        Intent intent = new Intent(context, ActivityTrackerService.class);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        setRequestPendingIntent(pendingIntent);
        return pendingIntent;
    }

    private boolean servicesConnected() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
        if (ConnectionResult.SUCCESS == resultCode) {
            Log.d(ActivityUtils.APPTAG, context.getString(R.string.play_services_available));
            return true;
        } else {
            Log.d(ActivityUtils.APPTAG, context.getString(R.string.play_services_unavailable));
            return false;
        }
    }

    public void connect() {
        if (servicesConnected() && !googleApiClient.isConnected()) {
            Log.d(ActivityUtils.APPTAG, "GoogleApiClient Connection Initiated: connect() Called");
            googleApiClient.connect();
        } else {
            Log.d(ActivityUtils.APPTAG, "GoogleApiClient already connected or is unavailable");
        }
    }

    public void disconnect() {
        if (servicesConnected() && googleApiClient.isConnected()) {
            Log.d(ActivityUtils.APPTAG, "GoogleApiClient disconnection kicked");
            if (mActivityRecognitionPendingIntent != null && googleApiClient != null) {
                ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(googleApiClient,
                        mActivityRecognitionPendingIntent);
            }
            googleApiClient.disconnect();
        } else {
            Log.d(ActivityUtils.APPTAG, "GoogleApiClient already disconnected or is unavailable");
        }
    }
}

Service Class:

public class ActivityTrackerService extends IntentService {

    private SharedPreferences mPrefs;

    public ActivityTrackerService() {
        super("ActivityTrackerService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        mPrefs = getApplicationContext().getSharedPreferences(ActivityUtils.SHARED_PREFERENCES, Context.MODE_PRIVATE);
        if (ActivityRecognitionResult.hasResult(intent)) {

            ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
            DetectedActivity mostProbableActivity = result.getMostProbableActivity();
            int confidence = mostProbableActivity.getConfidence();
            int activityType = mostProbableActivity.getType();
            String activityName = ActivityUtils.getNameFromType(activityType);

            Log.d(ActivityUtils.APPTAG, "Activity Detected:" + activityName);

            Intent regularActivityUpdateIntent = new Intent(ActivityUtils.REGULAR_ACTIVITY_UPDATE_INTENT);
            regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_NAME, activityName);
            regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_TYPE, activityType);

            getApplicationContext().sendBroadcast(regularActivityUpdateIntent);

            if (!mPrefs.contains(ActivityUtils.KEY_PREVIOUS_ACTIVITY_TYPE)) {
                Editor editor = mPrefs.edit();

                editor.putInt(ActivityUtils.KEY_PREVIOUS_ACTIVITY_TYPE, activityType);
                editor.putString(ActivityUtils.KEY_PREVIOUS_ACTIVITY_NAME, activityName);

                editor.commit();

                Intent newActivityUpdateIntent = new Intent(ActivityUtils.NEW_ACTIVITY_UPDATE_INTENT);
                regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_NAME, activityName);
                regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_TYPE, activityType);
                getApplicationContext().sendBroadcast(newActivityUpdateIntent);

            } else if (isMoving(activityType) && activityChanged(activityType) && (confidence >= 50)) {
                sendNotification();
            }
        }
    }

    private void sendNotification() {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
        builder.setContentTitle("Attention").setContentText("Click to turn on GPS, or swipe to ignore")
                .setSmallIcon(R.drawable.ic_notification).setContentIntent(getContentIntent());
        NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notifyManager.notify(0, builder.build());
    }

    private PendingIntent getContentIntent() {
        Intent gpsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        return PendingIntent.getActivity(getApplicationContext(), 0, gpsIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    private boolean activityChanged(int currentType) {
        int previousType = mPrefs.getInt(ActivityUtils.KEY_PREVIOUS_ACTIVITY_TYPE, DetectedActivity.UNKNOWN);
        if (previousType != currentType) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isMoving(int type) {
        switch (type) {
        case DetectedActivity.STILL:
        case DetectedActivity.TILTING:
        case DetectedActivity.UNKNOWN:
            return false;
        default:
            return true;
        }
    }
}

The specific android manifest entries are as follows :

<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />



<service android:name=".ActivityTrackerService" >
        </service>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

Has anybody tried using the com.google.android.gms.common.api.GoogleApiClient to request for ActivityUpdates using ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates or Is there some othe rway to use GoogleApiClient to request activity updates ??

2

There are 2 answers

0
prbylnd On

you should write your project's gradle (app)

 dependencies{
 compile 'com.google.firebase:firebase-appindexing:11.8.0'
 ....
 }

then add libraries and import.

0
Paamand On

I had the same problem, and even with explicit intent the onHandleIntent() would not be called.

I found that onStartCommand was called however, and could get around it by setting and checking the intent action.

It is not an explanation or solutions per se, but at least a workaound ;)