5

I have put together this piece of code to get the users activity, to see is he walking or driving or still, but its not working, onHandleIntent never called. it is connecting to GoogleApiClient.

Here is my code

Activity Layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView android:text="@string/hello_world" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/msg" />

MainActivity

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.ActivityRecognition;

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

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

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

    //get the textview
    textView = (TextView) findViewById(R.id.msg);

    //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 gPlay
        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) {
            String v =  "Activity :" +
                    intent.getStringExtra("act") + " " +
                    "Confidence : " + intent.getExtras().getInt("confidence") + "n";

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

    IntentFilter filter = new IntentFilter();
    filter.addAction("SAVVY");
    registerReceiver(receiver, filter);
}

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

@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("Saquib", "connected to ActRecog " + "PI " +mActivityRecongPendingIntent.toString() );
    ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGApiClient, 0, mActivityRecongPendingIntent);
}

@Override
public void onConnectionSuspended(int i) {
    Log.d("Saquib", "suspended to ActRecog");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.d("Saquib", "Not connected to ActRecog");
}

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mGApiClient.disconnect();

        unregisterReceiver(receiver);
     }
   }

ActivityRecognitionIntentService

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

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

/**
 * Created by tutsberry on 17/03/15.
 */
public class ActivityRecognitionIntentService extends IntentService {

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

@Override
protected void onHandleIntent(Intent intent) {

    if(ActivityRecognitionResult.hasResult(intent)) {
        ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
        DetectedActivity detectedActivity = result.getMostProbableActivity();

        int confidence = detectedActivity.getConfidence();
        String mostProbableName = getActivityName(detectedActivity.getType());

        Intent i = new Intent("SAVVY");
        i.putExtra("act", mostProbableName);
        i.putExtra("confidence", confidence);

        Log.d("Saquib", "mostProbableName " + mostProbableName);
        Log.d("Saquib", "Confidence : " + confidence);

        //Send Broadcast
        this.sendBroadcast(i);

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

private String getActivityName(int type) {
    switch (type)
    {
        case DetectedActivity.IN_VEHICLE:
            return "in_vehicle";
        case DetectedActivity.ON_BICYCLE:
            return "on_bicycle";
        case DetectedActivity.WALKING:
            return "walking";
        case DetectedActivity.STILL:
            return "still";
        case DetectedActivity.TILTING:
            return "tilting";
        case DetectedActivity.UNKNOWN:
            return "unknown";
        case DetectedActivity.RUNNING:
            return "running";

    }
    return "n/a";
}
}

and manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutsberry.moveyours" >

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".ActivityRecognitionIntentService">

</service>
    </application>

</manifest>

Guys please help, google doc is no use for ActivityRecognition

Saqueib
  • 3,484
  • 3
  • 33
  • 56
  • Have you tried using a Broadcast pending intent instead of a Service pending intent? – Muzikant Mar 24 '15 at 15:06
  • You may try to use a request code other than 0 when creating the pending intent – Muzikant Mar 24 '15 at 15:06
  • I have tried doing that, it works on my Sony phone but nothing is accurate it keep giving wrong activities with 80% confidence. I think ActivityRecognition not reliable API thats why there are not good documentation on official docs. – Saqueib Mar 25 '15 at 04:06
  • 3
    What's the problem here? You're saying "onHandleIntent never called" but then you say in your comment "it works on my Sony phone but nothing is accurate it keep giving wrong activities with 80% confidence", so obviously onHandleIntent is called? – Emanuel Moecklin Mar 27 '15 at 02:38
  • My activity recognition code that looks much like yours works great but of course you can't expect the activity recognition to be 100% accurate. It depends a lot on what sensors your device has. – Emanuel Moecklin Mar 27 '15 at 02:45
  • @EmanuelMoecklin `onHandleIndent` was not getting called on my device, but its working on my other phone which is running lower version of android. as you said maybe something wrong with sensor. by the way device is [redmi note](http://www.gsmarena.com/xiaomi_redmi_note-6217.php) which is not working – Saqueib Mar 27 '15 at 03:13
  • Yeah looks more like a sensor issue, the code looks ok to me. – Emanuel Moecklin Mar 27 '15 at 14:25

2 Answers2

4

Maybe you are missing the

<uses-permission android:name="android.permission.INTERNET" />
Teo Inke
  • 5,928
  • 4
  • 38
  • 37
  • Added it, same problem. Its not working on both device. Its working on my second device without net permission. I have tried adding `` & updated google play service but no luck. – Saqueib Mar 31 '15 at 03:21
2

Make sure that you are connected to the internet beforehand. I think otherwise it will not work. The first time you connect to google play services you must be connected to the internet.

rabz100
  • 751
  • 1
  • 5
  • 13
  • doesn't work on my 4.2.2 android phone. but it works on my other sony phone which is running 4.0 – Saqueib Mar 25 '15 at 04:07