Skip to content

Instantly share code, notes, and snippets.

@mcatta
Created May 13, 2013 10:15
Show Gist options
  • Save mcatta/5567365 to your computer and use it in GitHub Desktop.
Save mcatta/5567365 to your computer and use it in GitHub Desktop.
Download thread
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class DownloadThread extends Thread {
InputStream inputStream = null;
Handler handler;
URL url;
URLConnection urlConnection;
public DownloadThread(Handler handler) {
super();
this.handler = handler;
try {
url = new URL(Variables.URL);
} catch (MalformedURLException ex) {
// CODICE IRRAGGIUNGIBILE,L'URL OVVIAMENTE E' OK
ex.printStackTrace();
}
}
@Override
public void run() {
Log.i("LVUpdate/DOWNLOAD Thread", " *** Avvio della procedura di download *** ");
Message message = new Message();
byte[] buffer = new byte[1024]; // buffer store for the stream
String read = "";
try {
urlConnection = url.openConnection();
inputStream = urlConnection.getInputStream();
int current = 0;
while (((current = inputStream.read(buffer)) != -1)) {
String temp = new String(buffer, 0, current);
read += temp;
}
inputStream.close();
} catch (IOException e) {
Log.e("LVUpdate/DOWNLOAD Callable", "Error During Input Stream close; " + e.getMessage());
}
try {
message.what = Variables.DOWNLOAD_FINISHED;
message.obj = read;
message.arg1 = Variables.NO_ERROR;
} catch (Exception e) {
message.arg1 = Variables.DOWNLOAD_ERROR;
}
handler.sendMessage(message);
}
public void cancel() {
try {
inputStream.close();
this.interrupt();
} catch (IOException e) {
Log.e("THREAD CANCEL ERROR", "ERROR WHILE CLOSING CONNECTION");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment