我正在尝试以与在活动中成功完成相同的方式从片段绑定服务,但是当我尝试在服务上调用方法时,我得到 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;