【发布时间】:2014-01-28 18:02:43
【问题描述】:
我有我的应用程序设置,其中(非意图)服务将使用 gps/网络侦听器轮询位置。它工作得很好,因为我负责服务何时结束(即在找到新位置或达到超时时调用 stopSelf() )。但是,我最近读到,intentService 可能更适合长时间运行的任务,因为它不是在 ui 线程上运行,而是在它自己的工作线程上运行。问题是,现在它不允许服务在任何时候运行(我假设这是因为服务中没有任何活动发生,而侦听器等待接收位置,因此服务自行结束)。
当它是非意图服务时,我的 onStartCommand() 方法看起来像:
@Override
protected void onStartCommand(Intent intent) {
grabLocation();
}
由于我已将服务切换为 Intent 服务,因此我取消了此方法(根据文档,它不应该被 intentSerivce 覆盖),现在我的 onHandleIntent 服务如下所示:
@Override
protected void onHandleIntent(Intent intent) {
grabLocation();
}
服务几乎立即结束。服务结束后如何延期?
我使用 startService(Intent) 像其他任何服务一样调用该服务
locationPollingIntent = new Intent(MainActivity.this, LocationService.class);
updateLocationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(locationPollingIntent);
}
});
清单sn-p:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service
android:name="com.rperryng.intellilocation.backgroundServices.LocationService"
android:label="Location Service" />
<receiver android:name="com.rperryng.intellilocation.backgroundServices.AutoStart" />
<activity
android:name="com.rperryng.intellilocation.activities.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>
</application>
【问题讨论】:
-
如何启动 IntentService?您的清单文件看起来如何?
-
我已经添加了你提到的代码 @EarlOfEgo 。如果您想知道服务是否已启动,它是,我有来自整个服务的 Logcat 消息(包括 onCreate、onHandleIntent、grabLocation() 和 onDestroy())它只是没有给我的听众任何时间必须在终止服务之前检索位置更新
标签: android intentservice