Descarrega.java
1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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();
}
}
}