向intent添加额外内容时,ActivityRecognitionResult.hasResult(intent)为false

时间:2015-01-03 17:18:10

标签: android android-intent google-play-services intentservice

我目前正致力于添加Google API活动识别。

我成功地使用待处理的意图报告了活动,如示例所示:http://developer.android.com/training/location/activity-recognition.html

现在,我想要一个来自IntentService的回调(由挂起的intent触发)。为此,我尝试了在Using ResultReceiver in Android

找到的解决方案
Intent intent = new Intent(ctx, ActivityRecognitionIntentService.class);
intent.putExtra(ActivityRecognitionIntentService.REQUEST_RECEIVER_EXTRA, new ResultReceiver(null) {
    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        switch (resultCode) {
            case ActivityRecognitionIntentService.RESULT_ID_WITH_ACTIVITYRESULT:

                ActivityRecognitionResult result = resultData.getParcelable(ActivityRecognitionIntentService.RESULT_BUNDLE_ACTIVITYRESULT);
                DetectedActivity mostProbableActivity = result.getMostProbableActivity();

                observer.onNext(mostProbableActivity);

                // Get the confidence percentage for the most probable activity
                int confidence = mostProbableActivity.getConfidence();

                // Get the type of activity
                int activityType = mostProbableActivity.getType();

                Log.d(TAG, getNameFromType(activityType) + " confidence: " + confidence + " isMoving: " + isMoving(activityType));
                break;
            case ActivityRecognitionIntentService.RESULT_ID_NO_ACTIVITYRESULT:
                Log.e(TAG, "Nonfatal: no activity result");
                break;
            default:
                Log.e(TAG, "Unexpected resultCode: " + resultCode);
        }
    }
}); 

遗憾的是,ActivityRecognitionResult.hasResult(intent)始终返回false。

/**
 * Called when a new activity detection update is available.
 */
@Override
protected void onHandleIntent(Intent intent) {

    // outputs "onHandleIntent false"
    Log.d(TAG, "onHandleIntent " + ActivityRecognitionResult.hasResult(intent));

}

进一步测试表明,传递给意图的任何额外内容都会导致同样的问题,例如:

Intent intent = new Intent(ctx, ActivityRecognitionIntentService.class);
intent.putExtra("TEST", "TESTING");
PendingIntent pendingIntent = PendingIntent.getService(ctx, 0, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);

ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(apiClient, 0, pendingIntent);

再次使ActivityRecognitionResult.hasResult(intent)返回false。删除“TEST”extra,会按预期显示Activity结果。

最后我的问题是:

  • 为什么在意图中添加额外功能会使意图无法用于活动识别
  • 是否可以通过其他方式创建回调。 注意:这是出于图书馆项目的目的,所以不能使用EventBus,因为我没有活动/片段来接收发布的事件。

1 个答案:

答案 0 :(得分:0)

我在IntentService中找到了一个使用LocalBroadcastReceiver的解决方案,转发结果。

可以在https://github.com/mcharmas/Android-ReactiveLocation

中找到实施方案