Commit 869cb3854946f2d04062e28a7cc6910c265575f3

Authored by Imanol-Mikel Barba Sabariego
1 parent 2ea470f7

Descargas en segundo plano, falta control de buffer, arreglada interfaz lista co…

…n iconos, quitado recurso calidad default
res/layout/rowlayout.xml
1 -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
2 - android:id="@+id/lelayout"  
3 - android:layout_width="fill_parent"  
4 - android:layout_height="wrap_content" >  
5 -  
6 - <TextView  
7 - android:id="@+id/rowTextView"  
8 - android:layout_width="fill_parent"  
9 - android:layout_height="wrap_content"  
10 - android:background="@drawable/selectedonlist"  
11 - android:padding="10dp"  
12 - android:textColor="@drawable/selectedonlist2"  
13 - android:textSize="16sp" >  
14 - </TextView>  
15 -  
16 - <ImageView  
17 - android:id="@+id/rowImageView"  
18 - android:layout_width="wrap_content"  
19 - android:layout_height="wrap_content"  
20 - android:layout_alignParentRight="true"  
21 - android:layout_centerVertical="true"  
22 - android:layout_marginRight="50dp"  
23 - android:src="@android:drawable/btn_star_big_off" />  
24 - 1 +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2 + android:id="@+id/lelayout"
  3 + android:layout_width="fill_parent"
  4 + android:layout_height="wrap_content"
  5 + android:background="@color/Black" >
  6 +
  7 + <ImageView
  8 + android:id="@+id/rowImageView"
  9 + android:layout_width="wrap_content"
  10 + android:layout_height="wrap_content"
  11 + android:layout_alignParentLeft="true"
  12 + android:layout_centerVertical="true"
  13 + android:layout_marginLeft="5dip"
  14 + android:adjustViewBounds="true"
  15 + android:contentDescription="@string/itemType"
  16 + android:maxHeight="25dip"
  17 + android:maxWidth="25dip"
  18 + android:scaleType="fitCenter"
  19 + android:src="@android:drawable/btn_star_big_off" />
  20 +
  21 + <TextView
  22 + android:id="@+id/rowTextView"
  23 + android:layout_width="fill_parent"
  24 + android:layout_height="40dip"
  25 + android:layout_centerVertical="true"
  26 + android:layout_marginLeft="5dip"
  27 + android:layout_toRightOf="@+id/rowImageView"
  28 + android:background="@drawable/selectedonlist"
  29 + android:gravity="center_vertical"
  30 + android:textColor="@drawable/selectedonlist2"
  31 + android:textSize="20sp" />
  32 +
25 </RelativeLayout> 33 </RelativeLayout>
26 \ No newline at end of file 34 \ No newline at end of file
res/values/strings.xml
@@ -6,7 +6,7 @@ @@ -6,7 +6,7 @@
6 <string name="descarregar">Iniciar aplicació</string> 6 <string name="descarregar">Iniciar aplicació</string>
7 <string name="hint">Toca per iniciar.</string> 7 <string name="hint">Toca per iniciar.</string>
8 <string name="url">URL del Servidor</string> 8 <string name="url">URL del Servidor</string>
9 - <string name="urlhint">Direcció URL del servidor a connectarse (sense http://)</string> 9 + <string name="urlhint">Direcció URL del servidor a connectarse\n(sense http://)</string>
10 <string name="prefs">Preferencies</string> 10 <string name="prefs">Preferencies</string>
11 <string name="help">Ajuda</string> 11 <string name="help">Ajuda</string>
12 <string name="desc">Reproduir</string> 12 <string name="desc">Reproduir</string>
@@ -26,20 +26,8 @@ @@ -26,20 +26,8 @@
26 siusplau dirigeixi\'s a la Universitat o escrigui un mail als desenvolupadors.\n\n Necessària la instal·lació 26 siusplau dirigeixi\'s a la Universitat o escrigui un mail als desenvolupadors.\n\n Necessària la instal·lació
27 de la llibreria Vitamio per reproduïr arxius .ts</string> 27 de la llibreria Vitamio per reproduïr arxius .ts</string>
28 <string name="defaultURL">revistes.upc.es/~imanol/PBE</string> 28 <string name="defaultURL">revistes.upc.es/~imanol/PBE</string>
29 - <string name="qual">Qualitat de reproducció</string>  
30 - <string name="qual_hint">Qualitat inicial de reproducció</string>  
31 - <string-array name="qualityNames">  
32 - <item >High Quality</item>  
33 - <item >Medium Quality</item>  
34 - <item >Low Quality</item>  
35 - </string-array>  
36 - <string-array name="qualityValues">  
37 - <item >0</item>  
38 - <item >1</item>  
39 - <item >2</item>  
40 - </string-array>  
41 - <string name="defaultQuality">0</string>  
42 <string name="alertVitamioNotInstalled">Alerta! Llibreries de Vitamio no instal·lades!</string> 29 <string name="alertVitamioNotInstalled">Alerta! Llibreries de Vitamio no instal·lades!</string>
43 <string name="alertLogoDescription">Alerta!</string> 30 <string name="alertLogoDescription">Alerta!</string>
  31 + <string name="itemType">Item type</string>
44 32
45 </resources> 33 </resources>
46 \ No newline at end of file 34 \ No newline at end of file
res/xml/prefs.xml
1 <?xml version="1.0" encoding="utf-8"?> 1 <?xml version="1.0" encoding="utf-8"?>
2 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > 2 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
3 <EditTextPreference android:key="server" android:title="@string/url" android:summary="@string/urlhint" android:defaultValue="@string/defaultURL"/> 3 <EditTextPreference android:key="server" android:title="@string/url" android:summary="@string/urlhint" android:defaultValue="@string/defaultURL"/>
4 - <ListPreference android:title="@string/qual" android:summary="@string/qual_hint" android:key="quality" android:entries="@array/qualityNames" android:entryValues="@array/qualityValues" android:defaultValue="@string/defaultQuality"/>  
5 </PreferenceScreen> 4 </PreferenceScreen>
6 \ No newline at end of file 5 \ No newline at end of file
src/com/upc/pbe/upcnews/Descarrega.java
1 -package com.upc.pbe.upcnews;  
2 -  
3 -import java.io.BufferedReader;  
4 -import java.io.File;  
5 -import java.io.FileOutputStream;  
6 -import java.io.IOException;  
7 -import java.io.InputStream;  
8 -import java.io.InputStreamReader;  
9 -import java.io.OutputStream;  
10 -import java.net.URL;  
11 -import java.net.URLConnection;  
12 -  
13 -import android.app.DownloadManager;  
14 -import android.app.DownloadManager.Request;  
15 -import android.net.Uri;  
16 -import android.os.AsyncTask;  
17 -import android.os.Environment;  
18 -import android.util.Log;  
19 -  
20 -//Descarrega un arxiu i el guarda o retorna en String  
21 -public class Descarrega extends AsyncTask<Object, Object, Object>  
22 -{  
23 - final static String TAG = "Descarrega";  
24 - private String html;  
25 - DownloadManager manager;  
26 -  
27 - public Descarrega()  
28 - {  
29 - html = "";  
30 - }  
31 -  
32 - public Descarrega(DownloadManager man){  
33 - manager = man;  
34 - }  
35 -  
36 - public void descarregarguardar(String url, String path) throws IOException  
37 - {  
38 -  
39 - // Descarrega un arxiu i el guarda  
40 - // Creem l'arxiu  
41 - File file = new File(path + url.substring(url.lastIndexOf("/")+1, url.length()));  
42 - // Iniciem la descarrega  
43 - URLConnection conn = new URL(url).openConnection();  
44 - conn.connect();  
45 - Log.d(TAG, "\nDescarregant: \n");  
46 - Log.d(TAG, " >> URL: " + url + " >> Desti: " + path + " >> Tamany: "  
47 - + conn.getContentLength() + " bytes");  
48 - // Llegeix cada byte i l'escriu en un arxiu fins que arriba a -1  
49 - InputStream in = conn.getInputStream();  
50 - OutputStream out = new FileOutputStream(file);  
51 - byte data[] = new byte[102400]; //Mejor throughput!!  
52 - int count;  
53 - while((count = in.read(data)) != -1)  
54 - {  
55 - out.write(data,0,count);  
56 - }  
57 - out.flush();  
58 - out.close();  
59 - in.close();  
60 -  
61 - }  
62 -  
63 - public void descarrega(String url, String path, String name) throws IOException{  
64 -  
65 - Request req = new Request(Uri.parse(url));  
66 -  
67 - //req.setVisibleInDownloadsUi(false);  
68 - req.setDestinationInExternalPublicDir(path, name);  
69 - manager.enqueue(req);  
70 - Log.d(TAG, "\nDescarregant: \n");  
71 - Log.d(TAG, " >> URL: " + url + " >> Desti: " + path);  
72 -  
73 - }  
74 -  
75 - protected String doInBackground(String url) throws IOException  
76 - {  
77 - // Descarrega un arxiu i el retorna en un String  
78 - html = "";  
79 - // Iniciem la connexi� i creem els Streams  
80 - URLConnection conn = new URL(url).openConnection();  
81 - BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
82 - // Iniciem la descarrega i anem guardant al String  
83 - Log.d(TAG, "\nDescarregant: \n");  
84 - Log.d(TAG, ">> URL: " + url + " >> Tamany: " + conn.getContentLength()  
85 - + " bytes");  
86 - String inputLine;  
87 - while ((inputLine = in.readLine()) != null)  
88 - {  
89 - html = html + "\n" + inputLine;  
90 - }  
91 - Log.d(TAG, "Descarrega finalitzada");  
92 - in.close();  
93 - return html;  
94 - }  
95 -  
96 - @Override  
97 - protected Object doInBackground(Object... arg0)  
98 - {  
99 - // Metode Overrided, no te utilitat  
100 - return null;  
101 - }  
102 -} 1 +package com.upc.pbe.upcnews;
  2 +
  3 +import java.io.BufferedReader;
  4 +import java.io.IOException;
  5 +import java.io.InputStreamReader;
  6 +import java.net.URL;
  7 +import java.net.URLConnection;
  8 +
  9 +import android.content.Context;
  10 +import android.os.AsyncTask;
  11 +import android.util.Log;
  12 +import android.widget.Toast;
  13 +
  14 +public class Descarrega extends AsyncTask<URL, Integer, String>
  15 +{
  16 + final static String TAG = "Descarrega";
  17 + private Context ctx;
  18 +
  19 + public Descarrega(Context c)
  20 + {
  21 + ctx = c;
  22 + }
  23 +
  24 + @Override
  25 + protected String doInBackground(URL... urls)
  26 + {
  27 + String html = "";
  28 + // Iniciem la connexi� i creem els Streams
  29 + try
  30 + {
  31 + URLConnection conn = urls[0].openConnection();
  32 + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  33 + // Iniciem la descarrega i anem guardant al String
  34 + Log.d(TAG, "\nDescarregant: \n");
  35 + Log.d(TAG, ">> URL: " + urls[0] + " >> Tamany: " + conn.getContentLength() + " bytes");
  36 + String inputLine;
  37 + while ((inputLine = in.readLine()) != null)
  38 + {
  39 + html += inputLine + "\n";
  40 + }
  41 + in.close();
  42 + Log.d(TAG, "Descarrega finalitzada");
  43 + }
  44 + catch(IOException e)
  45 + {
  46 + this.cancel(true);
  47 + Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG).show();
  48 + return "";
  49 + }
  50 + return html;
  51 + }
  52 +
  53 +}
  54 +
