Descarrega.java 1.49 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;
	boolean failed = false;

	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) {
			failed = true;
			return urls[0].toString();
		}
		return html;
	}
	
	protected void onPostExecute(String url) 
	 {
		if(failed)
		{
			failed = false;
			this.cancel(true);
			Toast.makeText(ctx, "No s'ha pogut connectar a " + url, Toast.LENGTH_LONG).show();
		}
	}
}