Android:运行线程一段时间

时间:2013-04-08 12:29:54

标签: android multithreading time runnable terminate

在我的应用程序中,我正在调用API来获取一些JSON。 有时当人们使用2g网络或他们的网络丢失时,等待时间会变得很长(特别是当你显示一个对话框时),因此我想在45秒之后杀死该线程。

我搜索了SO并找到了这个帖子:Running a thread for some seconds

这是最好的方法吗?

我的代码是:

new Thread(new Runnable() {
                public void run() {
                     //i.e.
                    fetchJSON();
                }
            }).start(); 

干杯!

1 个答案:

答案 0 :(得分:1)

为此,您实际上需要使用HTTP的connection_timeout功能,以使您的Web调用在一段时间后自动终止。例如:

final int CONNECTION_TIME_OUT = 45;     //in seconds

HttpParams httpPar = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpPar, CONNECTION_TIME_OUT * 1000);
HttpConnectionParams.setSoTimeout(httpPar, CONNECTION_TIME_OUT * 1000);
HttpClient client = new DefaultHttpClient(httpPar);

有了这个,如果完成您的请求需要超过45秒,您的client将自动终止http连接。

相关问题