co.madteam.activityrecognitionexample.services.ActivityRecognitionIntentService.java Source code

Java tutorial

Introduction

Here is the source code for co.madteam.activityrecognitionexample.services.ActivityRecognitionIntentService.java

Source

/**
 * Created by James Coggan on 12/09/15.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package co.madteam.activityrecognitionexample.services;

import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;

import java.util.ArrayList;

import co.madteam.activityrecognitionexample.R;
import co.madteam.activityrecognitionexample.utils.Constants;

public class ActivityRecognitionIntentService extends IntentService {

    protected static final String TAG = ActivityRecognitionIntentService.class.getName();

    public ActivityRecognitionIntentService() {
        super(TAG);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(Intent intent) {

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

        // Get the list of the probable activities
        ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();

        String type = "";
        float confidence = 0;

        // Select the most confidence type
        for (DetectedActivity da : detectedActivities) {
            if (da.getConfidence() > confidence) {
                confidence = da.getConfidence();
                type = Constants.getActivityString(getApplicationContext(), da.getType());
            }
        }

        // Add to the notification the current most confidence activity
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher).setContentTitle("Current activity: " + type).setOngoing(true)
                .setContentText("Confidence: " + String.valueOf(confidence) + "%");
        int mNotificationId = Constants.NOTIFICATION_ID;
        NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotifyMgr.notify(mNotificationId, mBuilder.build());
    }
}