Descarrega.java 1.33 KB
package com.upc.pbe.upcnews;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class Descarrega extends AsyncTask<URL, Integer, String> {
	final static String TAG = "Descarrega";
	private Context ctx;

	public Descarrega(Context c) {
		ctx = c;
	}

	@Override
	protected String doInBackground(URL... urls) {
		// Codi de la tasca en background
		String html = "";
		// Iniciem la connexió i creem els Streams
		try {
			URLConnection conn = urls[0].openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			// Iniciem la descarrega, anem guardant al String i actualitzant la
			// barra de progrés
			int totalLength = conn.getContentLength();
			String inputLine;
			Log.d(TAG, "\nDescarregant: \n");
			Log.d(TAG, ">> URL: " + urls[0] + " >> Tamany: " + totalLength
					+ " bytes");
			while ((inputLine = in.readLine()) != null) {
				html += inputLine + "\n";
			}
			in.close();
			Log.d(TAG, "Descarrega finalitzada");
		} catch (IOException e) {
			this.cancel(true);
			Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG).show();
			return "";
		}
		return html;
	}
}