我们需要在哪种片段方法中使用长期运行的Web服务

时间:2014-09-23 06:21:40

标签: java android android-fragments

在哪种方法中从android片段调用Web服务是合适的?

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

2 个答案:

答案 0 :(得分:2)

使用onStart()方法

  • Async Task指导中使用onStart()来电并运行 后台主题​​
  • 在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
        }
    }

}

答案 1 :(得分:-1)

您可以使用此片段的onCreateView()方法调用WebService -

public class MainActivity extends Fragment
{

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
  Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.mainFragment,container ,false);

    new GetWebService().execute();

    return view;
  }

  class GetWebService extends AsyncTask<String, String, String> 
  {

    @Override
    protected void onPreExecute() 
    {
       super.onPreExecute();
    }

    protected String doInBackground(String... args) 
    {

       //Call Webservice here and return the result

       return "";  
    }

    protected void onPostExecute(String result) 
    {
       //Do something with result
    }
}