如何在viewpager中执行asynctask?

时间:2014-12-16 08:21:02

标签: android android-asynctask

我有3个寻呼机视图。当我尝试执行asynctask时,应用程序崩溃,因为所有任务同时启动。我想为当前可见的寻呼机执行asynctask。我该怎么做?

寻呼机1:

public class test extends android.support.v4.app.Fragment {

    private MyAsyncTask mAuthTask = null;

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

        View test = inflater.inflate(R.layout.test, container, false);
        ((TextView)test.findViewById(R.id.textView)).setText("test");
        return test;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            attemptLogin();
        }
    }
    @Override
    public void onViewCreated (View view, Bundle savedInstanceState) {

    }


    public void attemptLogin() {

        if (mAuthTask != null) {
            return;
        }
        mAuthTask = new MyAsyncTask();
        mAuthTask.execute((Void) null);
    }



    private class MyAsyncTask extends AsyncTask<Void, Void, Void>
    {
        @Override
        protected void onPostExecute(Void result) {
            //mProgressDialog.dismiss();
            Toast.makeText(getActivity(),
                    "completed", Toast.LENGTH_LONG).show();
        }
        @Override
        protected void onPreExecute() {
            Toast.makeText(getActivity(),
                    "Loading Explore", Toast.LENGTH_LONG).show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // my network operation



            return null;
        }
    }
}

4 个答案:

答案 0 :(得分:0)

试试这个......

//调用/执行Asynctask

new myAsyncTask().execute();

// AsyncTask的代码示例

private class myAsyncTask extends AsyncTask<Void, Void, Void>
    {
        JSONObject jObject;
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            //
        }

        @Override
        protected Void doInBackground(Void... arg0)
        {
     // doing bakground task

      return null;
        }
      protected void onPostExecute(Void result)
        {
        super.onPostExecute(result);
       }
   }

答案 1 :(得分:0)

这对我有用:

Base AsyncTask 类是:

public class BaseAsyncTask extends AsyncTask<String, Void, String> {

    @Override
    protected String  doInBackground(String... urls) {
        // TODO Auto-generated method stub
        return GET(urls[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }



    public static String GET(String url) {
        InputStream inputStream = null;
        String result = "";
        try {

            // create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // make GET request to the given URL
            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // convert inputstream to string
            if (inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return result;
    }

    private static String convertInputStreamToString(InputStream inputStream)
            throws IOException {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }


}

并在您想要的地方使用它:

baseAsyncTask = new BaseAsyncTask();
        baseAsyncTask.execute(apiUrl);
        try {
            result = baseAsyncTask.get();
        } catch (InterruptedException f) {
            // TODO Auto-generated catch block
            f.printStackTrace();
        } catch (ExecutionException e) {
            // TODO: handle exception
            e.printStackTrace();
        }

答案 2 :(得分:0)

ViewPager.onPageChangeListener pagelistener = new OnPageChangeListener(){

public void onPageScrollStateChanged(int state) {


}

public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

public void onPageSelected(int position) {
    // Check if this is the page you want.
}

});  pager.setOnPageChangeListener(pagelistener);

在onPageSelected

中调用asynctask

答案 3 :(得分:0)

假设您已使用片段填充ViewPager:

我不知道为什么你的应用程序会因为启动AsyncTask而崩溃,但如果你想弄清楚ViewPager中哪些片段是可见的,你可以覆盖Fragment方法setUserVisibleHint(boolean isVisibleToUser)

所以这样:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        startMyAsync();
    }else{
        startMyAsyncWithDelay();
    }
}