哪种方法适合从 android fragment 调用 Web 服务?
- oncreateView() 或
- oncreate() 或
- onViewCreated()
最佳答案
使用onStart()
方法
- 在
onStart()
mentod 中使用Async Task
调用并运行 后台线程 - 在 AsyncTask 中使用
doInBackground()
来运行采取的方法 执行时间更长 - 在
onPreExecute()
、onPostExecute()
中更新 UI 线程,onProgressUpdate()
public class FrgLatein extends Fragment {
//New-Instance
public static FrgLatein newInstance(){
Log.d("FrgLatein", "newInstance");
FrgLatein fragment = new FrgLatein();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("FrgLatein", "onCreateView");
View view=inflater.inflate(R.layout.frg_latein, container, false);
setHasOptionsMenu(true);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d("FrgLatein", "onActivityCreated");
super.onActivityCreated(savedInstanceState);
}
@Override
public void onStart() {
Log.d("FrgLatein", "onStart");
super.onStart();
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// Do the Web service long run here
return "Executed";
}
@Override
protected void onPostExecute(String result) {
// Do the UI-task here
}
@Override
protected void onPreExecute() {
// Do the UI-task here
}
@Override
protected void onProgressUpdate(Void... values) {
// Do the UI-task here which has to be done during backgroung tasks are running like a downloading process
}
}
}
关于java - 我们需要在哪个 fragment 方法中消费长期的weservice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25988192/