
Activity Recognition in Android Studio
Download Demo of this app from play store
Practical Implementation in Android Studio
1. Add this permission in your manifest file.
2. Add this dependency in gradle file and sync your project.
3. Create class for background services
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.location.ActivityRecognitionClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
public class BackgroundDetectedActivitiesService extends Service {
private static final String TAG = BackgroundDetectedActivitiesService.class.getSimpleName();
private Intent mIntentService;
private PendingIntent mPendingIntent;
private ActivityRecognitionClient mActivityRecognitionClient;
IBinder mBinder = new BackgroundDetectedActivitiesService.LocalBinder();
public class LocalBinder extends Binder {
public BackgroundDetectedActivitiesService getServerInstance() {
return BackgroundDetectedActivitiesService.this;
}
}
public BackgroundDetectedActivitiesService() {
}
@Override
public void onCreate() {
super.onCreate();
mActivityRecognitionClient = new ActivityRecognitionClient(this);
mIntentService = new Intent(this, DetectedActivitiesIntentService.class);
mPendingIntent = PendingIntent.getService(this, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
requestActivityUpdatesButtonHandler();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
public void requestActivityUpdatesButtonHandler() {
Task<Void> task = mActivityRecognitionClient.requestActivityUpdates(
Constants.DETECTION_INTERVAL_IN_MILLISECONDS,
mPendingIntent);
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void result) {
Toast.makeText(getApplicationContext(),
“Successfully requested activity updates”,
Toast.LENGTH_SHORT)
.show();
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(),
“Requesting activity updates failed to start”,
Toast.LENGTH_SHORT)
.show();
}
});
}
public void removeActivityUpdatesButtonHandler() {
Task<Void> task = mActivityRecognitionClient.removeActivityUpdates(
mPendingIntent);
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void result) {
Toast.makeText(getApplicationContext(),
“Removed activity updates successfully!”,
Toast.LENGTH_SHORT)
.show();
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), “Failed to remove activity updates!”,
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
removeActivityUpdatesButtonHandler();
}
}
public class Constants {
public static final String BROADCAST_DETECTED_ACTIVITY = “activity_intent”;
static final long DETECTION_INTERVAL_IN_MILLISECONDS = 30 * 1000;
public static final int CONFIDENCE = 70;
}
5. Create class for broadcasting user activity
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;
import java.util.ArrayList;
public class DetectedActivitiesIntentService extends IntentService {
protected static final String TAG = DetectedActivitiesIntentService.class.getSimpleName();
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.e(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);
}
}
6. Create main activity, this is main class. All control are given to this activity and from you can initialize background services and use user activity broadcasting.
Thats it 🙂 Any question and issue, Feel free to ask anything . Thank you