2016-06-14 36 views
2

运行代码后,我遇到start service问题。Android设置完成启动服务的监听程序

我的服务类:

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    super.onStartCommand(intent, flags, startId); 

    mApplication.setService(this); 
} 

现在:

startService(intent); // service run sucess, but after millisecond delay 
mApplication.setIsServiceRunning(true); 

mApplication.getService().MyMethodAnyThing(); // <--- NullPointerExeption, because in my class mApplication.setService(this) do with delay and getService is null. 

我需要completed start service。例如:

startService(intent); 
mApplication.setIsServiceRunning(true); 

// i need like listener 
@Override 
onServiceIsRunComplete() { 
     // here i'm sure that service is run 
     mApplication.getService().MyMethodAnyThing(); 
} 
+2

然后使用'bindService'并等待'ServiceConnection' – pskink

+0

这很奇怪,因为服务与您的活动在同一线程上运行 –

+0

@TimCastelijns是的,对我来说奇怪 – grizzly

回答

1

停止服务时,也许这样的事情,

protected ServiceConnection mServerConn = new ServiceConnection() { 
    @Override 
    public void onServiceConnected(ComponentName name, IBinder binder) { 
     Log.d(LOG_TAG, "onServiceConnected"); 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName name) { 
     Log.d(LOG_TAG, "onServiceDisconnected"); 
    } 
} 

public void start() { 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE); 
    mContext.startService(intent); 
} 

也不要忘记unbindService()。

相关问题