我有Service
需要在其中onCreate
做一些工作,就像打开一个文件一样。但是,如果有IOException
,onCreate应该失败,我该如何向调用者指出这个?该方法不会抛出任何异常。我尝试过使用stopSelf()
,但显然它在创建服务之前没有效果,仍然会调用onStartCommand()
,之后代码失败,因为服务设置不正确。
public class MyService extends Service {
@Override
public void onCreate() {
try {
// do something
} catch (IOException ex) {
stopSelf(); // this does nothing
// need to show that setting up the service failed
return;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// this shouldn't be called if there was an error in onCreate
}
}