我想使用IntentService
(从BroadcastReceiver
启动)从Internet下载文件,但我想通知用户文件下载是否成功,以及是否下载以解析文件。在我的IntentService
中使用处理程序和handleMessage
是一个好的解决方案吗?从我所读到的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();
}
如果你只想创建一个通知来通知用户,那么你可以在IntentService中下载后完成(请参阅从Android中的服务发送通知)
如果你想显示一个更详细的UI(通过活动),那么你可能想用startActivity()方法启动你的应用程序的一个活动(请参阅android从服务启动活动)
如果您不需要任何UI内容,只需在下载后立即在IntentService
中进行解析即可。