我想使用 a IntentService
(从 a 开始BroadcastReceiver
)从 Internet 下载文件,但我想通知用户文件是否下载成功以及是否已下载以解析文件。handleMessage
在我的内部使用处理程序IntentService
是一个很好的解决方案吗?从我读到IntentServices
的是简单的工作线程在处理意图后过期,那么处理程序是否有可能不处理消息?
private void downloadResource(final String source, final File destination) {
Thread fileDownload = new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(source);
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
FileOutputStream fileOutput = new FileOutputStream(destination);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
// parse the downloaded file ?
} catch (Exception e) {
e.printStackTrace();
destination.delete();
}
}
});
fileDownload.start();
}