src/com/upc/pbe/upcnews/Directoris.java
1 package com.upc.pbe.upcnews; 1 package com.upc.pbe.upcnews;
2 2
3 import java.io.IOException; 3 import java.io.IOException;
  4 +import java.net.URL;
4 import java.util.ArrayList; 5 import java.util.ArrayList;
  6 +import java.util.concurrent.ExecutionException;
5 7
6 import android.app.Activity; 8 import android.app.Activity;
7 import android.app.DownloadManager; 9 import android.app.DownloadManager;
@@ -16,147 +18,195 @@ import android.view.View; @@ -16,147 +18,195 @@ import android.view.View;
16 import android.widget.AdapterView; 18 import android.widget.AdapterView;
17 import android.widget.AdapterView.OnItemClickListener; 19 import android.widget.AdapterView.OnItemClickListener;
18 import android.widget.ListView; 20 import android.widget.ListView;
  21 +import android.widget.RelativeLayout;
19 import android.widget.TextView; 22 import android.widget.TextView;
20 import android.widget.Toast; 23 import android.widget.Toast;
21 24
22 //Segona Activity, mostra els directoris i arxius del servidor 25 //Segona Activity, mostra els directoris i arxius del servidor
23 -public class Directoris extends Activity implements OnItemClickListener {  
24 - 26 +public class Directoris extends Activity implements OnItemClickListener
  27 +{
  28 +
25 final static String TAG = "Directoris"; 29 final static String TAG = "Directoris";
26 - private Descarrega d = new Descarrega();  
27 private String URL, currentFolder; 30 private String URL, currentFolder;
28 private HTMLParser parser; 31 private HTMLParser parser;
29 32
30 - public void onCreate(Bundle savedInstanceState){  
31 - //Creem el layout 33 + public void onCreate(Bundle savedInstanceState)
  34 + {
  35 + // Creem el layout
32 Log.d(TAG, "onCreated"); 36 Log.d(TAG, "onCreated");
33 super.onCreate(savedInstanceState); 37 super.onCreate(savedInstanceState);
34 - //Passem del layout anterior al actual 38 + // Passem del layout anterior al actual
35 setContentView(R.layout.dirs); 39 setContentView(R.layout.dirs);
36 - //Canviem la direccio de la URL a la actual 40 + // Canviem la direccio de la URL a la actual
37 currentFolder = ((UpcApp) getApplication()).getUrl() + "/"; 41 currentFolder = ((UpcApp) getApplication()).getUrl() + "/";
38 URL = currentFolder; 42 URL = currentFolder;
39 - //Creem un HTMLParser 43 + // Creem un HTMLParser
40 parser = new HTMLParser(URL); 44 parser = new HTMLParser(URL);
41 - //Fem una llista ListView i la omplim amb la informacio trobada  
42 - ((ListView)findViewById(R.id.listView1)).setOnItemClickListener(this); 45 + // Fem una llista ListView i la omplim amb la informacio trobada
  46 + ((ListView) findViewById(R.id.listView1)).setOnItemClickListener(this);
43 this.showResources(); 47 this.showResources();
44 } 48 }
45 -  
46 - public void showResources(){  
47 - //Actualitza la informacio que mostra la ListView a mesura que ens desplacem pels directoris 49 +
  50 + public void showResources()
  51 + {
  52 + // Actualitza la informacio que mostra la ListView a mesura que ens
  53 + // desplacem pels directoris
48 ArrayList<String> entries; 54 ArrayList<String> entries;
49 - try{  
50 - entries = parser.parse(d.doInBackground(currentFolder)); 55 + Descarrega d = new Descarrega(this);
  56 + try
  57 + {
  58 + d.execute(new URL(currentFolder));
  59 + entries = parser.parse(d.get());
51 this.createEntries(entries); 60 this.createEntries(entries);
52 } 61 }
53 - catch (IOException e){ 62 + catch (InterruptedException e)
  63 + {
  64 + // TODO Auto-generated catch block
  65 + e.printStackTrace();
  66 + }
  67 + catch (ExecutionException e)
  68 + {
  69 + // TODO Auto-generated catch block
  70 + e.printStackTrace();
  71 + }
  72 + catch (IOException e)
  73 + {
54 // Nunca llegara aqui la cosa, y si lo hace ES CULPA DEL SERVIDOR!! 74 // Nunca llegara aqui la cosa, y si lo hace ES CULPA DEL SERVIDOR!!
55 } 75 }
56 } 76 }
57 -  
58 - public void createEntries(ArrayList<String> directories){  
59 - //Crea les entrades de la ListView 77 +
  78 + public void createEntries(ArrayList<String> directories)
  79 + {
  80 + // Crea les entrades de la ListView
60 String[] entries = directories.toArray(new String[directories.size()]); 81 String[] entries = directories.toArray(new String[directories.size()]);
61 ListView listView = (ListView) findViewById(R.id.listView1); 82 ListView listView = (ListView) findViewById(R.id.listView1);
62 listView.setAdapter(null); 83 listView.setAdapter(null);
63 ResourceAdapter adapter = new ResourceAdapter(this, R.layout.rowlayout, entries); 84 ResourceAdapter adapter = new ResourceAdapter(this, R.layout.rowlayout, entries);
64 listView.setAdapter(adapter); 85 listView.setAdapter(adapter);
65 } 86 }
66 - 87 +
67 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 88 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
68 //Determina el funcionament al clickar en una de les entrades de al ListView 89 //Determina el funcionament al clickar en una de les entrades de al ListView
69 - String path = ((TextView)view).getText().toString(); 90 + String path = ((TextView)((RelativeLayout)view).findViewById(R.id.rowTextView)).getText().toString();
70 //Si es un m3u8, el descarrega, parseja i inicia la reproduccio 91 //Si es un m3u8, el descarrega, parseja i inicia la reproduccio
71 - if(path.endsWith(".m3u8")){ 92 + if(path.endsWith(".m3u8"))
  93 + {
72 path = currentFolder + path; 94 path = currentFolder + path;
73 String playlist; 95 String playlist;
74 - try{  
75 - //Descarreguem m3u8  
76 - playlist = d.doInBackground(path);  
77 - Parser p = new Parser(path.substring(0, path.lastIndexOf("/") + 1), this);  
78 - try{  
79 - //Parsing m3u8  
80 - ArrayList<ParentList> m3u8parsed = p.parseFile(playlist);  
81 - Log.d(TAG, "Parsing completat");  
82 - //Creem un gestor HLS  
83 - DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);  
84 - HLS h = new HLS(m3u8parsed,((UpcApp)getApplication()).getLocalPath(), manager);  
85 - ((UpcApp)getApplication()).setHLS(h);  
86 - //Iniciem la reproduccio  
87 - Intent mIntent = new Intent(this, VideoActivity.class);  
88 - if(((UpcApp)getApplication()).getHLS() != null) {  
89 - startActivity(mIntent); 96 + try
  97 + {
  98 + Descarrega d = new Descarrega(this);
  99 + //Descarreguem m3u8
  100 + d.execute(new URL(path));
  101 + playlist = d.get();
  102 + Parser p = new Parser(path.substring(0, path.lastIndexOf("/") + 1), this);
  103 + try
  104 + {
  105 + //Parsing m3u8
  106 + ArrayList<ParentList> m3u8parsed = p.parseFile(playlist);
  107 + Log.d(TAG, "Parsing completat");
  108 + //Creem un gestor HLS
  109 + DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
  110 + HLS h = new HLS(m3u8parsed,((UpcApp)getApplication()).getLocalPath(), manager);
  111 + ((UpcApp)getApplication()).setHLS(h);
  112 + //Iniciem la reproduccio
  113 + Intent mIntent = new Intent(this, VideoActivity.class);
  114 + if(((UpcApp)getApplication()).getHLS() != null)
  115 + {
  116 + startActivity(mIntent);
  117 + }
  118 + else
  119 + {
  120 + Toast.makeText(this, "Error en gestor HLS", Toast.LENGTH_LONG).show();
  121 + }
  122 + }
  123 + catch (ErrorException e)
  124 + {
  125 + Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
  126 + Log.d(TAG, e.getMessage());
  127 + }
  128 + catch (WarningException e)
  129 + {
  130 + Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
  131 + Log.d(TAG, e.getMessage());
90 } 132 }
91 - else {  
92 - Toast.makeText(this, "Error en gestor HLS", Toast.LENGTH_LONG).show(); 133 + catch (InfoException e)
  134 + {
  135 + Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
  136 + Log.d(TAG, e.getMessage());
93 } 137 }
94 } 138 }
95 - catch (ErrorException e){  
96 - Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();  
97 - Log.d(TAG, e.getMessage()); 139 + catch (IOException e1)
  140 + {
  141 + // Nunca llegara aqui la cosa, y si lo hace ES CULPA DEL SERVIDOR!!
98 } 142 }
99 - catch (WarningException e){  
100 - Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();  
101 - Log.d(TAG, e.getMessage()); 143 + catch (InterruptedException e1)
  144 + {
  145 + // TODO Auto-generated catch block
  146 + e1.printStackTrace();
102 } 147 }
103 - catch (InfoException e){  
104 - Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();  
105 - Log.d(TAG, e.getMessage()); 148 + catch (ExecutionException e1)
  149 + {
  150 + // TODO Auto-generated catch block
  151 + e1.printStackTrace();
106 } 152 }
107 } 153 }
108 - catch (IOException e1){  
109 - // Nunca llegara aqui la cosa, y si lo hace ES CULPA DEL SERVIDOR!!  
110 - }  
111 -  
112 - }  
113 //Si es una carpeta, hi entra i mostra el seu contingut 154 //Si es una carpeta, hi entra i mostra el seu contingut
114 - else{  
115 - if(!path.startsWith("http://")){ 155 + else
  156 + {
  157 + if(!path.startsWith("http://"))
  158 + {
116 currentFolder += path; 159 currentFolder += path;
117 } 160 }
118 - else{ 161 + else
  162 + {
119 currentFolder = path; 163 currentFolder = path;
120 } 164 }
121 showResources(); 165 showResources();
122 } 166 }
123 } 167 }
124 -  
125 - public boolean onKeyDown(int keyCode, KeyEvent event) {  
126 - //Determina el funcionament al apretar la tecla de tornar enrere  
127 - if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){  
128 - if(currentFolder.equals(URL)){  
129 - super.finish();  
130 - return true;  
131 - }  
132 - currentFolder = currentFolder.substring(0, currentFolder.length()-1);  
133 - currentFolder = currentFolder.substring(0,currentFolder.lastIndexOf("/")+1);  
134 - showResources();  
135 - return true;  
136 - }  
137 - return super.onKeyDown(keyCode, event); 168 +
  169 + public boolean onKeyDown(int keyCode, KeyEvent event)
  170 + {
  171 + // Determina el funcionament al apretar la tecla de tornar enrere
  172 + if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
  173 + {
  174 + if (currentFolder.equals(URL))
  175 + {
  176 + super.finish();
  177 + return true;
  178 + }
  179 + currentFolder = currentFolder.substring(0, currentFolder.length() - 1);
  180 + currentFolder = currentFolder.substring(0, currentFolder.lastIndexOf("/") + 1);
  181 + showResources();
  182 + return true;
  183 + }
  184 + return super.onKeyDown(keyCode, event);
138 } 185 }
139 -  
140 - public boolean onCreateOptionsMenu(Menu menu) {  
141 - //Determina el funcionament al apretar la tecla d'opcions 186 +
  187 + public boolean onCreateOptionsMenu(Menu menu)
  188 + {
  189 + // Determina el funcionament al apretar la tecla d'opcions
142 getMenuInflater().inflate(R.menu.menu, menu); 190 getMenuInflater().inflate(R.menu.menu, menu);
143 Log.d(TAG, "Menu"); 191 Log.d(TAG, "Menu");
144 return true; 192 return true;
145 } 193 }
146 194
147 - public boolean onOptionsItemSelected(MenuItem item) {  
148 - //Determina el funcionament al clickar en el menu d'opcions  
149 - switch (item.getItemId()) {  
150 - case R.id.itemprefs:  
151 - startActivity(new Intent(this, Prefs.class));  
152 - Log.d(TAG, "Preferencies");  
153 - return true;  
154 - case R.id.itemhelp:  
155 - startActivity(new Intent(this, Help.class));  
156 - Log.d(TAG, "Help");  
157 - return true;  
158 - default:  
159 - return false; 195 + public boolean onOptionsItemSelected(MenuItem item)
  196 + {
  197 + // Determina el funcionament al clickar en el menu d'opcions
  198 + switch (item.getItemId())
  199 + {
  200 + case R.id.itemprefs:
  201 + startActivity(new Intent(this, Prefs.class));
  202 + Log.d(TAG, "Preferencies");
  203 + return true;
  204 + case R.id.itemhelp:
  205 + startActivity(new Intent(this, Help.class));
  206 + Log.d(TAG, "Help");
  207 + return true;
  208 + default:
  209 + return false;
160 } 210 }
161 } 211 }
162 } 212 }
163 \ No newline at end of file 213 \ No newline at end of file
src/com/upc/pbe/upcnews/HLS.java
@@ -5,7 +5,10 @@ import java.io.IOException; @@ -5,7 +5,10 @@ import java.io.IOException;
5 import java.util.ArrayList; 5 import java.util.ArrayList;
6 6
7 import android.app.DownloadManager; 7 import android.app.DownloadManager;
  8 +import android.app.DownloadManager.Request;
  9 +import android.content.Context;
