0

I am Trying to start a service if the DetectedActivity returned from Activity recognition returned is IN_VEHICLE. I have downloaded a code sample from : http://tutsberry.com/activity-recognition-implementation-on-android/

But i'm not sure where to put code in to start my service. I am Trying to the check the user activity in the background using the Activity Recognition and then start a service all in the background.

ActivityRecognitionIntentService Class

public class ActivityRecognitionIntentService extends IntentService {


//LogCat
private static final String TAG = ActivityRecognitionIntentService.class.getSimpleName();

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

protected void onHandleIntent(Intent intent) {
    if (ActivityRecognitionResult.hasResult(intent)) {
        //Extract the result from the Response
        ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
        DetectedActivity detectedActivity = result.getMostProbableActivity();

        //Get the Confidence and Name of Activity
        int confidence = detectedActivity.getConfidence();
        String mostProbableName = getActivityName(detectedActivity.getType());


        //Fire the intent with activity name & confidence
        Intent i = new Intent("ImActive");
        i.putExtra("activity", mostProbableName);
        i.putExtra("confidence", confidence);

        Log.d(TAG, "Most Probable Name : " + mostProbableName);
        Log.d(TAG, "Confidence : " + confidence);

        //Send Broadcast to be listen in MainActivity
        this.sendBroadcast(i);

    } else {
        Log.d(TAG, "Intent had no data returned");
    }
}

//Get the activity name
private String getActivityName(int type) {
    switch (type) {
        case DetectedActivity.IN_VEHICLE:
            return "In Vehicle";
        case DetectedActivity.ON_BICYCLE:
            return "On Bicycle";
        case DetectedActivity.ON_FOOT:
            return "On Foot";
        case DetectedActivity.WALKING:
            return "Walking";
        case DetectedActivity.STILL:
            return "Still";
        case DetectedActivity.TILTING:
            return "Tilting";
        case DetectedActivity.RUNNING:
            return "Running";
        case DetectedActivity.UNKNOWN:
            return "Unknown";
    }
    return "N/A";
}

}

MainActivity Class

public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{


// LogCat
private static final String TAG = MainActivity.class.getSimpleName();

private Context mContext;
private GoogleApiClient mGApiClient;
private BroadcastReceiver receiver;
private TextView textView;
private TextView tv2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



      textView = (TextView) findViewById(R.id.msg);
    textView.setMovementMethod(new ScrollingMovementMethod());

    tv2 = (TextView) findViewById(R.id.text2);

    //Set the context
    mContext = this;

    //Check Google Play Service Available
    if (isPlayServiceAvailable()) {
        mGApiClient = new GoogleApiClient.Builder(this)
                .addApi(ActivityRecognition.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        //Connect to Google API
        mGApiClient.connect();
    } else {
        Toast.makeText(mContext, "Google Play Service not Available", Toast.LENGTH_LONG).show();
    }

    //Broadcast receiver
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Add current time
            Calendar rightNow = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("h:mm:ss a");
            String strDate = sdf.format(rightNow.getTime());
            ;
            String v = strDate + " " +
                    intent.getStringExtra("activity") + " " +
                    "Confidence : " + intent.getExtras().getInt("confidence") + "\n";

            v = textView.getText() + v;
            textView.setText(v);
        }
    };

    //Filter the Intent and register broadcast receiver
    IntentFilter filter = new IntentFilter();
    filter.addAction("ImActive");
    registerReceiver(receiver, filter);

    //Check for Google play services available on device

}

private boolean isPlayServiceAvailable() {
    return GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext) == ConnectionResult.SUCCESS;
}





@Override
protected void onDestroy() {

    super.onDestroy();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}



@Override
public void onConnected(Bundle bundle) {
    Intent i = new Intent(this, ActivityRecognitionIntentService.class);
    PendingIntent mActivityRecongPendingIntent = PendingIntent
            .getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    Log.d(TAG, "connected to ActivityRecognition");
    ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGApiClient, 0, mActivityRecongPendingIntent);

    //Update the TextView
    textView.setText("Connected to Google Play Services \nWaiting for Active Recognition... \n");

}

@Override
public void onConnectionSuspended(int i) {
    Log.d(TAG, "Suspended to ActivityRecognition");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.d(TAG, "Not connected to ActivityRecognition");

    //Disconnect and detach the receiver
    mGApiClient.disconnect();
    unregisterReceiver(receiver);
}

}

