9

我正在尝试以与在活动中成功完成相同的方式从片段绑定服务,但是当我尝试在服务上调用方法时,我得到 NullPointerException - 显然是因为服务为空。现在绑定到 onStart 中的服务是否存在一些问题,或者我只是做错了?

@Override
public void onStart() {
    super.onStart();

    Intent intent = new Intent(getActivity(), LiteTrickService.class);
    getActivity().registerReceiver(receiver, new IntentFilter(LiteTrickService.BROADCAST_ACTION));
    getActivity().registerReceiver(receiver, new IntentFilter(LiteTrickService.BROADCAST_FAIL));
    getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

@Override
public void onStop() {
    super.onStop();
    getActivity().unbindService(mConnection);
    getActivity().unregisterReceiver(receiver);
    mBound = false;
}

编辑:对不起。这是我没有充分考虑这个问题的错误。mConnection 是一个 ServiceConnection,看起来像这样:

private ServiceConnection mConnection = new ServiceConnection() 
{

    @Override
    public void onServiceConnected(ComponentName className,
            IBinder service) {
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;
    }
};

堆栈跟踪 :

01-03 15:21:22.355: E/AndroidRuntime(12360): FATAL EXCEPTION: main
01-03 15:21:22.355: E/AndroidRuntime(12360): java.lang.NullPointerException
01-03 15:21:22.355: E/AndroidRuntime(12360):    at lite.hattrick.players.PlayerRankingFragment.onOptionsItemSelected(PlayerRankingFragment.java:205)

这将是引发异常的确切位置:case POPULATE_ID:

        if (hasData) {
            return false;
        }
        if(!mBound)
            getActivity().bindService(new Intent(getActivity().getApplicationContext(), LiteTrickService.class), mConnection, Context.BIND_AUTO_CREATE);
        mService.refreshPlayers(); // Null Pointer Exception as mService is null
        pBar.setVisibility(View.VISIBLE);
        return true;
4

2 回答 2

14

我解决了这个问题。结果我忘记在我的清单中提供带有正确包名的服务声明。

通过改变

<service android:name=".LiteTrickService" />

<service android:name="lite.hattrick.services.LiteTrickService" />

我解决了问题,服务现在按预期连接。

于 2013-01-03T14:36:18.393 回答
0

NullPointerExceptionmService变量上。正如您所说bindService()Activity绑定到Service它自己的线程。这意味着您的代码将在服务绑定时继续运行。这导致您的mService变量仍然是null.

您可以做的是将Service绑定后必须运行的代码移动到onServiceConnected()您的mConnection. 这将确保mService变量将指向您的服务,并且不会为空。

于 2013-01-03T14:27:42.977 回答