如何在此代码中添加AsyncTask Timeout?

时间:2014-10-16 08:14:03

标签: android android-asynctask

我在mainActivity [Get_IO()]中启动AsyncTask:

   // Rafraichissmeent de l'activity
    refresh = new Runnable() {
        public void run() {
            // Do something
            new Get_IO().execute();
            handler.postDelayed(refresh, 10000);
        }
    };
    handler.post(refresh);

但由于没有良好的连接质量,任务仍在等待,我想添加超时,但如何? 我已经尝试添加另一个任务来暂停,但不幸的是,它没有工作。

这里是Get_IO()代码:

public class Get_IO extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Handler mHandler = new Handler();
        //Runnable runnable = new Runnable() {
        //    @Override
        //    public void run() {
        //        if (mAT.getStatus() == Status.RUNNING || mAT.getStatus() == Status.PENDING) {
        //            mAT.cancel(true); //Cancel Async task or do the operation you want after 1 minute
        //        }
        //    }
        //};
        //mHandler.postDelayed(runnable, 60000);

        // Showing progress dialog
        pDialog = new ProgressDialog(PortailActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url_status, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                string_input = jsonObj.getString(TAG_INPUT);
                string_output = jsonObj.getString(TAG_OUTPUT);

                // tmp hashmap for single contact
                HashMap<String, String> iostatus = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                iostatus.put(TAG_INPUT, string_input);
                iostatus.put(TAG_OUTPUT, string_output);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

        TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
        lblMobile.setText(string_input.concat(" - ") .concat(string_output));
        check_etat_portail();
    }
}

我不太了解这件事;)

1 个答案:

答案 0 :(得分:0)

如果您想在执行makeServiceCall()时启动新活动,则应在onPostExecute()中执行此操作,并检查makeServiceCall()是否已暂停。如果你想缩短网络超时,你应该为你的HTTP请求设置它(所以基本上至少在makeServiceCall()甚至更低,这取决于你的应用程序结构。