运行在不同进程上的服务的问题

时间:2015-12-23 13:52:28

标签: java android android-studio service

我正在尝试在新流程中启动服务,因此当应用关闭时它会保持活跃状态​​。

我有一个名为MainScreen的活动,以及一个名为BackgroundSensorService的IntentService。 以下是该服务的明确定义:

<service
    android:name=".services.BackgroundSensorService"
    android:exported="false"
    android:process=":backgroundSens" >
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
    </intent-filter>
</service>

以下是运行该服务的代码段:

Intent intent = new Intent(MainScreen.this, BackgroundSensorService.class);
intent.setAction("android.intent.action.SEND");
startService(intent);

当我尝试在HandleIntent方法中设置断点时,我从未到达它。 我试图在onCreate中设置一个断点,但我也没有达到那个。 奇怪的是,如果我从我的服务中删除'process'标签,一切都很完美。

我对这个问题感到不满......

注意:我正在尝试模仿whatsapp示例服务的行为,即使在应用程序关闭时也会跟踪传入的消息。该服务应该在后台运行,并且没有GUI。

2 个答案:

答案 0 :(得分:0)

我在应用程序关闭后运行了一个未绑定服务的工作示例: https://github.com/kweaver00/Android-Samples/tree/master/Location/AlwaysRunningLocation

应用程序代码中的Android Manifest代码:

<service
    android:name=".YourService"
    android:enabled="true"
    android:exported="true"
    android:description="@string/my_service_desc"
    android:label="@string/my_infinite_service">
    <intent-filter>
        <action android:name="com.weaverprojects.alwaysrunninglocation.LONGRUNSERVICE" />
        </intent-filter>
    </service>

开始服务:

Intent servIntent = new Intent(v.getContext(), YourService.class);
startService(servIntent);

此处的示例,每次更改位置时调用(使用模拟位置)并且应用程序未打开

答案 1 :(得分:0)

根据我使用Android服务的经验,一旦你杀了应用程序,服务也会被杀死。但是,您可以强制它重新启动。

在您的服务中,您应该使用onStartCommand方法返回您要使用的服务类型。 主要选项是:

START_NOT_STICKY:告诉操作系统在关闭服务时不要重新创建服务。

START_STICKY:告诉操作系统重启服务如果关闭(听起来你想要这个)。

@Override
 public int onStartCommand(Intent intent, int flags, int startId)
{
   return START_STICKY; //restarts service when closed
}

然而,当重新启动服务时,将重置传递给它的所有参数。如果像我一样,你需要跟踪某些数据,你可以使用SharedPreferences来保存和读取值(可能有更好的方法,但这对我有用)。