如何在 Android 上停止 HttpURLConnection 连接 [英] How to stop HttpURLConnection connect on Android

查看:32
本文介绍了如何在 Android 上停止 HttpURLConnection 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 AsyncTask 连接 URLPath,如下代码所示.

I use AsyncTask to connect an URLPath as below code.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.left_list);

    Button btn = (Button)findViewById(resid);
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //how to stop connect
        }
    });
    new Connecting().execute();
}


class Connecting extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
            super.onPreExecute();
        //do something
    }

        @Override
        protected String doInBackground(String... aurl) {
            try {
                URL url = new URL(URLPath);
                connection = (HttpURLConnection)url.openConnection();
                connection.setConnectTimeout(30000);
                connection.setReadTimeout(30000);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.connect();
                is = connection.getInputStream();

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

        @Override
        protected void onPostExecute(String unused) {
            super.onPostExecute(unused);
        //access InputStream is
        }
}

connection 可能会花很多时间在 connect.
当它连接时,我想设置 Bbutton btn 被按下以停止连接连接.
如何在 setOnClickListener 方法中设置?

connection may spend much time in connect.
While it connecting, I want to set the Bbutton btn is pressed to stop the connection connect.
How can I set in setOnClickListener method?

推荐答案

将使用 HttpURLConnection 的代码包裹在一个 Future 中,可以随意取消.您还可以使用 Future 的超时功能,因为 HttpURLConnection 中的超时不可靠.

Wrap the code that uses HttpURLConnection inside a Future, which you can cancel at will. You can also use the Future's timeout feature, since the timeouts in HttpURLConnection are not reliable.

在你的网络类中定义一个执行器和未来:

Define an executor and future within your networking class:

final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
Future<MyResult> future;

然后将您的网络代码包装在 Future 中,如下所示:

Then wrap your networking code inside the Future like this:

future = executor.submit(new Callable<MyResult>() {
    @Override
    public MyResult call() throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        try {
            // .. use the connection ...
        } finally {
            connection.disconnect();
        }
    }
});

MyResult result = future.get(TIMEOUT, TimeUnit.SECONDS);

当你想取消时,你可以从任何线程调用:

When you want to cancel, you can make this call from any thread:

future.cancel(true);

如果未来超时或被取消,连接任务可能会继续阻塞在 HttpURLConnection 方法上,但您的应用程序不会被阻止.您仍然应该在连接上设置适当的超时以加快线程和网络套接字的释放.

If the future times out or is canceled, the connection task may continue to block on a HttpURLConnection method, but your application won't be held back. You should still set appropriate timeouts on the connection to speed up freeing of threads and network sockets.

这篇关于如何在 Android 上停止 HttpURLConnection 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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