使用服务来请求活动更新——如何处理intent



有一个我正在重构的应用程序,使用服务而不是IntentService来处理Activity更新。当前使用requestActivityUpdates来使用一个方法来收集意图并将其发送到基于IntentService的类进行处理。

ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(
            mGoogleApiClient,
            DETECTION_INTERVAL_IN_MILLISECONDS,
            getActivityDetectionPendingIntent()
    ).setResultCallback(this);

private PendingIntent getActivityDetectionPendingIntent() {
    Intent intent = new Intent(getApplicationContext(), ActivityIntentService.class);
    return PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
有没有一种方法可以直接在我的服务类中处理pendingIntent而不把它传递给IntentService?

PendingIntent.getService()适用于IntentService和regular Service。只是替换

Intent intent = new Intent(getApplicationContext(), ActivityIntentService.class);

Intent intent = new Intent(getApplicationContext(), ActivityService.class);

(或者你的服务的名字是什么)。

请参阅PendingIntent.getService()的文档:

检索将启动服务的PendingIntent, ,如调用Context.startService()。给服务的start参数将来自Intent的extras。

IntentService.onHandleIntent(Intent intent)接收到的意图将在常规服务中被onStartCommand(Intent intent, int flags, int startId)接收。

最新更新