问题描述
- 在 Fragment 中调用 Service 执行下载任务,但是失败了,代码如下,请问下是为什么啊
-
public class JokeFragment extends Fragment implements ServiceConnection, SendCallBack { private RecyclerView mRecyclerView; private RecyclerAdapter mAdapter; private List<JokeData> mJokeDatas = new ArrayList<>(); private JokeService mService; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Intent intent = new Intent(getActivity().getApplicationContext(), JokeService.class); getActivity().getApplicationContext().bindService(intent, this, Context.BIND_AUTO_CREATE); } @Override public void onResume() { super.onResume(); mAdapter.notifyDataSetChanged(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_joke, container, false); mRecyclerView = (RecyclerView) view.findViewById(R.id.fragment_recyclerview); mAdapter = new RecyclerAdapter(getActivity(), mJokeDatas); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); mRecyclerView.setHasFixedSize(true); mRecyclerView.setAdapter(mAdapter); return view; } @Override public void onResult(List<JokeData> datas) { mJokeDatas = datas; } @Override public void onError(String info) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = ((JokeService.LocalBinder) service).getService(); if (mService!=null){ mService.setCallBack(this); mService.Download(); } } @Override public void onServiceDisconnected(ComponentName name) { mService = null; } @Override public void onPause() { super.onPause(); if (mService != null) { mService.setCallBack(null); getActivity().getApplicationContext().unbindService(this); } } }
解决方案
if (mService != null) {
mService.setCallBack(null);
getActivity().getApplicationContext().unbindService(this);
}
放 在OnDestory()中试试
时间: 2025-01-19 15:18:40