在 onResume 中调用服务时出现 NullPointerException [英] NullPointerException when calling service in onResume

查看:22
本文介绍了在 onResume 中调用服务时出现 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调用服务,并根据响应将用户重定向到不同的活动(登录).

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

如果我等到说单击按钮时才执行此操作,则它可以正常工作(因为服务已绑定),但是如果我在 Resume 上执行此操作,则会出现以下异常:

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

我的代码是:

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

推荐答案

是什么让您认为 fooService 存在于 onResume() 点?

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

bindService() 的调用是异步的.当它发生时它就会发生.在 onServiceConnected() 被调用之前,你不能 doSomething(),并且 onServiceConnected() 可能在 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.

而且,如果 fooService 上的 get() 正在执行网络 I/O,您需要重写您的应用程序以将其从主应用程序线程移到后台线程.

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.

这篇关于在 onResume 中调用服务时出现 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