0
我想使用IntentService
(从BroadcastReceiver
开始)从Internet下载文件,但我想通知用户文件是否已成功下载,如果被下载来解析文件。在我的IntentService
里面使用处理程序和handleMessage
是一个很好的解决方案?从我读的IntentServices
是简单的工作线程处理意图后过期,所以有可能处理程序不处理消息?在IntentService中使用Handler由BroadcastReceiver启动
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();
}
我只是想解析下载的文件,没有任何UI交互。 – Paul
噢,但你说“我想告诉用户文件是否被成功下载”。如果您不需要任何用户界面,为什么不在下载后将它解析到IntentService中? – fiddler
我在帖子中添加了一些代码。所以可以在行解析文件“//解析下载的文件?” ? – Paul