NullPointerException when calling service in onRes

2019-01-27 09:47发布

问题:

I am attempting to make a call to a service, and based on the response, redirect the user to a different activity (a login).

If I wait to do this until say, a button click, then it works fine (since the service is bound), but if I do it onResume, then I get the following exception:

ERROR/AndroidRuntime(2226): FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to resume activity {...MyActivity}: 
        java.lang.NullPointerException

and my code is:

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

回答1:

What makes you think that fooService exists at the point of onResume()?

The call to bindService() is asynchronous. It will happen when it happens. You cannot doSomething() until onServiceConnected() is called, and onServiceConnected() may not have been called by the time onResume() is called.

And, if get() on fooService is doing network I/O, you need to rewrite your app to move that off the main application thread and onto a background thread.