我想使用Google Play服务提供的Activity Recognition API,但我这样做有问题。 首先,我无法找到并更新适合我的指南,所以我做了一些类似于github上的“官方”示例的女巫正在我的手机上工作。
到目前为止,我所做的是:
1)在清单
中添加<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
2)添加了内部gradle(因为我在这个版本中使用了其他游戏服务,所以它是10.0.1)
compile 'com.google.android.gms:play-services-location:10.0.1'
3)我创建了一个新类
public class ActivityRecognizationIntentService extends IntentService {
public ActivityRecognizationIntentService() {
super("ActivityRecognizationIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
Intent localIntent = new Intent(AddictionFour.BROADCAST_ACTION);
// Get the list of the probable activities associated with the current state of the
// device. Each activity is associated with a confidence level, which is an int between
// 0 and 100.
ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();
// Broadcast the list of detected activities.
localIntent.putExtra(AddictionFour.ACTIVITY_EXTRA, detectedActivities);
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}}
4)在我想要使用API的GameActivity类中,我对此进行了更改(注意:我只发布相关的代码)
public void onCreate(Bundle savedInstanceState) {
// connection to Google Play Games
mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.getContextOfApplication())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(ActivityRecognition.API)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
// add other APIs and scopes here as needed
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle arg0) {
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, 0, getActivityDetectionPendingIntent());
}
@Override
public void onResume() {
LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, new IntentFilter(AddictionFour.BROADCAST_ACTION));
super.onResume();
}
private PendingIntent getActivityDetectionPendingIntent() {
Intent intent = new Intent(this, ActivityRecognizationIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
// requestActivityUpdates() and removeActivityUpdates().
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public class ActivityDetectionBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//not relevant code for now (read below)
}
}
基本上我在做github上的例子正在做同样的事情,app没有任何错误并且不会崩溃但是onHandleIntent永远不会被调用。我错过了什么?
PS:除了onReceive of ActivityDetectionBroadcastReceiver之外,执行第4点内的所有代码。