如何从异步任务中取消

时间:2012-10-25 10:12:23

标签: android asynchronous

我在我的活动中调用一个函数,这基本上是一个通过webservice从远程服务器获取数据的异步任务。

 private void myAsyncTask() {
            new AsyncTask<Object, Object, Object>() {

                @Override
                protected void onPreExecute() {

                    progress_Dialog = ProgressDialog.show(a, "", "Loading");

                }

                @Override
                protected Integer doInBackground(Object... params) {


                    try
                    {
                    try {

                        MenuService menuService = new MenuServiceImpl();

                        MenuServiceResponse partnerMenu;
                            partnerMenu = menuService.getMenu();

                        productlist=Menu.getMenu().getMenuEntries();

                        System.gc();
                        return 0;
                    } catch (myServiceException e) {
                        bgFlag=true;

                        e.printStackTrace();
                    }
                    }
                    catch (Exception e) {

                        bgFlagForserviceExeption=true;
                        e.printStackTrace();


                    }
                    }                           return 0;
                }


                @Override
                protected void onPostExecute(Object result) {
                    if (progress_Dialog != null) {

                        progress_Dialog.dismiss();

                    }

                    try
                    {

                        if(bgFlagForserviceExeption)
                        {
                            MyAlertDialog.ShowAlertDialog(ShopActivity.this, "", "Please try again later", "OK");

                        }
                        if(bgFlag==false)
                        {
                     adapter = new ShopAdapter(
                            ShopActivity.this, productlist);

                                    allproduts.setAdapter(adapter);
                        }
                        else
                        {
                            MyAlertDialog.ShowAlertDialog(ShopActivity.this, "", " Please try again later", "OK");

                        }


                    }
                    catch(Exception e)
                    {
                        adapter=null;
                }

                }

            }.execute();



}

当我调用此活动时,将显示进度条,直到doinbackground()结束。如何按下手机后退按钮退出后台进程,现在问题是我将不得不等到后台进程完成即使我按下后退按钮。我怎么能实现这个

1 个答案:

答案 0 :(得分:1)

覆盖后退按钮。

Here it is

只需调用asynctask.cancel(true);

Read here