2015-12-23 17 views
0

我试图在新进程中启动一个服务,所以它会在应用程序关闭时保持活动状态。在另一个进程上运行的服务的问题

我有一个名为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。

+0

如果进程名称以小写字符开头,则该服务将在该名称的全局进程中运行,**前提是它有权这样做**。这允许不同应用程序中的组件共享一个进程,从而减少资源使用。 – Skynet

+0

感谢您的快速回复,@Skynet。我试过了,但它不能解决我的问题。不过,很高兴知道。谢谢! –

+0

意图服务意味着在后台运行 - 即使您的应用程序不在堆栈中 – Skynet

回答

0

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

Android清单代码应用标签:

<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); 

这里的例子,每当位置发生变化(使用模拟位置)并且应用程序未打开时调用

+0

感谢您的答复,@Keith。我真的不明白你是如何得到服务保持熬夜的。您没有指定它将运行在不同的进程上。 如果您通过流程管理器杀死您的应用程序,您的服务是否仍会运行?因为这是我的主要问题。如果是这样,请详细说明清单中的哪些标签为您提供了此行为 –

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来保存和读取值(可能有更好的方法,但这对我有用)。

+0

感谢您的信息,但这不是我正在寻找的。如果我在不同的进程上运行该服务,则应用程序关闭时不应关闭该服务,因为这只会杀死主进程 –

相关问题