Android的ActivityRecognition没有调用onHandleIntent方法

5

我创建了一段代码来获取用户的活动信息,以查看他是在步行、驾车还是静止不动,但它没有起作用,onHandleIntent从未被调用。它正在连接到GoogleApiClient

这是我的代码:

活动布局

<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";
}
}

和清单

<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>

大家好,请帮忙,谷歌文档对于活动识别没什么用处。


你尝试过使用广播PendingIntent而不是服务PendingIntent吗? - Muzikant
3
这里的问题是什么?你说“onHandleIntent从未被调用”,但在你的评论中又说“它在我的Sony手机上可以工作,但准确性不高,只有80%的置信度,它一直提供错误的活动”,所以显然onHandleIntent被调用了? - Emanuel Moecklin
我的活动识别代码与你的非常相似,运行良好。但是当然不能期望活动识别百分之百准确,这很大程度上取决于设备所拥有的传感器。 - Emanuel Moecklin
@EmanuelMoecklin 在我的设备上没有调用onHandleIndent,但在我另一部运行较低版本的安卓手机上可以正常工作。正如你所说,可能是传感器出了问题。顺便说一下,这个设备是红米Note,目前无法正常工作。 - Saqueib
是的,看起来更像是传感器问题,代码在我看来没问题。 - Emanuel Moecklin
显示剩余2条评论
2个回答

4
也许您缺少了

标签。
<uses-permission android:name="android.permission.INTERNET" />

添加了后,问题依旧。两台设备都不能用。只有我的第二个设备没有网络权限也可以用。我尝试了添加 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 并更新 Google Play 服务,但仍然不行。 - Saqueib

2

请确保在执行以下步骤之前已连接到互联网。否则,可能无法正常运行。第一次连接Google Play服务时必须连接到互联网。


在我的4.2.2安卓手机上无法运行,但在我另一部运行4.0的索尼手机上可以运行。 - Saqueib

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接