8 import android.net.TrafficStats; 10 import android.net.TrafficStats;
  11 +import android.net.Uri;
9 import android.util.Log; 12 import android.util.Log;
10 13
11 //Gestor del protocol HTTP Live Streaming 14 //Gestor del protocol HTTP Live Streaming
@@ -21,7 +24,7 @@ public class HLS @@ -21,7 +24,7 @@ public class HLS
21 private int currentSegment; 24 private int currentSegment;
22 private boolean endReached; 25 private boolean endReached;
23 private String localFolder; 26 private String localFolder;
24 - private Descarrega d; 27 + private DownloadManager dm;
25 private BandwidthMeasurer bm; 28 private BandwidthMeasurer bm;
26 29
27 30
@@ -42,8 +45,6 @@ public class HLS @@ -42,8 +45,6 @@ public class HLS
42 endReached = false; 45 endReached = false;
43 this.localFolder = localFolder; 46 this.localFolder = localFolder;
44 bm = new BandwidthMeasurer(); 47 bm = new BandwidthMeasurer();
45 -  
46 - d = new Descarrega(manager);  
47 } 48 }
48 49
49 public void loadVideo() 50 public void loadVideo()
@@ -75,7 +76,7 @@ public class HLS @@ -75,7 +76,7 @@ public class HLS
75 Log.d(TAG, seg.getName() + " " + seg.getURL()); 76 Log.d(TAG, seg.getName() + " " + seg.getURL());
76 long startTime = System.currentTimeMillis(); 77 long startTime = System.currentTimeMillis();
77 long segmentBytes = TrafficStats.getTotalRxBytes(); 78 long segmentBytes = TrafficStats.getTotalRxBytes();
78 - d.descarregarguardar(seg.getURL(), localFolder); 79 + descarregarguardar(seg.getURL(), localFolder);
79 double bps = bm.Measure(segmentBytes, startTime); 80 double bps = bm.Measure(segmentBytes, startTime);
80 Log.d(TAG, "Velocitat actual (KB/s): " + (bps / 8e3)); 81 Log.d(TAG, "Velocitat actual (KB/s): " + (bps / 8e3));
81 if ((bps <= qualities.get(currentQuality).getQuality()) && (bps != -1)) 82 if ((bps <= qualities.get(currentQuality).getQuality()) && (bps != -1))
@@ -117,6 +118,14 @@ public class HLS @@ -117,6 +118,14 @@ public class HLS
117 return path; 118 return path;
118 } 119 }
119 120
  121 + public void descarregarguardar(String url, String path)
  122 + {
  123 + Request req = new Request(Uri.parse(url));
  124 + req.setVisibleInDownloadsUi(false);
  125 + req.setDestinationUri(Uri.parse("file://"+path + url.substring(url.lastIndexOf("/")+1, url.length())));
  126 + dm.enqueue(req);
  127 + }
  128 +
