onBack pressed只解雇ProgressDialog [英] onBackPressed only dismissing ProgressDialog

查看:159
本文介绍了onBack pressed只解雇ProgressDialog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经意识到,我和我的AsyncTask的一个小问题。我意识到,当我在Android设备上preSS后退按钮以关闭我的进度对话框和我的AsyncTask,只有被辞退了进度对话框和我的AsyncTask仍然执行。我真的不知道为什么会这样,所以我只是希望,如果有人可以让我回到正确的轨道上,并帮我解决这个问题。

  @覆盖
    公共无效onBack pressed()
    {
        / **如果用户pressed后退按钮时运行的AsyncTask
            这将关闭AsyncTask的。 * /
        如果(mTask = NULL&放大器;!&安培;!mTask.getStatus()= AsyncTask.Status.FINISHED)
        {
            mTask.cancel(真);
        }
        super.onBack pressed();
        完();
    }    @覆盖
    保护无效的onDestroy()
    {
        // TODO自动生成方法存根        / **如果activity被销毁时运行的AsyncTask
            这将关闭AsyncTask的。 * /        如果(mTask = NULL&放大器;!&安培;!mTask.getStatus()= AsyncTask.Status.FINISHED)
        {
            mTask.cancel(真);
        }        super.onDestroy();
    }    @覆盖
    保护无效的onPause()
    {
        // TODO自动生成方法存根        如果(pDialog!= NULL)
        {
            如果(pDialog.isShowing())
            {
                pDialog.dismiss();
            }
            super.onPause();
        }
    }        保护字符串doInBackground(字符串参数... args){            如果(isCancelled()){打破;}             尝试{
                在意向= getIntent();
                串SEARCHTERM = in.getStringExtra(TAG_SEARCH);
                查询字符串= URLEn coder.en code(SEARCHTERM,UTF-8);
                字符串的URL =example.com;
                JSONParsser jParser =新JSONParsser();
                JSONObject的JSON = jParser.readJSONFeed(URL);
                尝试{                    JSONArray问题= json.getJSONObject(全能)getJSONArray(问题);                    的for(int i = 0; I< questions.length();我++){
                        JSONObject的问题= questions.getJSONObject(I)
                    字符串主题= question.getString(TAG_QUESTION_SUBJECT);
                    字符串ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
                    字符串内容= question.getString(TAG_QUESTION_CONTENT);                    // JSONArray答案= question.getJSONObject(TAG_ANSWERS).getJSONArray(TAG_ANSWER);
                    // JSONObject的回答= Answers.getJSONObject(0);                    //字符串内容= Answer.getString(TAG_ANSWERS_CONTENT);                               HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();                               map.put(TAG_QUESTION_SUBJECT,主题);
                               map.put(TAG_QUESTION_CONTENT,内容);
                               map.put(TAG_QUESTION_CHOSENANSWER,ChosenAnswer);                               questionList.add(地图);                    }
                }赶上(JSONException E){
                    // TODO自动生成catch块
                    e.printStackTrace();
                }
            }赶上(UnsupportedEncodingException五){
                // TODO自动生成catch块
                e.printStackTrace();
            }                返回TAG_QUESTION;        }

JSONParsser:

 公共类JSONParsser {    InputStream为= NULL;
    JSONObject的jObj = NULL;
    JSON字符串=;
    公众的EditText等;    公共JSONParsser(){
    }    公众的JSONObject readJSONFeed(字符串URL){        尝试{
        HttpClient的客户端=新DefaultHttpClient();
        HttpPost要求=新HttpPost(URL);
        //request.setURI(website);
        尝试{
            HTT presponse响应= client.execute(请求);
        HttpEntity httpEntity = response.getEntity();
        是= httpEntity.getContent();        }赶上(ClientProtocolException E){
            // TODO自动生成catch块
            e.printStackTrace();
        }赶上(IOException异常五){
            // TODO自动生成catch块
            e.printStackTrace();
        }
        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);
            StringBuilder的SB =新的StringBuilder();
            串线;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
            }
            is.close();
            JSON = sb.toString();
        }赶上(例外五){
            Log.e(缓冲区错误,错误转换结果+ e.toString());
        }        尝试{
            jObj =新的JSONObject(JSON);
        }赶上(JSONException E){
           Log.e(JSON解析器,错误分析数据+ e.toString());
        }        Log.d(JSON字符串,JSON);        返回jObj;        }最后{}    } {
    }}


