Igo*_*gor 0 service binding android
我试图调用服务,并根据响应将用户重定向到另一个活动(登录).
如果我等到这样做,直到说,按钮单击,然后它工作正常(因为服务绑定),但如果我在onResume上,那么我得到以下异常:
ERROR/AndroidRuntime(2226): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to resume activity {...MyActivity}:
java.lang.NullPointerException
Run Code Online (Sandbox Code Playgroud)
我的代码是:
FooService fooService;
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, FooService.class);
bindService(intent, fooServiceConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onResume() {
//I would assume the service would have bound by now?
super.onResume();
doSomething();
}
Run Code Online (Sandbox Code Playgroud)
是什么让你认为fooService存在的onResume()?
调用bindService()是异步的.它会在它发生时发生.你不能doSomething()直到onServiceConnected()被调用,并且onServiceConnected()可能没有被调用的时间onResume()被调用.
而且,如果get()on fooService正在进行网络I/O,则需要重写应用程序以将其从主应用程序线程移到后台线程上.