java - 如何在android AsyncTask中设置等待互联网连接的时间限制?

标签 java android-asynctask progressdialog android-internet

我使用 AsyncTask 来连接互联网。 进度对话框可以在 onPreExecute() 处显示,我检查该移动设备是否在线,如果是,则意味着它将执行 http 连接代码,还会在 onPostExecute() 处关闭进度对话框,其工作效果也很好。

但是,如果请求时网络连接可用,并且在获得响应之前连接关闭,则我会遇到问题,这意味着进度对话框始终显示。

现在我想解决这个问题,如果在获得响应之前互连断开意味着它会提醒我没有互联网连接并关闭进度对话框(可以将加载时间限制设置为 30 秒)。

下面是我的代码。

有人可以帮忙吗?

   public class SubjectTask extends AsyncTask<Void, Void, Integer> {

    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(Login.this, "Loading",
                "Please wait...");
        //checkConnection();

    }

    @Override
    protected Integer doInBackground(Void... arg0) {

        if (isOnline()) {  //using ConnectivityManager And Network Info

            try {

                //Http Request connections

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



            return 1;
        } else {

            alert("Check your internet connection");
            return 0;
        }

    }

    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

}

最佳答案

您可以使用广播接收器来获取网络连接或断开的事件。在 doInbackground 方法中注册此接收器,并在 onPostExecute 方法中取消注册。

 broadcastReceiver = new BroadcastReceiver() {

                    @Override
                    public void onReceive(Context context, Intent intent) {

                        ConnectivityManager connectivity = (ConnectivityManager) context
                                .getSystemService(Context.CONNECTIVITY_SERVICE);


                            NetworkInfo info = connectivity.getActiveNetworkInfo();
                            //Play with the info about current network state
                             if(info.getState()== NetworkInfo.State.DISCONNECTED) {
                               // hide loader and show alert here
}

                        }

                    }
                };

                intentFilter = new IntentFilter();
                intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                registerReceiver(broadcastReceiver, intentFilter); 

关于java - 如何在android AsyncTask中设置等待互联网连接的时间限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24902760/

相关文章:

java - Inmobi 横幅广告尺寸

java - 如何在 Selenium Web 驱动程序中与不同用户并行登录网站?

android - 在 onDestroy 中进行所有清理是否安全?

java - 线程完成后出现 ProgressDialog

android - 如何设置 ProgressDialog 的大小以环绕进度圈

android - ProgressDialog 是否可绘制? GIF 什么的?

java - 对象的并发修改异常

java - 我可以用一行代码创建2个目录吗?

android-asynctask - asynctask #2 执行 doinbackground() 时发生错误

android - 异步任务 : how to add check on internet connection faults?