I want to use an IntentService
(which is started from a BroadcastReceiver
) to download a file from Internet, but I want to inform the user if the file was downloaded successfully or not and if was downloaded to parse the file. Using a handler and handleMessage
inside my IntentService
is a good solution? From what I read IntentServices
is simple worker threads that expire after handling the intent, so is it possible that the handler does not handle the message ?
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();
}