解决方案

您必须实现在的AsyncTask 取值 doInBackground 方法,如果您想取消它的执行。

您调用了取消() isCancelled() 将返回真正之后,你的 doInBackground 返回 onCancelled ,转而执行 onPostExecute 。该参数将发出在后台线程上的中断,使你长时间的操作被关闭。不过,我会假设你赶上什么地方?

Android电子文档


  

要确保任务是尽快取消,您应该
  经常检查返回值 isCancelled()定期从
   doInBackground(Object []对象),如果可能的话(里面比如一个循环。)


I have realized that i have a little issue with my asynctask. I realized that when I press the back button on an android device to dismiss my progress dialog and my asynctask, only my progress dialog is being dismissed and my asynctask still executes. I really do not know why this is happening so I was just hoping if somebody can get me back on the right track and help me with this problem.

    @Override
    public void onBackPressed() 
    {              
        /** If user Pressed BackButton While Running Asynctask
            this will close the ASynctask. */
        if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
        {
            mTask.cancel(true);
        }          
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy()
    {
        // TODO Auto-generated method stub

        /** If Activity is Destroyed While Running Asynctask
            this will close the ASynctask.   */

        if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
        {
            mTask.cancel(true);
        }  

        super.onDestroy();
    }

    @Override
    protected void onPause()
    {
        // TODO Auto-generated method stub

        if (pDialog != null)
        {
            if(pDialog.isShowing())
            {
                pDialog.dismiss();
            }
            super.onPause();
        }  
    }

        protected String doInBackground(String... args) {

            if (isCancelled()){break;}

             try {
                Intent in = getIntent();
                String searchTerm = in.getStringExtra("TAG_SEARCH");
                String query = URLEncoder.encode(searchTerm, "utf-8");
                String URL = "example.com";
                JSONParsser jParser = new JSONParsser();
                JSONObject json = jParser.readJSONFeed(URL);
                try {

                    JSONArray questions = json.getJSONObject("all").getJSONArray("questions");

                    for(int i = 0; i < questions.length(); i++) {
                        JSONObject question = questions.getJSONObject(i);


                    String Subject = question.getString(TAG_QUESTION_SUBJECT);
                    String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
                    String Content = question.getString(TAG_QUESTION_CONTENT);

                    //JSONArray Answers = question.getJSONObject(TAG_ANSWERS).getJSONArray(TAG_ANSWER);


                    //JSONObject Answer = Answers.getJSONObject(0);

                    //String Content = Answer.getString(TAG_ANSWERS_CONTENT);

                               HashMap<String, String> map = new HashMap<String, String>();

                               map.put(TAG_QUESTION_SUBJECT, Subject);
                               map.put(TAG_QUESTION_CONTENT, Content);
                               map.put(TAG_QUESTION_CHOSENANSWER, ChosenAnswer);

                               questionList.add(map);

                    }


                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

                return TAG_QUESTION ;           

        }

JSONParsser:

public class JSONParsser {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";
    public EditText et;

    public JSONParsser () {
    }

    public JSONObject readJSONFeed(String URL) {

        try{
        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(URL);
        //request.setURI(website);
        try {
            HttpResponse response = client.execute(request);
        HttpEntity httpEntity = response.getEntity();
        is = httpEntity.getContent();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
           Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        Log.d("JSON String",json);

        return jObj;

        }finally{}

    }{
    }

}

解决方案

You have to implement cancelling features within the AsyncTasks doInBackground method, if you wish to cancel its execution.

After you called cancel() isCancelled() will return true, and after your doInBackground returned onCancelled is executed instead of onPostExecute. The Parameter will issue an interrupt on the background thread, so your long-time operations are closed. However, I'd assume you catch that somewhere?

From the Android docs:

To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

这篇关于onBack pressed只解雇ProgressDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