|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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;
|
|
14
|
public class Descarrega extends AsyncTask<URL, Integer, String> {
|
|
15
16
|
final static String TAG = "Descarrega";
private Context ctx;
|
|
17
|
boolean failed = false;
|
|
18
19
|
public Descarrega(Context c) {
|
|
20
21
|
ctx = c;
}
|
|
22
|
|
|
23
|
@Override
|
|
24
25
|
protected String doInBackground(URL... urls) {
// Codi de la tasca en background
|
|
26
|
String html = "";
|
|
27
|
// Iniciem la connexió i creem els Streams
|
|
28
|
try {
|
|
29
|
URLConnection conn = urls[0].openConnection();
|
|
30
31
32
33
|
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
// Iniciem la descarrega, anem guardant al String i actualitzant la
// barra de progrés
|
|
34
|
int totalLength = conn.getContentLength();
|
|
35
|
String inputLine;
|
|
36
|
Log.d(TAG, "\nDescarregant: \n");
|
|
37
38
|
Log.d(TAG, ">> URL: " + urls[0] + " >> Tamany: " + totalLength
+ " bytes");
|
|
39
|
while ((inputLine = in.readLine()) != null) {
|
|
40
41
42
43
|
html += inputLine + "\n";
}
in.close();
Log.d(TAG, "Descarrega finalitzada");
|
|
44
|
} catch (IOException e) {
|
|
45
46
|
failed = true;
return urls[0].toString();
|
|
47
48
|
}
return html;
|
|
49
|
}
|
|
50
51
52
53
54
55
56
57
58
59
|
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();
}
}
|
|
60
|
}
|