2

asynctask に少し問題があることに気付きました。Android デバイスの [戻る] ボタンを押して進行状況ダイアログと非同期タスクを閉じると、進行状況ダイアログのみが閉じられ、非同期タスクは引き続き実行されることに気付きました。なぜこれが起こっているのか本当にわからないので、誰かが私を正しい軌道に戻し、この問題を解決してくれることを願っていました.

    @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 ;           

        }

JSON パーサー:

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{}

    }{
    }

}
4

1 に答える 1

3

実行をキャンセルしたい場合は、 AsyncTasksメソッド内にキャンセル機能を実装する必要があります。doInBackground

呼び出された後cancel() isCancelled()は return が返されtrue返された後doInBackground onCancelledは の代わりに実行されますonPostExecute。パラメーターはバックグラウンド スレッドで割り込みを発行するため、長時間の操作は閉じられます。しかし、どこかでそれをキャッチすると思いますか?

Android ドキュメントから:

タスクができるだけ早くキャンセルされるようにするには、可能であればisCancelled()定期的に から の戻り値をチェックする必要がdoInBackground(Object[])あります (たとえば、ループ内)。

于 2013-08-31T16:29:36.783 に答える