0

Guys have anybody got the ActivityrecognitionAPI to work in Android. It does not give any updates. Have tried the API documents, Plenty of Examples. OnHandleIntent does not fire.

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

import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;

public class ActivityRecognitionIntentService extends IntentService{

    ActivityRecognitionResult result;
    Intent i;
    DetectedActivity mpactivity;

    public ActivityRecognitionIntentService() {
        super("ActivityRecognitionIntentService");
        i = new Intent("ACTIVITY_RECOGNITION_DATA");
        }

    private String getTypes(int type) {
        if(type == DetectedActivity.UNKNOWN)
            return "Unknown";
        else if(type == DetectedActivity.IN_VEHICLE)
            return "In Vehicle";
        else if(type == DetectedActivity.ON_BICYCLE)
            return "On Bicycle";
        else if(type == DetectedActivity.RUNNING)
            return "Running";
        else if(type == DetectedActivity.ON_FOOT)
            return "On Foot";
        else if(type == DetectedActivity.STILL)
            return "Still";
        else if(type == DetectedActivity.TILTING)
            return "Tilting";
        else if(type == DetectedActivity.WALKING)
            return "Walking";
        else
            return "";
        }

    @Override
    protected void onHandleIntent(Intent intent) {
         if (intent.getAction() == "ActivityRecognitionIntentService") {
            if(ActivityRecognitionResult.hasResult(intent)){    
                result = ActivityRecognitionResult.extractResult(intent);
                mpactivity = result.getMostProbableActivity();
                i.putExtra("Activity", getTypes(mpactivity.getType()));
                i.putExtra("Confidence", mpactivity.getConfidence());
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
                }
            }
        }
    }       

The Main activity is as

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

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.TextView;
import android.widget.Toast;

public class Actrecogex extends Activity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener,  GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

    TextView textView1;
    GoogleApiClient mGoogleActclient;
    PendingIntent mActivityRecognitionPendingIntent;
    Intent i;
    LocalBroadcastManager mBroadcastManager;

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

        textView1 = new TextView(this);
        textView1 =(TextView)findViewById(R.id.textView1);   

        i = new Intent(this, ActivityRecognitionIntentService.class);  
        mBroadcastManager = LocalBroadcastManager.getInstance(this);

        mGoogleActclient = new GoogleApiClient.Builder(this)
        .addApi(ActivityRecognition.API)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .build();

        mGoogleActclient.connect();
        }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        textView1.setText("Failed Connection" + arg0); 
        }

    @Override
    public void onConnected(Bundle arg0) {
        i.setAction("ActivityRecognitionIntentService");
        mActivityRecognitionPendingIntent = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleActclient, 0, mActivityRecognitionPendingIntent);  
        }

    @Override
    public void onConnectionSuspended(int arg0) {
        textView1.setText("Failed Suspended" + arg0);
        }

    private BroadcastReceiver receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(getApplicationContext(), "Service", Toast.LENGTH_SHORT).show();
            String v =  "Activity :" + intent.getStringExtra("Activity") + " " + "Confidence : " + intent.getExtras().getInt("Confidence") + "\n";
            v += textView1.getText() ;
            textView1.setText(v);
            }
        };

    @Override
    public void onDisconnected() {
        textView1.setText("Disconnected" ); 
        }
    }

Manifest

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="21" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>

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

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

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

Does the code really work, Or I am wasting time. Seriously want to go back Activityrecogntionclient. Testing the App on Gingerbread and Kitkat. Both does not budge

Ravi
  • 13
  • 1
  • 8
  • Now Found out where the problem is coming from ActivityRecognitionResult is the culprit. Now able to get a error from this. So the onHandleIntent is kicking but throwing error. – Ravi Jan 21 '15 at 06:38
  • I am getting error message for Forceclose periodically in gingerbread, but not in Kitkat. The periodic error message i persume is activity feedback from service. – Ravi Jan 22 '15 at 04:36

2 Answers2

0

It seems your definition of the service in the Manifest is wrong: it is missing a leading period. It should be

<service android:name=".ActivityRecognitionIntentService" android:exported="false"></service>

Your onHandleIntent() uses

intent.getAction() == "ActivityRecognitionIntentService"

But you cannot compare strings with == so your if statement never returns true. Instead, you must use equals() or the equivalent TextUtils.equals() (which also handles cases where either argument is null):

"ActivityRecognitionIntentService".equals(intent.getAction())
// OR
TextUtils.equals(intent.getAction(), "ActivityRecognitionIntentService")
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • Thankyou for Pointingout that. The Problem is OnHandleIntent never gets called. Changed to equals(), same result – Ravi Jan 21 '15 at 05:24
  • Updated my answer: looks like your manifest service definition needs to be corrected as well. – ianhanniballake Jan 21 '15 at 05:28
  • Added leading Period .ActivityRecognitionIntentService No Difference, same issue – Ravi Jan 21 '15 at 06:37
  • What happens when you remove the `exported="false"` attribute? – ianhanniballake Jan 21 '15 at 06:45
  • Exported = false is for safety. NO change if I remove. I am getting periodic error message, Which I presume to be activity updates. The error stops when I remove ActivityRecognitionResult. So the error comes from this only. – Ravi Jan 21 '15 at 06:49
  • Oh, so your service is being launched. What do you mean by a 'periodic error message'? Can you append the error message to your question? If it is a `NullPointerException`, what is null? – ianhanniballake Jan 21 '15 at 06:56
  • The Application actrecogex is stopped unexpectedly, please try again later. Force close. Now I press forceclose and sometime (around 10 secs) later same error comes back , without opening the application. – Ravi Jan 21 '15 at 07:00
  • Look at logcat for the actual exception and include that. – ianhanniballake Jan 21 '15 at 07:03
  • I am checking on the phone. I am not able to use the emulator to check because of the latest playsservices library I am using. Emulators are all on old versions – Ravi Jan 21 '15 at 07:06
0
 if (intent.getAction() == "ActivityRecognitionIntentService") {
}

Was giving null value. So the periodic Error Message.

The Main Problem was the Broadcastreceiver was not receiving anything. So needed to have separate class for Broadcastreceiver. It is Working now.

<receiver android:name="ActBreceiver" android:exported="false">
            <intent-filter>
                <action android:name="ACTIVITY_RECOGNITION_DATA"/>
            </intent-filter>
        </receiver>
Ravi
  • 13
  • 1
  • 8