Reputation: 195
I am downloading a file from the net and then reading it using a BufferedReader. Currently I download the file using DownloadManager then have this code :
while (latestNumbersFile.exists() != true) {
System.out.println("WAITING...");
}
try {
Thread.sleep(5000);
} catch (InterruptedException ignored) {
}
So that any following code does not execute until the file has finished downloading. This works but seams really dirty to me.
If I remove the Thread.sleep(5000);
it seams that the file does indeed exist but is not quite ready to be read.
There has to be a better way of recognizing when a file not only exists but is actually complete and ready to have something preformed on it.
Any thoughts?? (sorry if this is a noobie question, I've searched high and low for an answer)
Upvotes: 3
Views: 2248
Reputation: 2145
Busy-waiting is not recomended. You'd better use DownloadManager.
From Download a file with Android, and showing the progress in a ProgressDialog :
Use DownloadManager class (GingerBread and newer only) This method is awesome, you do not have to worry about downloading the file manually, handle threads, streams, etc. GingerBread brought a new feature: DownloadManager which allows you to download files easily and delegate the hard work to the system.
Upvotes: 0
Reputation: 536
From Android developers when download completes, DownloadManager broadcasts an intent. You can capture this "event" and handle it like:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
/** Do your coding here **/
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Source from: Vogella
Please let me know if this helps you, if it doesn't we can try anything else :)
Upvotes: 4