gpt4 book ai didi

java - 我们需要在哪个 fragment 方法中消费长期的weservice

转载 作者:行者123 更新时间:2023-11-30 02:39:23 24 4
gpt4 key购买 nike

哪种方法适合从 android fragment 调用 Web 服务?

  • oncreateView()
  • oncreate()
  • onViewCreated()

最佳答案

使用onStart()方法

  • onStart() mentod 中使用 Async Task 调用并运行后台线程
  • 在 AsyncTask 中使用 doInBackground() 来运行采取的方法执行时间更长
  • onPreExecute()onPostExecute() 中更新 UI 线程,onProgressUpdate()

Async task Example :

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com