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();
}
If you just want to create a notification to inform the user, then you can do it after download in your IntentService (see Sending a notification from a service in Android)
If you want to display a more elaborated UI (via an Activity) then you probably want to start one of your app’s activities with startActivity() method (see android start activity from service)
If you don’t need any UI stuff, just do the parsing in the
IntentServiceright after download.