Andrew Irwin
  • 691
  • 12
  • 40
  • 2
    it's very unlikely that anyone will bother to read a tutorial just to help you. Please post the relevent bits of code, what you have tried and what doesn't work in your question. – e4c5 Oct 12 '15 at 14:23
  • Ok sorry , Give me one second while i post up my code – Andrew Irwin Oct 12 '15 at 14:26
  • I looks like all the code is available in github - isn't the code to start the service in this code example? – Kristy Welsh Oct 12 '15 at 14:29
  • Im not sure @kristy Welsh where else you saw this code. The only place i found this code was in the start TutsBerry link i posted. If you have found code that could help please post a link to it here. Thank you. – Andrew Irwin Oct 12 '15 at 14:33
  • I am quite new to android. this is my first app so i am kind of finding it difficult to get things working. – Andrew Irwin Oct 12 '15 at 14:35
  • https://github.com/tutsberry/ImActive – Kristy Welsh Oct 12 '15 at 14:37
  • Yes that is the code I am using but I am not actually using it in my actual app. I created a separate android project and copied the code into to it to see how the Activity Recognition api works. Can you help me though ? I am trying to start a service if the activity detected is In Vehicle. – Andrew Irwin Oct 12 '15 at 14:41

1 Answers1

-1

MainActivity.java

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends Activity {
    IntentFilter filter;
    BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        filter = new IntentFilter();
        mReceiver = new MyReceiver();
        filter.addAction("IN_VEHICLE"); //Name the action what ever you need to.
        filter.addAction("OTHER_ACTION");
        filter.addAction("YET_ANOTHER_ACTION)");
        registerReceiver(mReceiver, filter); //Register the receiver you define with the actions you want.
    }

    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if("IN_VEHICLE_RESPONSE".equals(intent.getAction())){
                //Launch other activities here 
                Intent i = new Intent(getApplicationContext(), InVehicleActivity.class );
                startActivity(i);

            }else if("OTHER_ACTION_RESPONSE".equals(intent.getAction())){
                //Launch desired activity
            }else if("YET_ANOTHER_ACTION_RESPONSE".equals(intent.getAction())){
                //Launch desired activity
            }else{
                //Handle unssuported actions
            }
        }
    }

}

MyIntentService.java

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;

public class MyIntentService extends IntentService {

    Bundle extras;

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

    @Override
    protected void onHandleIntent(Intent intent) {
        extras = intent.getExtras();
        if("IN_VEHICLE".equals(intent.getAction())){
            inVehicle(extras);
            return;
        }
        if("OTHER_ACTION".equals(intent.getAction())){
            //otheraction method
            return;
        }
        if("YET_ANOTHER_ACTION".equals(intent.getAction())){
            //yetanotheraction method
            return;
        }

    }

    private void inVehicle(Bundle extras) {
        //do work
        //do work
        Intent intent = new Intent();
        intent.setAction("IN_VEHICLE_RESPONSE");
        //put all other desired stuff in intent
        getApplicationContext().sendBroadcast(intent);
    }

}

Don't forget to add your receiver to your manifest. I would suggest that you start Activities from Activity not Service layer.

TerNovi
  • 390
  • 5
  • 16
  • Thank you so much for your answer. Ill will try it out asap and get back to you and hopefully it will work for me and i will accept the answer! :) thank you so much i have been trying a for a long time to get this working, but its proving to be difficult as i lack general android knowledge as i am only new . – Andrew Irwin Oct 12 '15 at 15:44
  • Your welcome. Let me know if you have any questions. I tried to make the code as simple as possible for you to understand what you need to do. – TerNovi Oct 12 '15 at 15:48
  • I see at the end of your answer you wrote that you suggest that i should start the service from an activity. My intention is that the user may have their device in their pocket locked and then if the activity recognition detects that the user is In Vehicle that my service will start. Am i right in saying that if i use an activity the app has to be open and the user present. Or can i just use a broadcast receiver like you have, but on its own to detect the activity and start the service . all done in the background – Andrew Irwin Oct 12 '15 at 15:55
  • It's more complicated than that. You have to think about what will trigger those actions? If you start opening activities from the background you have to be careful because certain actions will not make sense. You will have opened the activity from the background but the user will not really see until he starts using his phone? You can open them from the background but it would be better if you used PendingIntents, and you check if the device is in a state that would allow for that activity to open without crashing. – TerNovi Oct 12 '15 at 16:02
  • Im really sorry but how do i link your code into the activity recognition api code? – Andrew Irwin Oct 12 '15 at 16:58