120 public String previous() throws IOException 129 public String previous() throws IOException
121 { 130 {
122 Segment seg = null; 131 Segment seg = null;
@@ -128,8 +137,8 @@ public class HLS @@ -128,8 +137,8 @@ public class HLS
128 return localFolder + seg.getURL().substring(seg.getURL().lastIndexOf("/") + 1, seg.getURL().length()); 137 return localFolder + seg.getURL().substring(seg.getURL().lastIndexOf("/") + 1, seg.getURL().length());
129 } 138 }
130 139
131 - public void setDefQuality(int q) 140 + public void startDownloadManager(Context ctx)
132 { 141 {
133 - currentQuality = q; 142 + dm = (DownloadManager) ctx.getSystemService("download");
134 } 143 }
135 } 144 }
136 \ No newline at end of file 145 \ No newline at end of file
src/com/upc/pbe/upcnews/MainActivity.java
1 package com.upc.pbe.upcnews; 1 package com.upc.pbe.upcnews;
2 2
3 import java.io.File; 3 import java.io.File;
4 -import java.io.IOException;  
5 import java.net.MalformedURLException; 4 import java.net.MalformedURLException;
  5 +import java.net.URL;
6 import java.util.List; 6 import java.util.List;
  7 +import java.util.concurrent.ExecutionException;
7 8
8 import android.app.Activity; 9 import android.app.Activity;
9 -import android.app.DownloadManager;  
10 -import android.app.DownloadManager.Request;  
11 -import android.content.Context;  
12 import android.content.Intent; 10 import android.content.Intent;
13 import android.content.pm.PackageInfo; 11 import android.content.pm.PackageInfo;
14 import android.content.pm.PackageManager; 12 import android.content.pm.PackageManager;
15 -import android.net.Uri;  
16 import android.os.Bundle; 13 import android.os.Bundle;
17 -import android.os.Environment;  
18 import android.util.Log; 14 import android.util.Log;
19 import android.view.Menu; 15 import android.view.Menu;
20 import android.view.MenuItem; 16 import android.view.MenuItem;
@@ -48,19 +44,7 @@ public class MainActivity extends Activity implements OnClickListener { @@ -48,19 +44,7 @@ public class MainActivity extends Activity implements OnClickListener {
48 if(tempFolder.mkdirs()) { 44 if(tempFolder.mkdirs()) {
49 Log.d(TAG,"Directori " + tempFolder.toString() + " creat"); 45 Log.d(TAG,"Directori " + tempFolder.toString() + " creat");
50 } 46 }
51 - Log.d(TAG, Environment.getExternalStorageDirectory().toString());  
52 -  
53 - DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);  
54 - Request req = new Request(Uri.parse("http://10.0.2.157/upload/segments/pbe1.ts"));  
55 -  
56 - //req.setVisibleInDownloadsUi(false);  
57 - req.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().toString()+"/UPC NEWS", "b.ts");  
58 - manager.enqueue(req);  
59 -  
60 -  
61 -  
62 -  
63 - 47 +
64 //Creem els botons i text 48 //Creem els botons i text
65 URLText = (TextView) findViewById(R.id.textViewUrl); 49 URLText = (TextView) findViewById(R.id.textViewUrl);
66 buttonDescarrega = (ImageButton) findViewById(R.id.button); 50 buttonDescarrega = (ImageButton) findViewById(R.id.button);
@@ -87,26 +71,29 @@ public class MainActivity extends Activity implements OnClickListener { @@ -87,26 +71,29 @@ public class MainActivity extends Activity implements OnClickListener {
87 public void onClick(View v) { 71 public void onClick(View v) {
88 //Al polsar el boto s'inicia la descarrega 72 //Al polsar el boto s'inicia la descarrega
89 Log.d(TAG, "onClicked"); 73 Log.d(TAG, "onClicked");
90 - this.descarregar();  
91 - if(!html.equals("EMPTY")) {  
92 - ((UpcApp) getApplication()).setDesc(html);  
93 - startActivity(new Intent(this, Directoris.class)); 74 + Descarrega d = new Descarrega(this);
  75 + try
  76 + {
  77 + d.execute(new URL(((UpcApp)getApplication()).getUrl()));
  78 + html = d.get();
94 } 79 }
95 - }  
96 -  
97 - public void descarregar() {  
98 - //Descarrega del document HTML de la URL especificada  
99 - //Si hi ha errors, els mostrem en Toasts  
100 - Descarrega d = new Descarrega();  
101 - html="EMPTY";  
102 - try {  
103 - html = (String) d.doInBackground(((UpcApp)getApplication()).getUrl()); 80 + catch (InterruptedException e)
  81 + {
  82 + // TODO Auto-generated catch block
  83 + e.printStackTrace();
104 } 84 }
105 - catch(MalformedURLException e) {  
106 - Toast.makeText(this, "URL invalida", Toast.LENGTH_LONG).show(); 85 + catch (ExecutionException e)
  86 + {
  87 + // TODO Auto-generated catch block
  88 + e.printStackTrace();
  89 + }
  90 + catch (MalformedURLException e)
  91 + {
  92 + Toast.makeText(this, "URL Malformada", Toast.LENGTH_LONG).show();
107 } 93 }
108 - catch(IOException e) {  
109 - Toast.makeText(this, "No s'ha pogut trobar la URL", Toast.LENGTH_LONG).show(); 94 + if(!html.equals("")) {
  95 + ((UpcApp) getApplication()).setDesc(html);
  96 + startActivity(new Intent(this, Directoris.class));
110 } 97 }
111 } 98 }
112 99
@@ -141,6 +128,7 @@ public class MainActivity extends Activity implements OnClickListener { @@ -141,6 +128,7 @@ public class MainActivity extends Activity implements OnClickListener {
141 return false; 128 return false;
142 } 129 }
143 } 130 }
  131 +
