简体   繁体   English

Android活动识别不适用于Nexus 5

[英]Android Activity Recognition not working with Nexus 5

I had a code working that was using Google's Activity Recognition Updates. 我有一个使用Google的活动识别更新的代码。 Now all of a sudden these seem to send updates either several times per second or never although requested every 20 seconds. 现在突然之间,这些请求似乎每秒钟发送几次更新,或者每20秒发送一次,但从未发送过。 I haven't changed the code and checked earlier versions but got the same problem. 我没有更改代码并检查了早期版本,但遇到了同样的问题。

I built a minimal example from the tutorial but also get no activity updates with my Nexus 5 device. 我从本教程中构建了一个最小的示例,但是我的Nexus 5设备也没有任何活动更新。 With my HTC Desire (MildWild 5.0 based on Android 2.3.7) it works perfectly fine. 使用我的HTC Desire(基于Android 2.3.7的MildWild 5.0),它可以完美运行。 I suspected Google Play Services but both phones have version 4.2.43 installed 我怀疑有Google Play服务,但两部手机均安装了4.2.43版

MainActivity: 主要活动:

package com.example.testactivities;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.ActivityRecognitionClient;

public class MainActivity extends FragmentActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
    // Constants that define the activity detection interval
    public static final int MILLISECONDS_PER_SECOND = 1000;
    public static final int DETECTION_INTERVAL_SECONDS = 1;
    public static final int DETECTION_INTERVAL_MILLISECONDS = 
            MILLISECONDS_PER_SECOND * DETECTION_INTERVAL_SECONDS;
    /*
     * Store the PendingIntent used to send activity recognition events
     * back to the app
     */
    private PendingIntent mActivityRecognitionPendingIntent;
    // Store the current activity recognition client
    private ActivityRecognitionClient mActivityRecognitionClient;
    // Flag that indicates if a request is underway.
    private boolean mInProgress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /*
         * Instantiate a new activity recognition client. Since the
         * parent Activity implements the connection listener and
         * connection failure listener, the constructor uses "this"
         * to specify the values of those parameters.
         */
        mActivityRecognitionClient =
                new ActivityRecognitionClient(this, this, this);
        /*
         * Create the PendingIntent that Location Services uses
         * to send activity recognition updates back to this app.
         */
        Intent intent = new Intent(
                this.getApplicationContext(), ActivityRecognitionIntentService.class);
        /*
         * Return a PendingIntent that starts the IntentService.
         */
        mActivityRecognitionPendingIntent =
                PendingIntent.getService(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        // Start with the request flag set to false
        mInProgress = false;
        this.startUpdates();
    }

    /**
     * Request activity recognition updates based on the current
     * detection interval.
     *
     */
     public void startUpdates() {
        // If a request is not already underway
        if (!mInProgress) {
            // Indicate that a request is in progress
            mInProgress = true;
            // Request a connection to Location Services
            mActivityRecognitionClient.connect();
        //
        } else {
            /*
             * A request is already underway. You can handle
             * this situation by disconnecting the client,
             * re-setting the flag, and then re-trying the
             * request.
             */
        }
    }

     /*
      * Called by Location Services once the location client is connected.
      *
      * Continue by requesting activity updates.
      */
     @Override
     public void onConnected(Bundle dataBundle) {
         Log.v("EXAMPLE","connected");
         /*
          * Request activity recognition updates using the preset
          * detection interval and PendingIntent. This call is
          * synchronous.
          */
         mActivityRecognitionClient.requestActivityUpdates(
                 DETECTION_INTERVAL_MILLISECONDS,
                 mActivityRecognitionPendingIntent);
         /*
          * Since the preceding call is synchronous, turn off the
          * in progress flag and disconnect the client
          */
         mInProgress = false;
         mActivityRecognitionClient.disconnect();
     }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        Log.v("EXAMPLE","Connection failed");

    }

    @Override
    public void onDisconnected() {
        Log.v("EXAMPLE","Disconnected");
    }

}

Manifest: 表现:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testactivities"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="19" />
    <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" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <activity
            android:name="com.example.testactivities.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="com.example.testactivities.ActivityRecognitionIntentService"/>
    </application>

</manifest>

RecognitionIntentService: RecognitionIntentService:

package com.example.testactivities;

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

public class ActivityRecognitionIntentService extends IntentService {

    public ActivityRecognitionIntentService() {
        super("ActivityRecognitionIntent");
        Log.v("EXAMPLE","constructor");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.v("EXAMPLE","new activity update");
    }

}

UPDATE: I believe canopi identified the correct problem. 更新:我相信canopi确定了正确的问题。 When the device is still with high confidence, it doesn't fire recognition intents at all. 当设备仍然充满信心时,它根本不会触发识别意图。 This was definitely different a year ago (on other devices). 绝对与一年前(在其他设备上)不同。 To detect if the device is still I log the last incoming activity with its timestamp and check periodically for that. 为了检测设备是否仍处于静止状态,我记录了上次传入的活动及其时间戳,并定期进行检查。 An old timestamp signals that the device has been still for that time. 旧的时间戳记表明该设备在该时间之前一直处于静止状态。

I would suggest you increase the detection interval, it takes at least 6 to 7 seconds for the sensors to detect a change in your activity. 我建议您增加检测间隔,传感器至少需要6到7秒才能检测到您的活动变化。 Also, I have observed that ActivityRecognition stops firing intents if the device is Still for a certain period of time. 另外,我观察到,如果设备在一定时间内保持静止,ActivityRecognition会停止激发意图。 They are immediately triggered when the device is in motion again. 当设备再次运动时,将立即触发它们。

Perhaps you have the location services disabled on your Nexus 5 device... 也许您已在Nexus 5设备上禁用了定位服务...
Activity Recognition needs the location services active/enabled. 活动识别需要激活/启用位置服务。

As suggested by canopi, increase the detection 'time', in which 0 will give you the fastest result. 如canopi所建议,增加检测“时间”,其中0将为您提供最快的结果。

I had encountered the same problem and instead of adding the build() part on onCreate directly, I added the method below and called it on onCreate(). 我遇到了同样的问题,我没有在onCreate上直接添加build()部分,而是在下面添加了方法并在onCreate()上调用了它。 Try to trace the code from this google sample . 尝试从此google示例中跟踪代码。 I got the code stripped down from there. 我从那里剥离了代码。

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(ActivityRecognition.API)
            .build();
}

Also add buildGoogleApiClient() to your onCreate method. 还要将buildGoogleApiClient()添加到您的onCreate方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM