使用AsyncTask设置超时功能[Android] [英] Set timeout function with AsyncTask [Android]

查看:104
本文介绍了使用AsyncTask设置超时功能[Android]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我而言,我想按下按钮并获得超时处理.单击按钮后,它将通过Web服务验证accNo,如果验证(ProgressDialog)超过5秒钟,则它将停止并显示alertDialog来通知用户超时".

In my case, I would like to get the button pressed and get process with the timeout. When button clicked then it will verify the accNo with web services, if the verification (ProgressDialog) is over 5 seconds then it will stop and display the alertDialog to notice user "Timeout".

但是现在我还不知道何时以1毫秒进行测试,从逻辑上讲,它将在alertDialog中暂停直到被按下为止,但是现在它将以毫秒为单位显示该对话框,然后自动关闭并打算进行下一个活动.这是我的代码:

But now I have not idea when I in testing with 1 milliseconds, in logically it will pause in alertDialog until get pressed, but now it will display the dialog in milliseconds then auto dismiss and intent to next activity. Here is my code:

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_information3);

btn_next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (title.getText().toString().equals("INFO")) {
                InfoAsyncTask infoAsyncTask = new InfoAsyncTask();
                try {
                    infoAsyncTask.execute().get(1, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
                    alertDialog.setTitle(":: Error ::");
                    alertDialog.setMessage("Verify Timeout. Please try again.");

                    alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    alertDialog.show();
                }
           }
       });
   }

private class InfoAsyncTask extends AsyncTask<Void, Void, String> {
    private String results;
    private ProgressDialog pDialog;
    private Object resultRequestSOAP;
    String accNo = et_accNo.getText().toString().trim();
    int timeout = 15000;

    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(Information3.this);
        pDialog.setMessage("Verifying...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(Void... params) {
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("Code", InfoCode);
        request.addProperty("AccNo", accNo);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, timeout);
        androidHttpTransport.debug = true;

        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            String requestDumpString = androidHttpTransport.requestDump;
            Log.d("request Dump: ", requestDumpString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            resultRequestSOAP = envelope.getResponse();
            results = resultRequestSOAP.toString();
            Log.d("Output: ", results);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(String result) {
        if (resultRequestSOAP == null) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            } else {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);

                alertDialog.setTitle(":: Error ::");
                alertDialog.setMessage("Connection error, please check your internet connection.");

                alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                alertDialog.show();
                pDialog.dismiss();
            }
        } else {
            if (results.equals("false")) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);

                alertDialog.setTitle(":: Warning ::");
                alertDialog.setMessage("Please fill in correct account number");

                alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                alertDialog.show();
            } else if (et_billNo.getText().toString().trim().isEmpty()) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);

                alertDialog.setTitle(":: Warning ::");
                alertDialog.setMessage("Please fill in bill number");

                alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                alertDialog.show();
            } else if (et_amountNo.getText().toString().trim().isEmpty() || Integer.parseInt(et_amountNo.getText().toString().trim()) <= 0) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);

                alertDialog.setTitle(":: Warning ::");
                alertDialog.setMessage("Please fill in amount");

                alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                alertDialog.show();
            } else if (results.equals("true")) {
                Title = title.getText().toString();
                String value1 = et_accNo.getText().toString().trim();
                String value2 = et_billNo.getText().toString().trim();
                int value3 = Integer.parseInt(et_amountNo.getText().toString().trim());

                addSearchInput(value1);
                addSearchInput(value2);
                addSearchInput(String.valueOf(value3));

                Intent intent = new Intent(Information3.this, confirmation3.class);
                intent.putExtra("name", Title);
                intent.putExtra("value1", value1);
                intent.putExtra("value2", value2);
                intent.putExtra("value3", value3);
                startActivity(intent);
            } else {
                super.onPreExecute();
            }
            pDialog.dismiss();
        }
    }
}

推荐答案

get()方法将阻止UI线程,我想您不希望这样做.

get() method will block the UI thread and I guess you don't want this.

您应该在doInBackground中实现取消机制,并通过超时[这样](

You should implement cancel mechanics in doInBackground and call AsyncTask.cancel() by timeout [like that](https://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long))

final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        AsyncTask.cancel();
      }
    }, 1);

请注意,使用AsyncTask有很多陷阱,请检查我的文章.

Be aware there are many gotchas with AsyncTask, check my article.

这篇关于使用AsyncTask设置超时功能[Android]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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