144 /* 132 /*
145 * COSAS POR HACER 133 * COSAS POR HACER
146 * (NORMAL) Quitar la elección de calidad al inicio? Discutir 134 * (NORMAL) Quitar la elección de calidad al inicio? Discutir
src/com/upc/pbe/upcnews/Parser.java
@@ -3,79 +3,91 @@ package com.upc.pbe.upcnews; @@ -3,79 +3,91 @@ package com.upc.pbe.upcnews;
3 import java.io.IOException; 3 import java.io.IOException;
4 import java.net.MalformedURLException; 4 import java.net.MalformedURLException;
5 import java.util.ArrayList; 5 import java.util.ArrayList;
  6 +import java.util.concurrent.ExecutionException;
  7 +import java.net.URL;
6 8
7 -import android.app.Activity; 9 +import android.content.Context;
8 import android.widget.Toast; 10 import android.widget.Toast;
9 11
10 //Parser d'arxius m3u8 12 //Parser d'arxius m3u8
11 -public class Parser{  
12 - 13 +public class Parser
  14 +{
  15 +
13 private static final String STARTWORD = "#EXTM3U"; 16 private static final String STARTWORD = "#EXTM3U";
14 - private String path; //CWD, completes implicit paths such as "file.m3u8" appending the CWD in order to download the file  
15 - private int fileType; //Indica si es segment list o media list 17 + private String path; // CWD, completes implicit paths such as "file.m3u8"
  18 + // appending the CWD in order to download the file
  19 + private int fileType; // Indica si es segment list o media list
16 private int currentLine; 20 private int currentLine;
17 - private int currentSegment; //Cada segment de cada qualitat distinta  
18 - private int currentList; //Index de cada recurso distint 21 + private int currentSegment; // Cada segment de cada qualitat distinta
  22 + private int currentList; // Index de cada recurso distint
19 private boolean expectSegment = false; 23 private boolean expectSegment = false;
20 private boolean expectList = false; 24 private boolean expectList = false;
21 - private Descarrega download;  
22 - private Activity caller; //On enviar les notificacions i warnings  
23 - private boolean validated; //Indica si la llista comen�a amb #EXTM3U o no 25 + private Context ctx; // On enviar les notificacions i warnings
  26 + private boolean validated; // Indica si la llista comen�a amb #EXTM3U o no
24 private String server; 27 private String server;
25 28
26 - public Parser(String p, Activity caller){  
27 - this.caller = caller; 29 + public Parser(String p, Context caller)
  30 + {
  31 + ctx = caller;
28 path = p; 32 path = p;
29 String host = p.substring(7); 33 String host = p.substring(7);
30 - server = host.substring(0,host.indexOf("/")); 34 + server = host.substring(0, host.indexOf("/"));
31 currentLine = 0; 35 currentLine = 0;
32 currentSegment = 0; 36 currentSegment = 0;
33 currentList = 0; 37 currentList = 0;
34 - fileType = -1;//-1 indica UNDETERMINED, 0 indica SEGMENTS, 1 indica MEDIA  
35 - download = new Descarrega(); 38 + fileType = -1;// -1 indica UNDETERMINED, 0 indica SEGMENTS, 1 indica
  39 + // MEDIA
36 validated = false; 40 validated = false;
37 } 41 }
38 42
39 - public ArrayList<ParentList> parseFile(String file) throws ErrorException, WarningException, InfoException {  
40 - //Parseja un arxiu m3u8 43 + public ArrayList<ParentList> parseFile(String file) throws ErrorException, WarningException, InfoException
  44 + {
  45 + // Parseja un arxiu m3u8
41 ArrayList<ParentList> lists = new ArrayList<ParentList>(); 46 ArrayList<ParentList> lists = new ArrayList<ParentList>();
42 lists.add(new ParentList("")); 47 lists.add(new ParentList(""));
43 lists.get(0).getLists().add(new Video(-1)); 48 lists.get(0).getLists().add(new Video(-1));
44 String[] lines = file.split("\n"); 49 String[] lines = file.split("\n");
45 - for (int i = 0; i < lines.length; i++){  
46 - if (lines[i].endsWith("\\")){  
47 - //Barreja les entrades multilinea, que son les que acaben en backslash 50 + for (int i = 0; i < lines.length; i++)
  51 + {
  52 + if (lines[i].endsWith("\\"))
  53 + {
  54 + // Barreja les entrades multilinea, que son les que acaben en
  55 + // backslash
48 lines[++i] = lines[i - 1].substring(0, lines[i - 1].indexOf("\\") - 1) 56 lines[++i] = lines[i - 1].substring(0, lines[i - 1].indexOf("\\") - 1)
49 + lines[i]; 57 + lines[i];
50 } 58 }
51 - try{ 59 + try
  60 + {
52 parseLine(lines[i], lists); 61 parseLine(lines[i], lists);
53 } 62 }
54 - catch (InfoException iE){  
55 - Toast.makeText(caller, iE.getMessage(), Toast.LENGTH_SHORT).show(); 63 + catch (InfoException iE)
  64 + {
  65 + Toast.makeText(ctx, iE.getMessage(), Toast.LENGTH_SHORT).show();
56 } 66 }
57 - catch (WarningException wE){  
58 - Toast.makeText(caller, wE.getMessage(), Toast.LENGTH_SHORT).show(); 67 + catch (WarningException wE)
  68 + {
  69 + Toast.makeText(ctx, wE.getMessage(), Toast.LENGTH_SHORT).show();
59 } 70 }
60 } 71 }
61 /* 72 /*
62 - * Esto contiene una lista de RECURSOS,  
63 - * que a su vez contiene una lista de CALIDADES.  
64 - * Si no te gusta mis VERSOS,  
65 - * te mando a la mierda sin SUTILIDADES. 73 + * Esto contiene una lista de RECURSOS, que a su vez contiene una lista
  74 + * de CALIDADES. Si no te gusta mis VERSOS, te mando a la mierda sin
  75 + * SUTILIDADES.
66 * 76 *
67 * -- Imanol, hasta las cejas de cafeina. 77 * -- Imanol, hasta las cejas de cafeina.
68 * 78 *
69 * PD: En el ultimo nivel de profundidad hay una lista de segmentos 79 * PD: En el ultimo nivel de profundidad hay una lista de segmentos
70 * (debajo de calidades). Alli esta el autentico tesoro de Narnia. 80 * (debajo de calidades). Alli esta el autentico tesoro de Narnia.
71 */ 81 */
72 - for (int i = 0; i < lists.size(); i++){ 82 + for (int i = 0; i < lists.size(); i++)
  83 + {
73 sortQuality(lists.get(i)); 84 sortQuality(lists.get(i));
74 } 85 }
75 return lists; 86 return lists;
76 } 87 }
77 88
78 - private int searchID(String ID, ArrayList<ParentList> lists){ 89 + private int searchID(String ID, ArrayList<ParentList> lists)
  90 + {
79 for (int i = 0; i < lists.size(); i++) 91 for (int i = 0; i < lists.size(); i++)
80 { 92 {
81 if (lists.get(i).getID().equals(ID)) 93 if (lists.get(i).getID().equals(ID))
@@ -86,110 +98,154 @@ public class Parser{ @@ -86,110 +98,154 @@ public class Parser{
86 return -1; 98 return -1;
87 } 99 }
88 100
89 - private void sortQuality(ParentList ppls){ 101 + private void sortQuality(ParentList ppls)
  102 + {
90 ArrayList<Video> lists = ppls.getLists(); 103 ArrayList<Video> lists = ppls.getLists();
91 - if (lists.get(0).getQuality() == -1){  
92 - //Es el cas de Media Lists i Segment Lists, no tenen diferenciacio de qualitats 104 + if (lists.get(0).getQuality() == -1)
  105 + {
  106 + // Es el cas de Media Lists i Segment Lists, no tenen diferenciacio
  107 + // de qualitats
93 return; 108 return;
94 } 109 }
95 - //Bubblesort  
96 - while (true){ 110 + // Bubblesort
  111 + while (true)
  112 + {
97 boolean sorted = true; 113 boolean sorted = true;
98 int i = 0; 114 int i = 0;
99 - do{  
100 - if (lists.get(i).getQuality() < lists.get(i + 1).getQuality()){ 115 + do
  116 + {
  117 + if (lists.get(i).getQuality() < lists.get(i + 1).getQuality())
  118 + {
101 sorted = false; 119 sorted = false;
102 Video aux = lists.get(i); 120 Video aux = lists.get(i);
103 lists.set(i, lists.get(i + 1)); 121 lists.set(i, lists.get(i + 1));
104 lists.set(i + 1, aux); 122 lists.set(i + 1, aux);
105 } 123 }
106 124
107 - }while (++i != lists.size() - 1);  
108 - if (sorted){ 125 + }
  126 + while (++i != lists.size() - 1);
  127 + if (sorted)
  128 + {
109 break; 129 break;
110 } 130 }
111 } 131 }
112 132
113 } 133 }
114 134
115 - public void parseLine(String line, ArrayList<ParentList> lists) throws ErrorException, WarningException, InfoException {  
116 - //Parseja una linea de l'arxiu  
117 - if (line.isEmpty()){ 135 + public void parseLine(String line, ArrayList<ParentList> lists) throws ErrorException, WarningException, InfoException
  136 + {
  137 + // Parseja una linea de l'arxiu
  138 + if (line.isEmpty())
  139 + {
118 currentLine++; 140 currentLine++;
119 return; 141 return;
120 } 142 }
121 - else{ 143 + else
  144 + {
122 ParentList ppls = lists.get(currentList); 145 ParentList ppls = lists.get(currentList);
123 Video pls = ppls.getLists().get(ppls.getLists().size() - 1); 146 Video pls = ppls.getLists().get(ppls.getLists().size() - 1);
124 - if (!validated){  
125 - if (line.equals(STARTWORD)){ 147 + if (!validated)
  148 + {
  149 + if (line.equals(STARTWORD))
  150 + {
126 validated = true; 151 validated = true;
127 } 152 }
128 - else{ 153 + else
  154 + {
129 throw new ErrorException("Playlist no valida"); 155 throw new ErrorException("Playlist no valida");
130 } 156 }
131 } 157 }
132 - else{  
133 - if (line.charAt(0) == '#'){  
134 - if (line.substring(0, 4).equals("#EXT")){  
135 - if (expectSegment && !line.startsWith("#EXT-X-BYTERANGE")){ 158 + else
  159 + {
  160 + if (line.charAt(0) == '#')
  161 + {
  162 + if (line.substring(0, 4).equals("#EXT"))
  163 + {
  164 + if (expectSegment
  165 + && !line.startsWith("#EXT-X-BYTERANGE"))
  166 + {
136 throw new ErrorException("S'esperava segment URI, en comptes tenim EXT-TAG"); 167 throw new ErrorException("S'esperava segment URI, en comptes tenim EXT-TAG");
137 } 168 }
138 - if (expectList){ 169 + if (expectList)
  170 + {
139 throw new ErrorException("S'esperava llista, en comptes tenim EXT-TAG"); 171 throw new ErrorException("S'esperava llista, en comptes tenim EXT-TAG");
140 } 172 }
141 String[] extTag = line.split(":", 2); 173 String[] extTag = line.split(":", 2);
142 - if (extTag[0].equals("#EXT-X-MEDIA-SEQUENCE")){ 174 + if (extTag[0].equals("#EXT-X-MEDIA-SEQUENCE"))
  175 + {
143 pls.setSequence(Integer.parseInt(extTag[1])); 176 pls.setSequence(Integer.parseInt(extTag[1]));
144 } 177 }
145 - else if (extTag[0].equals("#EXT-X-TARGETDURATION")){ 178 + else if (extTag[0].equals("#EXT-X-TARGETDURATION"))
  179 + {
146 pls.setMaxDuration(Integer.parseInt(extTag[1])); 180 pls.setMaxDuration(Integer.parseInt(extTag[1]));
147 } 181 }
148 - else if (extTag[0].equals("#EXTINF")){  
149 - if (fileType == -1){ 182 + else if (extTag[0].equals("#EXTINF"))
  183 + {
  184 + if (fileType == -1)
  185 + {
150 fileType = 0; 186 fileType = 0;
151 } 187 }
152 - else if (fileType == 1){ 188 + else if (fileType == 1)
  189 + {
153 throw new ErrorException("Arxiu invalid, hauria de contenir llistes pero s'han trobat segments"); 190 throw new ErrorException("Arxiu invalid, hauria de contenir llistes pero s'han trobat segments");
154 } 191 }
155 String[] args = extTag[1].split(","); 192 String[] args = extTag[1].split(",");
156 float duration = Float.parseFloat(args[0]); 193 float duration = Float.parseFloat(args[0]);
157 - if (duration > pls.getMaxDuration()){  
158 - throw new ErrorException("Segment " + currentSegment + 1 + " en linea " + currentLine + " supera la duracio maxima"); 194 + if (duration > pls.getMaxDuration())
  195 + {
  196 + throw new ErrorException("Segment "
  197 + + currentSegment + 1 + " en linea "
  198 + + currentLine
  199 + + " supera la duracio maxima");
159 } 200 }
160 Segment s = new Segment(duration); 201 Segment s = new Segment(duration);
161 - if (args.length == 1){ 202 + if (args.length == 1)
  203 + {
162 s.setName(""); 204 s.setName("");
163 } 205 }
164 - else{ 206 + else
  207 + {
165 s.setName(args[1]); 208 s.setName(args[1]);
166 } 209 }
167 pls.getSegments().add(s); 210 pls.getSegments().add(s);
168 expectSegment = true; 211 expectSegment = true;
169 } 212 }
170 - else if (extTag[0].equals("#EXT-X-STREAM-INF")){  
171 - if (fileType == -1){ 213 + else if (extTag[0].equals("#EXT-X-STREAM-INF"))
  214 + {
  215 + if (fileType == -1)
  216 + {
172 fileType = 1; 217 fileType = 1;
173 } 218 }
174 - else if (fileType == 0){ 219 + else if (fileType == 0)
  220 + {
175 throw new ErrorException("Arxiu invalid, hauria de contenir segments pero s'han trobat llistes"); 221 throw new ErrorException("Arxiu invalid, hauria de contenir segments pero s'han trobat llistes");
176 } 222 }
177 expectList = true; 223 expectList = true;
178 String programID = ""; 224 String programID = "";
179 double bandwidth = -1; 225 double bandwidth = -1;
180 String[] arguments = extTag[1].split(","); 226 String[] arguments = extTag[1].split(",");
181 - for (int i = 0; i < arguments.length; i++){ 227 + for (int i = 0; i < arguments.length; i++)
  228 + {
182 String[] argument = arguments[i].split("="); 229 String[] argument = arguments[i].split("=");
183 - //Si l'argument en questio conte diferents valors, detecta el caracter " i els ajunta en un String  
184 - if (argument[1].startsWith("\"") && !argument[1].endsWith("\"")){ 230 + // Si l'argument en questio conte diferents
  231 + // valors, detecta el caracter " i els ajunta en
  232 + // un String
  233 + if (argument[1].startsWith("\"")
  234 + && !argument[1].endsWith("\""))
  235 + {
185 int j = i; 236 int j = i;
186 - while (true){  
187 - if (i == arguments.length - 1){  
188 - throw new ErrorException("Argument mal expressat en linea " + currentLine); 237 + while (true)
  238 + {
  239 + if (i == arguments.length - 1)
  240 + {
  241 + throw new ErrorException("Argument mal expressat en linea "
  242 + + currentLine);
189 } 243 }
190 - if (arguments[++i].endsWith("\"")){ 244 + if (arguments[++i].endsWith("\""))
  245 + {
191 String end = arguments[i]; 246 String end = arguments[i];
192 - for (int k = j + 1; k < i; k++){ 247 + for (int k = j + 1; k < i; k++)
  248 + {
193 argument[1] += arguments[k]; 249 argument[1] += arguments[k];
194 } 250 }
195 argument[1] += end; 251 argument[1] += end;
@@ -197,26 +253,37 @@ public class Parser{ @@ -197,26 +253,37 @@ public class Parser{
197 } 253 }
198 } 254 }
199 } 255 }
200 - if (argument[0].equals("PROGRAM-ID")){ 256 + if (argument[0].equals("PROGRAM-ID"))
  257 + {
201 programID = argument[1]; 258 programID = argument[1];
202 } 259 }
203 - else if (argument[0].equals("BANDWIDTH")){ 260 + else if (argument[0].equals("BANDWIDTH"))
  261 + {
204 bandwidth = Double.parseDouble(argument[1]); 262 bandwidth = Double.parseDouble(argument[1]);
205 } 263 }
206 } 264 }
207 - if (programID.equals("") || bandwidth == -1){  
208 - throw new ErrorException("Playlist en linea " + currentLine + " no te arguments"); 265 + if (programID.equals("") || bandwidth == -1)
  266 + {
  267 + throw new ErrorException("Playlist en linea "
  268 + + currentLine + " no te arguments");
209 } 269 }
210 - if (!programID.equals(ppls.getID())){  
211 - //Si el Program-ID no coincideix, buscar o crear un de nou  
212 - if (ppls.getID().equals("")){  
213 - //Si es treballa amb la ParentList per defecte, modificar, no crear una nova 270 + if (!programID.equals(ppls.getID()))
  271 + {
  272 + // Si el Program-ID no coincideix, buscar o
  273 + // crear un de nou
  274 + if (ppls.getID().equals(""))
  275 + {
  276 + // Si es treballa amb la ParentList per
  277 + // defecte, modificar, no crear una nova
214 lists.get(0).setID(programID); 278 lists.get(0).setID(programID);
215 } 279 }
216 - else{ 280 + else
  281 + {
217 currentList = searchID(programID, lists); 282 currentList = searchID(programID, lists);
218 - if (currentList == -1){  
219 - //No s'ha trobat ParentList, es crea una nova 283 + if (currentList == -1)
  284 + {
  285 + // No s'ha trobat ParentList, es crea
  286 + // una nova
220 lists.add(new ParentList(programID)); 287 lists.add(new ParentList(programID));
221 currentList = lists.size() - 1; 288 currentList = lists.size() - 1;
222 } 289 }
@@ -224,20 +291,28 @@ public class Parser{ @@ -224,20 +291,28 @@ public class Parser{
224 pls = ppls.getLists().get(ppls.getLists().size() - 1); 291 pls = ppls.getLists().get(ppls.getLists().size() - 1);
225 } 292 }
226 } 293 }
227 - //Creem una List dins el ParentList correcte  
228 - if ((ppls.getLists().size() == 1) && (pls.getQuality() == -1) && pls.getSegments().isEmpty()){  
229 - //Si es treballa amb la List per defecte, modificar, no crear una nova 294 + // Creem una List dins el ParentList correcte
  295 + if ((ppls.getLists().size() == 1)
  296 + && (pls.getQuality() == -1)
  297 + && pls.getSegments().isEmpty())
  298 + {
  299 + // Si es treballa amb la List per defecte,
  300 + // modificar, no crear una nova
230 pls.setQuality(bandwidth); 301 pls.setQuality(bandwidth);
231 } 302 }
232 - else{ 303 + else
  304 + {
233 ppls.getLists().add(new Video(bandwidth)); 305 ppls.getLists().add(new Video(bandwidth));
234 } 306 }
235 } 307 }
236 - else if (extTag[0].equals("#EXT-X-MEDIA")){  
237 - if (fileType == -1){ 308 + else if (extTag[0].equals("#EXT-X-MEDIA"))
  309 + {
  310 + if (fileType == -1)
  311 + {
238 fileType = 1; 312 fileType = 1;
239 } 313 }
240 - else if (fileType == 0){ 314 + else if (fileType == 0)
  315 + {
241 throw new ErrorException("Arxiu invalid, hauria de contenir segments pero s'han trobat llistes"); 316 throw new ErrorException("Arxiu invalid, hauria de contenir segments pero s'han trobat llistes");
242 } 317 }
243 String Type = ""; 318 String Type = "";
@@ -246,18 +321,28 @@ public class Parser{ @@ -246,18 +321,28 @@ public class Parser{
246 String URI = ""; 321 String URI = "";
247 boolean Default = false; 322 boolean Default = false;
248 String[] arguments = extTag[1].split(","); 323 String[] arguments = extTag[1].split(",");
249 - for (int i = 0; i < arguments.length; i++){ 324 + for (int i = 0; i < arguments.length; i++)
  325 + {
250 String[] argument = arguments[i].split("="); 326 String[] argument = arguments[i].split("=");
251 - //Si l'argument en questio conte diferents valors, detecta el caracter " i els ajunta en un String  
252 - if (argument[1].startsWith("\"") && !argument[1].endsWith("\"")){ 327 + // Si l'argument en questio conte diferents
  328 + // valors, detecta el caracter " i els ajunta en
  329 + // un String
  330 + if (argument[1].startsWith("\"")
  331 + && !argument[1].endsWith("\""))
  332 + {
253 int j = i; 333 int j = i;
254 - while (true){  
255 - if (i == arguments.length - 1){  
256 - throw new ErrorException("Argument mal expressat en linea " + currentLine); 334 + while (true)
  335 + {
  336 + if (i == arguments.length - 1)
  337 + {
  338 + throw new ErrorException("Argument mal expressat en linea "
  339 + + currentLine);
257 } 340 }
258 - if (arguments[++i].endsWith("\"")){ 341 + if (arguments[++i].endsWith("\""))
  342 + {
259 String end = arguments[i]; 343 String end = arguments[i];
260 - for (int k = j + 1; k < i; k++){ 344 + for (int k = j + 1; k < i; k++)
  345 + {
261 argument[1] += arguments[k]; 346 argument[1] += arguments[k];
262 } 347 }
263 argument[1] += end; 348 argument[1] += end;
@@ -265,55 +350,79 @@ public class Parser{ @@ -265,55 +350,79 @@ public class Parser{
265 } 350 }
266 } 351 }
267 } 352 }
268 - if (argument[0].equals("NAME")){ 353 + if (argument[0].equals("NAME"))
  354 + {
269 Name = argument[1].substring(1, argument[1].length() - 1); 355 Name = argument[1].substring(1, argument[1].length() - 1);
270 } 356 }
271 - else if (argument[0].equals("TYPE")){ 357 + else if (argument[0].equals("TYPE"))
  358 + {
272 Type = argument[1]; 359 Type = argument[1];
273 } 360 }
274 - else if (argument[0].equals("GROUP-ID")){ 361 + else if (argument[0].equals("GROUP-ID"))
  362 + {
275 GroupID = argument[1].substring(1, argument[1].length() - 1); 363 GroupID = argument[1].substring(1, argument[1].length() - 1);
276 } 364 }
277 - else if (argument[0].equals("DEFAULT")){  
278 - if (argument[1].equals("YES")){ 365 + else if (argument[0].equals("DEFAULT"))
  366 + {
  367 + if (argument[1].equals("YES"))
  368 + {
279 Default = true; 369 Default = true;
280 } 370 }
281 - else if (argument[1].equals("NO")){ 371 + else if (argument[1].equals("NO"))
  372 + {
282 Default = true; 373 Default = true;
283 } 374 }
284 - else{  
285 - throw new ErrorException("Valor invalid per l'argument DEFAULT en linea " + currentLine); 375 + else
  376 + {
  377 + throw new ErrorException("Valor invalid per l'argument DEFAULT en linea "
  378 + + currentLine);
286 } 379 }
287 } 380 }
288 - else if (argument[0].equals("URI")){  
289 - if (!argument[1].contains("http://")){  
290 - //En cas de que la ruta llegida es RELATIVE  
291 - URI = path + argument[1].substring(1, argument[1].length() - 1); 381 + else if (argument[0].equals("URI"))
  382 + {
  383 + if (!argument[1].contains("http://"))
  384 + {
  385 + // En cas de que la ruta llegida es
  386 + // RELATIVE
  387 + URI = path
  388 + + argument[1].substring(1, argument[1].length() - 1);
292 } 389 }
293 - else{ 390 + else
  391 + {
294 URI = argument[1].substring(1, argument[1].length() - 1); 392 URI = argument[1].substring(1, argument[1].length() - 1);
295 } 393 }
296 } 394 }
297 } 395 }
298 - if (Type.equals("") || Name.equals("") || URI.equals("") || GroupID.equals("")) {  
299 - throw new ErrorException("Playlist en linea " + currentLine + " no te arguments"); 396 + if (Type.equals("") || Name.equals("")
  397 + || URI.equals("") || GroupID.equals(""))
  398 + {
  399 + throw new ErrorException("Playlist en linea "
  400 + + currentLine + " no te arguments");
300 } 401 }
301 - Parser p = new Parser(URI.substring(0, URI.lastIndexOf("/") + 1), caller); 402 + Parser p = new Parser(URI.substring(0, URI.lastIndexOf("/") + 1), ctx);
302 Video newList; 403 Video newList;
303 - try{  
304 - newList = p.parseFile(download.doInBackground(URI)).get(0).getLists().get(0);  
305 - if (!GroupID.equals(ppls.getID())){  
306 - if (ppls.getID().equals("")){  
307 - //Si es treballa amb la ParentList per defecte, modificar, no crear una nova 404 + try
  405 + {
  406 + Descarrega download = new Descarrega(ctx);
  407 + download.execute(new URL(URI));
  408 + newList = p.parseFile(download.get()).get(0).getLists().get(0);
  409 + if (!GroupID.equals(ppls.getID()))
  410 + {
  411 + if (ppls.getID().equals(""))
  412 + {
  413 + // Si es treballa amb la ParentList per
  414 + // defecte, modificar, no crear una nova
308 ppls.setDefault(Default); 415 ppls.setDefault(Default);
309 ppls.setName(Name); 416 ppls.setName(Name);
310 ppls.setType(Type); 417 ppls.setType(Type);
311 ppls.getLists().set(0, newList); 418 ppls.getLists().set(0, newList);
312 ppls.setID(GroupID); 419 ppls.setID(GroupID);
313 } 420 }
314 - else{ 421 + else
  422 + {
315 currentList = searchID(GroupID, lists); 423 currentList = searchID(GroupID, lists);
316 - if (currentList == -1){ 424 + if (currentList == -1)
  425 + {
317 ParentList pl = new ParentList(GroupID); 426 ParentList pl = new ParentList(GroupID);
318 pl.setDefault(Default); 427 pl.setDefault(Default);
319 pl.setName(Name); 428 pl.setName(Name);
@@ -325,73 +434,115 @@ public class Parser{ @@ -325,73 +434,115 @@ public class Parser{
325 ppls.getLists().add(newList); 434 ppls.getLists().add(newList);
326 } 435 }
327 } 436 }
328 - else{ 437 + else
  438 + {
329 ppls.getLists().add(newList); 439 ppls.getLists().add(newList);
330 } 440 }
331 } 441 }
332 - catch (IOException e){  
333 - // Nunca llegara aqui la cosa, y si lo hace ES CULPA DEL SERVIDOR!! 442 + catch (IOException e)
  443 + {
  444 + // Nunca llegara aqui la cosa, y si lo hace ES
  445 + // CULPA DEL SERVIDOR!!
  446 + }
  447 + catch(InterruptedException e)
  448 + {
  449 +
  450 + }
  451 + catch(ExecutionException e)
  452 + {
  453 +
334 } 454 }
335 } 455 }
336 - else if (extTag[0].equals("#EXT-X-ENDLIST")){  
337 - if (expectSegment || expectList){ 456 + else if (extTag[0].equals("#EXT-X-ENDLIST"))
  457 + {
  458 + if (expectSegment || expectList)
  459 + {
338 throw new ErrorException("Final de llista no esperat!"); 460 throw new ErrorException("Final de llista no esperat!");
339 } 461 }
340 } 462 }
341 - else if (extTag[0].equals("#EXT-X-VERSION")){  
342 - //IGNORE 463 + else if (extTag[0].equals("#EXT-X-VERSION"))
  464 + {
  465 + // IGNORE
343 } 466 }
344 - else if (extTag[0].equals("#EXT-X-PLAYLIST-TYPE")){  
345 - //IGNORE 467 + else if (extTag[0].equals("#EXT-X-PLAYLIST-TYPE"))
  468 + {
  469 + // IGNORE
346 } 470 }
347 - else{ 471 + else
  472 + {
348 currentLine++; 473 currentLine++;
349 - throw new WarningException("Tag no implementat: " + extTag[0]); 474 + throw new WarningException("Tag no implementat: "
  475 + + extTag[0]);
350 } 476 }
351 } 477 }
352 - else{ 478 + else
  479 + {
353 String comment = line.substring(1); 480 String comment = line.substring(1);
354 - throw new InfoException("Comentari en linea " + currentLine++ + " " + comment); 481 + throw new InfoException("Comentari en linea "
  482 + + currentLine++ + " " + comment);
355 } 483 }
356 } 484 }
357 - else{  
358 - if (expectSegment){ 485 + else
  486 + {
  487 + if (expectSegment)
  488 + {
359 expectSegment = false; 489 expectSegment = false;
360 - try{  
361 - if(!line.startsWith("http://") && !line.startsWith("/")) 490 + try
  491 + {
  492 + if (!line.startsWith("http://")
  493 + && !line.startsWith("/"))
362 { 494 {
363 line = path + line; 495 line = path + line;
364 } 496 }
365 - else if(line.startsWith("/")) 497 + else if (line.startsWith("/"))
366 { 498 {
367 line = server + line; 499 line = server + line;
368 } 500 }
369 pls.getSegments().get(currentSegment).setURL(line); 501 pls.getSegments().get(currentSegment).setURL(line);
370 } 502 }
371 - catch (MalformedURLException e){ 503 + catch (MalformedURLException e)
  504 + {
372 throw new ErrorException(e.getMessage()); 505 throw new ErrorException(e.getMessage());
373 } 506 }
374 currentSegment++; 507 currentSegment++;
375 } 508 }
376 - else if (expectList){  
377 - //Descarregar llista i juntar les entrades amb les de la llista actual 509 + else if (expectList)
  510 + {
  511 + // Descarregar llista i juntar les entrades amb les de
  512 + // la llista actual
378 expectList = false; 513 expectList = false;
379 - Parser p = new Parser(line.substring(0, line.lastIndexOf("/") + 1), caller); 514 + Parser p = new Parser(line.substring(0, line.lastIndexOf("/") + 1), ctx);
380 Video newList; 515 Video newList;
381 - try{  
382 - newList = p.parseFile(download.doInBackground(line)).get(0).getLists().get(0); 516 + try
  517 + {
  518 + Descarrega download = new Descarrega(ctx);
  519 + download.execute(new URL(line));
  520 + newList = p.parseFile(download.get()).get(0).getLists().get(0);
383 pls.setMaxDuration(newList.getMaxDuration()); 521 pls.setMaxDuration(newList.getMaxDuration());
384 pls.setSequence(newList.getSequence()); 522 pls.setSequence(newList.getSequence());
385 - for (int i = 0; i < newList.getSegments().size(); i++){ 523 + for (int i = 0; i < newList.getSegments().size(); i++)
  524 + {
386 pls.getSegments().add(newList.getSegments().get(i)); 525 pls.getSegments().add(newList.getSegments().get(i));
387 } 526 }
388 } 527 }
389 - catch (IOException e){  
390 - // Nunca llegara aqui la cosa, y si lo hace ES CULPA DEL SERVIDOR!! 528 + catch (IOException e)
  529 + {
  530 + // Nunca llegara aqui la cosa, y si lo hace ES CULPA
  531 + // DEL SERVIDOR!!
  532 + }
  533 + catch(InterruptedException e)
  534 + {
  535 +
  536 + }
  537 + catch(ExecutionException e)
  538 + {
  539 +
391 } 540 }
392 } 541 }
393 - else{  
394 - throw new ErrorException("ERROR: String no esperat" + line); 542 + else
  543 + {
  544 + throw new ErrorException("ERROR: String no esperat"
  545 + + line);
395 } 546 }
396 } 547 }
397 } 548 }
src/com/upc/pbe/upcnews/ResourceAdapter.java
@@ -9,6 +9,7 @@ import android.view.View; @@ -9,6 +9,7 @@ import android.view.View;
9 import android.view.ViewGroup; 9 import android.view.ViewGroup;
10 import android.widget.ArrayAdapter; 10 import android.widget.ArrayAdapter;
11 import android.widget.ImageView; 11 import android.widget.ImageView;
  12 +import android.widget.RelativeLayout;
12 import android.widget.TextView; 13 import android.widget.TextView;
13 14
14 //Modificacio de l'Adapter d'Adnroid, creat al nostre gust per donar estil als elements de la ListView de directoris i arxius 15 //Modificacio de l'Adapter d'Adnroid, creat al nostre gust per donar estil als elements de la ListView de directoris i arxius
@@ -29,17 +30,20 @@ public class ResourceAdapter extends ArrayAdapter&lt;String&gt; { @@ -29,17 +30,20 @@ public class ResourceAdapter extends ArrayAdapter&lt;String&gt; {
29 public View getView(int position, View convertView, ViewGroup parent) { 30 public View getView(int position, View convertView, ViewGroup parent) {
30 TextView row; 31 TextView row;
31 ImageView rowImage; 32 ImageView rowImage;
  33 + RelativeLayout container;
32 34
33 - if (convertView == null) { 35 + if (convertView == null)
  36 + {
34 LayoutInflater inflater = ((Activity)context).getLayoutInflater(); 37 LayoutInflater inflater = ((Activity)context).getLayoutInflater();
35 - row = (TextView) inflater.inflate(R.layout.rowlayout, parent, false);  
36 - rowImage = (ImageView) inflater.inflate(R.layout.rowlayout, parent, false); 38 + container = (RelativeLayout) inflater.inflate(R.layout.rowlayout, parent, false);
37 } 39 }
38 - else {  
39 - row = (TextView) convertView;  
40 - rowImage = (ImageView) convertView; 40 + else
  41 + {
  42 + container = (RelativeLayout) convertView;
41 } 43 }
42 final String text = entries[position]; 44 final String text = entries[position];
  45 + row = (TextView) container.findViewById(R.id.rowTextView);
  46 + rowImage = (ImageView) container.findViewById(R.id.rowImageView);
43 row.setText(text); 47 row.setText(text);
44 //Si es un m3u8, posem el text en verd i l'icono de video 48 //Si es un m3u8, posem el text en verd i l'icono de video
45 if(text.endsWith(".m3u8")) { 49 if(text.endsWith(".m3u8")) {
@@ -52,6 +56,6 @@ public class ResourceAdapter extends ArrayAdapter&lt;String&gt; { @@ -52,6 +56,6 @@ public class ResourceAdapter extends ArrayAdapter&lt;String&gt; {
52 row.setTextColor(((Activity)context).getResources().getColor(R.color.BlueAndroid)); 56 row.setTextColor(((Activity)context).getResources().getColor(R.color.BlueAndroid));
53 rowImage.setImageResource(R.drawable.mediacontroller_ff_right); 57 rowImage.setImageResource(R.drawable.mediacontroller_ff_right);
54 } 58 }
55 - return row; 59 + return container;
56 } 60 }
57 } 61 }
58 \ No newline at end of file 62 \ No newline at end of file
src/com/upc/pbe/upcnews/UpcApp.java
@@ -15,8 +15,7 @@ public class UpcApp extends Application implements @@ -15,8 +15,7 @@ public class UpcApp extends Application implements
15 private SharedPreferences prefs; // Conjunt de preferencies de l'aplicacio 15 private SharedPreferences prefs; // Conjunt de preferencies de l'aplicacio
16 private String url = null; 16 private String url = null;
17 private String desc; 17 private String desc;
18 - private final static String localPath = Environment  
19 - .getExternalStorageDirectory().getPath() + "/UPC NEWS/"; 18 + private final static String localPath = Environment.getExternalStorageDirectory().getPath() + "/UPC NEWS/";
20 private HLS h; 19 private HLS h;
21 20
22 public String getLocalPath() { 21 public String getLocalPath() {
@@ -61,10 +60,4 @@ public class UpcApp extends Application implements @@ -61,10 +60,4 @@ public class UpcApp extends Application implements
61 public String getDesc() { 60 public String getDesc() {
62 return desc; 61 return desc;
63 } 62 }
64 -  
65 - public int getQuality() {  
66 - int qual = Integer.parseInt(prefs.getString("quality", "0"));  
67 -  
68 - return qual;  
69 - }  
70 } 63 }
71 \ No newline at end of file 64 \ No newline at end of file
src/com/upc/pbe/upcnews/VideoActivity.java
@@ -60,7 +60,7 @@ public class VideoActivity extends Activity { @@ -60,7 +60,7 @@ public class VideoActivity extends Activity {
60 video.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH); 60 video.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);
61 //Creem un gestor HLS, carreguem el video i iniciem la reproduccio 61 //Creem un gestor HLS, carreguem el video i iniciem la reproduccio
62 h = ((UpcApp)getApplication()).getHLS(); 62 h = ((UpcApp)getApplication()).getHLS();
63 - h.setDefQuality(((UpcApp)getApplication()).getQuality()); 63 + h.startDownloadManager(this);
64 h.loadVideo(); 64 h.loadVideo();
65 video.stopPlayback(); 65 video.stopPlayback();
66 video.setMediaController(mc); 66 video.setMediaController(mc);