我的应用程序有一个小部件。我使用 HttpURLConnection 下载内容(每 15 分钟自动下载一次)。下载内容通常需要 10 秒。
问题是当应用程序在使用中时,它会在后台进行更新操作时冻结/挂起。我正在使用我的小部件类中 updateAppWidget 方法的 handler.postDelayed 。即使我使用的是后台线程,应用程序也会暂时冻结。我想也许 httpConn.connect(); 可能是问题并使用了 DefaultHttpClient。还是一样的冻结效果。
有人可以对这个问题提供一些见解吗?
谢谢...
从使用此处理程序的小部件类...
处理程序处理程序 = 新处理程序();
handler.postDelayed(new Runnable() {
public void run() {
//download and update widget UI here.....
}
}, 1000);
private String download1(String urlString) {
InputStream in = null;
byte[] data = null;
URLConnection conn = null;
try
{
URL url = new URL(urlString);
conn = url.openConnection();
if ((conn instanceof HttpURLConnection))
{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setConnectTimeout(30000);
httpConn.setReadTimeout(30000);
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
in = httpConn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while((c = in.read()) > -1){
baos.write(c);
}
data = baos.toByteArray();
baos.close();
in.close();
String str = new String(data);
System.out.println(str);
httpConn.disconnect();
((HttpURLConnection) conn).disconnect();
return str;
}
else
{
httpConn.disconnect();
((HttpURLConnection) conn).disconnect();
return("Error: Invalid data");
}
}
}
catch (Exception ex)
{
Log.e("TAG",ex.getMessage().toString());
return("Error: No connection");
}
finally
{
try
{
if (conn != null)
{
conn = null;
}
if (in != null)
{
in.close();
in = null;
}
}catch(IOException ex)
{
return("Error: "+ex.getMessage());
}
}
return null;
}