2011-10-07 63 views
13

我正在尝试创建一个将在后台处理文件I/O的服务。更新数据的活动将绑定到服务并调用服务的方法来执行I/O。我正在使用Android文档进行指导。Android服务从未出现过 - onStartCommand()未调用

但是,我的服务似乎并不想开始。在我的活动的onCreate()方法,我有:

Intent smsIntent = new Intent(this, SurveyManagerService.class);  
String surveyFilename = getIntent().getStringExtra("surveyFilename"); 
System.out.println(startService(smsIntent)); //testing if it starts 
SurveyManagerServiceConnection connection = new SurveyManagerServiceConnection(); 
sms = connection.getSurveyManagerService(); 

在线路3的logcat输出ComponentInfo对象,所以它会出现该服务被创建;但是,短信为空。此外,SurveyManagerService onStartCommand()方法似乎从来没有被称为:

@Override 
public int onStartCommand(Intent intent, int flags, int startId) 
{ 
    System.out.println("starting service"); 
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); 
    openSurveyFromIntent(intent); 
    return START_REDELIVER_INTENT; 
} 

我从来没有看到任何logcat中“启动服务”输出,也不敬酒出现。

<service android:name=".SurveyManagerService" android:exported="false" android:enabled="true"> 
</service> 

我失去了一些东西很明显:

我的服务我的表现为申报?让我知道我应该提供哪些其他信息来诊断问题。

+0

也许你的服务反复崩溃声明你的服务? – Reno

+0

我该如何去测试它是否在onStartCommand()的第一行之前崩溃?谢谢。我忘了说onCreate()方法也有一个System.out.println测试,它永远不会被调用。 – Spinner

回答

5

在服务真正开始之前,似乎是onCreate()方法has to exit。一旦我删除了getSurveyManagerService()请求,并且一旦有一段时间过去,我收到System.out消息,指示服务正在启动。

不幸的是,这产生了另一个问题:Activity依赖于服务来处理它的数据,所以我需要确定如何使Activity等待服务启动。

编辑:我的解决方案是在我的Activity中创建ServiceConnection的私有子类。然后,我重写onServiceConnected()方法来为Activity提供其数据(在这种情况下填充ListView)。

18

也许你不小心将服务标签放在应用程序标签之外?然后服务只是默默地失败。尽管日志中应该有一个“无法启动服务意图...”错误。

+0

非常感谢,但''标签绝对在''标签内。 – Spinner

+0

我忘了在manifest中定义一个Service标签。谢谢 –

14

确保在AndroidManifest.xml

<application> 
    ... 
    <service android:name=".path.to.service.MyService"/> 
</application>