SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
Programmation Mobile
Android
Rabie JABALLAH: jaballahrabie@gmail.com
Slim BENHAMMOUDA: slim.benhammouda@gmail.com
Files and storage
● Android can read/write files from two locations:
- internal and external storage
- both are persistent storage; data remains after power-
off/rebot
● internal storage : Built into device
- guaranteed to be present
- typically smaller (~1-4 gb)
- can’t be expanded or removed
- specific and private to each app
- wiped out when the app is uninstalled
Files and storage (2)
Android provides 3 ways to store data:
- preferences files
- Files
- databases
Preferences
● SharePreferences object can store permanent settings
and data for your app
- stores key/value pairs similar to a bundle or Intent
- pairs added to SharePreferences persist after shutdown/reboot
(unlike savedInstanceState bundles
● Two ways to use it:
- per-activity: getPreferences
- per-app: getSharedPreferences - most common use
sharedprefences example
● Saving preferences for the activity (in onPause, onStop):
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putInt("name", value);
prefsEditor.putString("name", value);
...
prefsEditor.apply(); // or commit();
● Loading preferences later (e.g. in onCreate):
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
int i = prefs.getInt("name", defaultValue);
String s = prefs.getString("name", "defaultValue");
...
Multiple preferences files
● you can call getSharedPreferences and
supply a file name if you want to have
multiple pref. files for the same activity:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
SharedPreferences prefs = getSharedPreferences (
"filename", MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putInt("name", value);
prefsEditor.putString("name", value);
...
prefsEditor.commit();
File and Streams
● java.io.File - Objects that represent a file or
directory
- methods: canRead, canWrite, create, delete, exists,
getName, getParent, getPath, isFile, isDirectory,
lastModified, lenght, listFiles, mkdir, mkdirs, renameTo
File and Streams (2)
● jave.io.InputStream, outputStream - Stream objects
represent flows of data bytes from/to a source or
destination
- could come from a file, network, database, memory,...
- Normally not directly used; they only include low-level
methods for reading/writing a byte (character) at a time from
the input
- instead, a stream is often passed as parameter to other
objects like java.util.Scanner, java.io.BufferedReader, java.io.
PrintStream to do the actual reading /writing
Using internal storage
● An activity has methods you can call to read/write files
- getFilesDir() - returns internal directory for your app
- getCacheDir() - returns a “temp” directory for scrap files
- getResources().openRawResource(R.raw.id) - read an
input file from res/raw/
- openFileInput(“name”, mode) - opens a file for reading
- openFileOutput(“name”, mode) - opens a file for writing
● You can use these to read/write files on the device
- many methods return standard java.io.File objects
- some return java.io.InputStream or OutputStream objects, which
can be used with standard classes like scanner, BufferedReader,
and PrintStream to read/write files (see java API)
External storage
● external storage : Card that is inserted into
the device (such as a MicroSD card)
- can be much larger than internal storage (~8-32 gb)
- can be removed or transferred to another device if
needed
- may not be present, depending on the device
- read/writable by other apps and users; not private to
your app
- not wiped when the app is uninstalled, except in certain
cases
External storage permission
● if your app needs to read/write the device’s external
storage, you must explicitly request permission to do so
in your app’s AndroidManifest.XML file
- On install, the user will be prompted to confirm your app
permissions
- No longer needed since Kitkat (Android 4.4)
<manifest ...>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
Using external storage
● Methods to read/write external storage :
- getExternalFilesDir(“name”) - returns “private” external directory
for your app with the given name
- Environment.getExternalStoragePublicDirectory(name) -
returns public directory for common files like photos, music, etc.
*pass constants for name such as Environment.DIRECTORY_ALARMS,
DIRECTORY_DCIM, DIRECTORY_DOWNLOADS, DIRECTORY_MOVIES,
DIRECTORY_MUSIC, DIRECTORY_NOTIFICATIONS,
DIRECTORY_PICTURES,
DIRECTORY_PODCASTS, DIRECTORY_RINGTONES
Using external storage (2)
● You can use to read/write files on the
external storage
- the above methods return standard java.io.File objects
- these can be used with standard classes like scanner,
BufferedReader, and PrintStream to read/write files (see
java API)
External storage example
// write short data to app-specific external storage
File outDir = getExternalFilesDir(null); // root dir
File outFile = new File(outDir, "example.txt");
PrintStream output = new PrintStream(outFile);
output.println("Hello, world!");
output.close();
// read list of pictures in external storage
File picsDir =
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
for (File file : picsDir.listFiles()) {
...
}
checking if storage is available
/* Checks if external storage is available
* for reading and writing */
public boolean isExternalStorageWritable() {
return Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState());
}
/* Checks if external storage is available
* for reading */
public boolean isExternalStorageReadable() {
return isExternalStorageWritable() ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(
Environment.getExternalStorageState());
}
Multithreads
● Each app has a single foreground thread
● All visual elements are on the main thread (also
known for UI thread)
● Don’t block the main thread !
● Don’t access the user interface from other
threads !
● We should use threads to access files since the
operation can be heavy
Multithreads (2)
● Standard Java concurrent programming: Thread,
Runnable, java.concurrent
● Android-specific background threads: AsyncTask
Accessing web service
● To read data from the web, first request the
INTERNETpermission in your AndroidManifest.
XML
<uses-permission
android:name=”android.permission.INTERNET” />
Accessing web service (2)
HttpURLConnection con = null;
InputStream is = null;
try {
String wsUrl = "http://my.web.service.url";
con = (HttpURLConnection) (new URL(wsUrl)).openConnection();
con.setRequestMethod("GET"); //it can be POST or PUT...
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
...
Accessing web service (3)
...
// read the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader
(is));
String line = null;
Accessing web service (4)
...
while ((line = br.readLine()) != null) {
buffer.append(line + "rn");
}
is.close();
con.disconnect();
result = buffer.toString();
}
catch (MalformedURLException e) { e.printStackTrace();}
catch (IOException e) { e.printStackTrace();}

Mais conteúdo relacionado

Mais procurados

Android datastorage
Android datastorageAndroid datastorage
Android datastorageKrazy Koder
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data StorageMingHo Chang
 
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?DicodingEvent
 
Eclipse Training - Standard Extension Points and APIs
Eclipse Training - Standard Extension Points and APIsEclipse Training - Standard Extension Points and APIs
Eclipse Training - Standard Extension Points and APIsLuca D'Onofrio
 
Ant_quick_guide
Ant_quick_guideAnt_quick_guide
Ant_quick_guideducquoc_vn
 
Sql grant, revoke, privileges and roles
Sql grant, revoke, privileges and rolesSql grant, revoke, privileges and roles
Sql grant, revoke, privileges and rolesVivek Singh
 
Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015Cindy Potvin
 
Yii in action
Yii in actionYii in action
Yii in actionKeaNy Chu
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android ApplicationMark Lester Navarro
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsTonny Madsen
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperGary Hockin
 
L0036 - Creating Views and Editors
L0036 - Creating Views and EditorsL0036 - Creating Views and Editors
L0036 - Creating Views and EditorsTonny Madsen
 
Create user database management security
Create user  database management securityCreate user  database management security
Create user database management securityGirija Muscut
 
L0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitL0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitTonny Madsen
 
JavaStates Simple Tutorial
JavaStates Simple TutorialJavaStates Simple Tutorial
JavaStates Simple TutorialLaurent Henocque
 

Mais procurados (20)

Android datastorage
Android datastorageAndroid datastorage
Android datastorage
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data Storage
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Persistences
PersistencesPersistences
Persistences
 
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
 
Eclipse Training - Standard Extension Points and APIs
Eclipse Training - Standard Extension Points and APIsEclipse Training - Standard Extension Points and APIs
Eclipse Training - Standard Extension Points and APIs
 
Ant_quick_guide
Ant_quick_guideAnt_quick_guide
Ant_quick_guide
 
Sql grant, revoke, privileges and roles
Sql grant, revoke, privileges and rolesSql grant, revoke, privileges and roles
Sql grant, revoke, privileges and roles
 
Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015
 
Drupal 8 Hooks
Drupal 8 HooksDrupal 8 Hooks
Drupal 8 Hooks
 
Yii in action
Yii in actionYii in action
Yii in action
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android Application
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard Views
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
L0036 - Creating Views and Editors
L0036 - Creating Views and EditorsL0036 - Creating Views and Editors
L0036 - Creating Views and Editors
 
Create user database management security
Create user  database management securityCreate user  database management security
Create user database management security
 
L0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitL0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget Toolkit
 
JavaStates Simple Tutorial
JavaStates Simple TutorialJavaStates Simple Tutorial
JavaStates Simple Tutorial
 
Local Storage
Local StorageLocal Storage
Local Storage
 

Destaque

Andcx formation-android-avance-creation-d-applications-complexes
Andcx formation-android-avance-creation-d-applications-complexesAndcx formation-android-avance-creation-d-applications-complexes
Andcx formation-android-avance-creation-d-applications-complexesCERTyou Formation
 
Angular 4 - ngfor -- Français
Angular 4  - ngfor -- FrançaisAngular 4  - ngfor -- Français
Angular 4 - ngfor -- FrançaisVERTIKA
 
Mobilization 2017: Don't lose your users because of endless quality issues
Mobilization 2017: Don't lose your users because of endless quality issuesMobilization 2017: Don't lose your users because of endless quality issues
Mobilization 2017: Don't lose your users because of endless quality issuesOlivier Destrebecq
 
Angular 4 - regles -- Français
Angular 4  - regles -- FrançaisAngular 4  - regles -- Français
Angular 4 - regles -- FrançaisVERTIKA
 
Algea - 04 - conclusion
Algea - 04 - conclusionAlgea - 04 - conclusion
Algea - 04 - conclusionYann Caron
 
Radio cognitive et intelligence artificielle
Radio cognitive et intelligence artificielleRadio cognitive et intelligence artificielle
Radio cognitive et intelligence artificiellebenouini rachid
 
Programmation Android - 00 - Présentation
Programmation Android - 00 - PrésentationProgrammation Android - 00 - Présentation
Programmation Android - 00 - PrésentationYann Caron
 
Traitement numérique des images - Projet Android "Virtual Pong" - Présentation
Traitement numérique des images - Projet Android "Virtual Pong" - PrésentationTraitement numérique des images - Projet Android "Virtual Pong" - Présentation
Traitement numérique des images - Projet Android "Virtual Pong" - PrésentationValentin Thirion
 
Conférence "Architecture Android" du 19 Mars 2013 par Mathias Seguy fondateur...
Conférence "Architecture Android" du 19 Mars 2013 par Mathias Seguy fondateur...Conférence "Architecture Android" du 19 Mars 2013 par Mathias Seguy fondateur...
Conférence "Architecture Android" du 19 Mars 2013 par Mathias Seguy fondateur...Mathias Seguy
 
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015Loïc Knuchel
 
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...Grégoire Arnould
 
01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)TECOS
 
Angular 4 - creer composants -- français
Angular 4  - creer composants -- françaisAngular 4  - creer composants -- français
Angular 4 - creer composants -- françaisVERTIKA
 
Support de la formation Android 5 , Avancé
Support de la formation Android 5 , Avancé Support de la formation Android 5 , Avancé
Support de la formation Android 5 , Avancé Alphorm
 
Meet up paris 13 of jun 2017
Meet up paris 13 of jun 2017Meet up paris 13 of jun 2017
Meet up paris 13 of jun 2017Jasmine Conseil
 

Destaque (20)

Andcx formation-android-avance-creation-d-applications-complexes
Andcx formation-android-avance-creation-d-applications-complexesAndcx formation-android-avance-creation-d-applications-complexes
Andcx formation-android-avance-creation-d-applications-complexes
 
Angular 4 - ngfor -- Français
Angular 4  - ngfor -- FrançaisAngular 4  - ngfor -- Français
Angular 4 - ngfor -- Français
 
Introduction gestion de projet
Introduction gestion de projetIntroduction gestion de projet
Introduction gestion de projet
 
Mobilization 2017: Don't lose your users because of endless quality issues
Mobilization 2017: Don't lose your users because of endless quality issuesMobilization 2017: Don't lose your users because of endless quality issues
Mobilization 2017: Don't lose your users because of endless quality issues
 
Angular 4 - regles -- Français
Angular 4  - regles -- FrançaisAngular 4  - regles -- Français
Angular 4 - regles -- Français
 
Algea - 04 - conclusion
Algea - 04 - conclusionAlgea - 04 - conclusion
Algea - 04 - conclusion
 
Radio cognitive et intelligence artificielle
Radio cognitive et intelligence artificielleRadio cognitive et intelligence artificielle
Radio cognitive et intelligence artificielle
 
Programmation Android - 00 - Présentation
Programmation Android - 00 - PrésentationProgrammation Android - 00 - Présentation
Programmation Android - 00 - Présentation
 
Traitement numérique des images - Projet Android "Virtual Pong" - Présentation
Traitement numérique des images - Projet Android "Virtual Pong" - PrésentationTraitement numérique des images - Projet Android "Virtual Pong" - Présentation
Traitement numérique des images - Projet Android "Virtual Pong" - Présentation
 
Initiation aux echecs
Initiation aux echecsInitiation aux echecs
Initiation aux echecs
 
Conférence "Architecture Android" du 19 Mars 2013 par Mathias Seguy fondateur...
Conférence "Architecture Android" du 19 Mars 2013 par Mathias Seguy fondateur...Conférence "Architecture Android" du 19 Mars 2013 par Mathias Seguy fondateur...
Conférence "Architecture Android" du 19 Mars 2013 par Mathias Seguy fondateur...
 
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
 
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...
 
Mta
MtaMta
Mta
 
Les virus
Les virusLes virus
Les virus
 
Montage video
Montage videoMontage video
Montage video
 
01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)
 
Angular 4 - creer composants -- français
Angular 4  - creer composants -- françaisAngular 4  - creer composants -- français
Angular 4 - creer composants -- français
 
Support de la formation Android 5 , Avancé
Support de la formation Android 5 , Avancé Support de la formation Android 5 , Avancé
Support de la formation Android 5 , Avancé
 
Meet up paris 13 of jun 2017
Meet up paris 13 of jun 2017Meet up paris 13 of jun 2017
Meet up paris 13 of jun 2017
 

Semelhante a 03 programmation mobile - android - (stockage, multithreads, web services)

Assets, files, and data parsing
Assets, files, and data parsingAssets, files, and data parsing
Assets, files, and data parsingAly Arman
 
Android File Management Presentation.pptx
Android File Management Presentation.pptxAndroid File Management Presentation.pptx
Android File Management Presentation.pptxvuqaxuly
 
Android File Management Presentation.pptx
Android File Management Presentation.pptxAndroid File Management Presentation.pptx
Android File Management Presentation.pptxvuqaxuly
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Khaled Anaqwa
 
Basic linux architecture
Basic linux architectureBasic linux architecture
Basic linux architectureRohit Kumar
 
Android session 4-behestee
Android session 4-behesteeAndroid session 4-behestee
Android session 4-behesteeHussain Behestee
 
EuroPython 2015 - Storing files for the web is not as straightforward as you ...
EuroPython 2015 - Storing files for the web is not as straightforward as you ...EuroPython 2015 - Storing files for the web is not as straightforward as you ...
EuroPython 2015 - Storing files for the web is not as straightforward as you ...Alessandro Molina
 
Building File Systems with FUSE
Building File Systems with FUSEBuilding File Systems with FUSE
Building File Systems with FUSEelliando dias
 
Lamp1
Lamp1Lamp1
Lamp1Reka
 
Lamp
LampLamp
LampReka
 

Semelhante a 03 programmation mobile - android - (stockage, multithreads, web services) (20)

Assets, files, and data parsing
Assets, files, and data parsingAssets, files, and data parsing
Assets, files, and data parsing
 
Memory management
Memory managementMemory management
Memory management
 
Android File Management Presentation.pptx
Android File Management Presentation.pptxAndroid File Management Presentation.pptx
Android File Management Presentation.pptx
 
Android File Management Presentation.pptx
Android File Management Presentation.pptxAndroid File Management Presentation.pptx
Android File Management Presentation.pptx
 
Storage 8
Storage   8Storage   8
Storage 8
 
Android-data storage in android-chapter21
Android-data storage in android-chapter21Android-data storage in android-chapter21
Android-data storage in android-chapter21
 
Man-In-The-Disk
Man-In-The-DiskMan-In-The-Disk
Man-In-The-Disk
 
Linux file
Linux fileLinux file
Linux file
 
MA DHARSH.pptx
MA DHARSH.pptxMA DHARSH.pptx
MA DHARSH.pptx
 
Edubooktraining
EdubooktrainingEdubooktraining
Edubooktraining
 
Lab4 - android
Lab4 - androidLab4 - android
Lab4 - android
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)
 
Basic linux architecture
Basic linux architectureBasic linux architecture
Basic linux architecture
 
Android session 4-behestee
Android session 4-behesteeAndroid session 4-behestee
Android session 4-behestee
 
EuroPython 2015 - Storing files for the web is not as straightforward as you ...
EuroPython 2015 - Storing files for the web is not as straightforward as you ...EuroPython 2015 - Storing files for the web is not as straightforward as you ...
EuroPython 2015 - Storing files for the web is not as straightforward as you ...
 
Building File Systems with FUSE
Building File Systems with FUSEBuilding File Systems with FUSE
Building File Systems with FUSE
 
Ppt
PptPpt
Ppt
 
Lamp1
Lamp1Lamp1
Lamp1
 
Lamp1
Lamp1Lamp1
Lamp1
 
Lamp
LampLamp
Lamp
 

Mais de TECOS

Bouhamed vuejs-meetup-tecos
Bouhamed vuejs-meetup-tecosBouhamed vuejs-meetup-tecos
Bouhamed vuejs-meetup-tecosTECOS
 
D3 js-last
D3 js-lastD3 js-last
D3 js-lastTECOS
 
Summer internship
Summer internshipSummer internship
Summer internshipTECOS
 
Mohamed bouhamed - ccna2
Mohamed bouhamed  - ccna2Mohamed bouhamed  - ccna2
Mohamed bouhamed - ccna2TECOS
 
Mohamed bouhamed - ccna1
Mohamed bouhamed  -  ccna1Mohamed bouhamed  -  ccna1
Mohamed bouhamed - ccna1TECOS
 
Mobile certified
Mobile certifiedMobile certified
Mobile certifiedTECOS
 
Analytics certified
Analytics certifiedAnalytics certified
Analytics certifiedTECOS
 
Ad words certified
Ad words certifiedAd words certified
Ad words certifiedTECOS
 
Télémétrie d’openstack
Télémétrie d’openstackTélémétrie d’openstack
Télémétrie d’openstackTECOS
 
cloudu certification
cloudu certificationcloudu certification
cloudu certificationTECOS
 
Internship report
Internship reportInternship report
Internship reportTECOS
 
Gsm presntation
Gsm presntationGsm presntation
Gsm presntationTECOS
 
Td gsm iit
Td gsm iitTd gsm iit
Td gsm iitTECOS
 
Complément réseaux informatiques
Complément réseaux informatiquesComplément réseaux informatiques
Complément réseaux informatiquesTECOS
 
Cours réseauxs gsm
Cours réseauxs gsmCours réseauxs gsm
Cours réseauxs gsmTECOS
 
Cours sécurité 2_asr
Cours sécurité 2_asrCours sécurité 2_asr
Cours sécurité 2_asrTECOS
 
chapitre 1
chapitre 1chapitre 1
chapitre 1TECOS
 
Serveur web iit_asr_p2i
Serveur web iit_asr_p2iServeur web iit_asr_p2i
Serveur web iit_asr_p2iTECOS
 
Examen
Examen Examen
Examen TECOS
 
Gsm presntation
Gsm presntationGsm presntation
Gsm presntationTECOS
 

Mais de TECOS (20)

Bouhamed vuejs-meetup-tecos
Bouhamed vuejs-meetup-tecosBouhamed vuejs-meetup-tecos
Bouhamed vuejs-meetup-tecos
 
D3 js-last
D3 js-lastD3 js-last
D3 js-last
 
Summer internship
Summer internshipSummer internship
Summer internship
 
Mohamed bouhamed - ccna2
Mohamed bouhamed  - ccna2Mohamed bouhamed  - ccna2
Mohamed bouhamed - ccna2
 
Mohamed bouhamed - ccna1
Mohamed bouhamed  -  ccna1Mohamed bouhamed  -  ccna1
Mohamed bouhamed - ccna1
 
Mobile certified
Mobile certifiedMobile certified
Mobile certified
 
Analytics certified
Analytics certifiedAnalytics certified
Analytics certified
 
Ad words certified
Ad words certifiedAd words certified
Ad words certified
 
Télémétrie d’openstack
Télémétrie d’openstackTélémétrie d’openstack
Télémétrie d’openstack
 
cloudu certification
cloudu certificationcloudu certification
cloudu certification
 
Internship report
Internship reportInternship report
Internship report
 
Gsm presntation
Gsm presntationGsm presntation
Gsm presntation
 
Td gsm iit
Td gsm iitTd gsm iit
Td gsm iit
 
Complément réseaux informatiques
Complément réseaux informatiquesComplément réseaux informatiques
Complément réseaux informatiques
 
Cours réseauxs gsm
Cours réseauxs gsmCours réseauxs gsm
Cours réseauxs gsm
 
Cours sécurité 2_asr
Cours sécurité 2_asrCours sécurité 2_asr
Cours sécurité 2_asr
 
chapitre 1
chapitre 1chapitre 1
chapitre 1
 
Serveur web iit_asr_p2i
Serveur web iit_asr_p2iServeur web iit_asr_p2i
Serveur web iit_asr_p2i
 
Examen
Examen Examen
Examen
 
Gsm presntation
Gsm presntationGsm presntation
Gsm presntation
 

03 programmation mobile - android - (stockage, multithreads, web services)

  • 1. Programmation Mobile Android Rabie JABALLAH: jaballahrabie@gmail.com Slim BENHAMMOUDA: slim.benhammouda@gmail.com
  • 2. Files and storage ● Android can read/write files from two locations: - internal and external storage - both are persistent storage; data remains after power- off/rebot ● internal storage : Built into device - guaranteed to be present - typically smaller (~1-4 gb) - can’t be expanded or removed - specific and private to each app - wiped out when the app is uninstalled
  • 3. Files and storage (2) Android provides 3 ways to store data: - preferences files - Files - databases
  • 4. Preferences ● SharePreferences object can store permanent settings and data for your app - stores key/value pairs similar to a bundle or Intent - pairs added to SharePreferences persist after shutdown/reboot (unlike savedInstanceState bundles ● Two ways to use it: - per-activity: getPreferences - per-app: getSharedPreferences - most common use
  • 5. sharedprefences example ● Saving preferences for the activity (in onPause, onStop): SharedPreferences prefs = getPreferences(MODE_PRIVATE); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putInt("name", value); prefsEditor.putString("name", value); ... prefsEditor.apply(); // or commit(); ● Loading preferences later (e.g. in onCreate): SharedPreferences prefs = getPreferences(MODE_PRIVATE); int i = prefs.getInt("name", defaultValue); String s = prefs.getString("name", "defaultValue"); ...
  • 6. Multiple preferences files ● you can call getSharedPreferences and supply a file name if you want to have multiple pref. files for the same activity: SharedPreferences prefs = getPreferences(MODE_PRIVATE); SharedPreferences prefs = getSharedPreferences ( "filename", MODE_PRIVATE); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putInt("name", value); prefsEditor.putString("name", value); ... prefsEditor.commit();
  • 7. File and Streams ● java.io.File - Objects that represent a file or directory - methods: canRead, canWrite, create, delete, exists, getName, getParent, getPath, isFile, isDirectory, lastModified, lenght, listFiles, mkdir, mkdirs, renameTo
  • 8. File and Streams (2) ● jave.io.InputStream, outputStream - Stream objects represent flows of data bytes from/to a source or destination - could come from a file, network, database, memory,... - Normally not directly used; they only include low-level methods for reading/writing a byte (character) at a time from the input - instead, a stream is often passed as parameter to other objects like java.util.Scanner, java.io.BufferedReader, java.io. PrintStream to do the actual reading /writing
  • 9. Using internal storage ● An activity has methods you can call to read/write files - getFilesDir() - returns internal directory for your app - getCacheDir() - returns a “temp” directory for scrap files - getResources().openRawResource(R.raw.id) - read an input file from res/raw/ - openFileInput(“name”, mode) - opens a file for reading - openFileOutput(“name”, mode) - opens a file for writing ● You can use these to read/write files on the device - many methods return standard java.io.File objects - some return java.io.InputStream or OutputStream objects, which can be used with standard classes like scanner, BufferedReader, and PrintStream to read/write files (see java API)
  • 10. External storage ● external storage : Card that is inserted into the device (such as a MicroSD card) - can be much larger than internal storage (~8-32 gb) - can be removed or transferred to another device if needed - may not be present, depending on the device - read/writable by other apps and users; not private to your app - not wiped when the app is uninstalled, except in certain cases
  • 11. External storage permission ● if your app needs to read/write the device’s external storage, you must explicitly request permission to do so in your app’s AndroidManifest.XML file - On install, the user will be prompted to confirm your app permissions - No longer needed since Kitkat (Android 4.4) <manifest ...> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ... </manifest>
  • 12. Using external storage ● Methods to read/write external storage : - getExternalFilesDir(“name”) - returns “private” external directory for your app with the given name - Environment.getExternalStoragePublicDirectory(name) - returns public directory for common files like photos, music, etc. *pass constants for name such as Environment.DIRECTORY_ALARMS, DIRECTORY_DCIM, DIRECTORY_DOWNLOADS, DIRECTORY_MOVIES, DIRECTORY_MUSIC, DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES
  • 13. Using external storage (2) ● You can use to read/write files on the external storage - the above methods return standard java.io.File objects - these can be used with standard classes like scanner, BufferedReader, and PrintStream to read/write files (see java API)
  • 14. External storage example // write short data to app-specific external storage File outDir = getExternalFilesDir(null); // root dir File outFile = new File(outDir, "example.txt"); PrintStream output = new PrintStream(outFile); output.println("Hello, world!"); output.close(); // read list of pictures in external storage File picsDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); for (File file : picsDir.listFiles()) { ... }
  • 15. checking if storage is available /* Checks if external storage is available * for reading and writing */ public boolean isExternalStorageWritable() { return Environment.MEDIA_MOUNTED.equals( Environment.getExternalStorageState()); } /* Checks if external storage is available * for reading */ public boolean isExternalStorageReadable() { return isExternalStorageWritable() || Environment.MEDIA_MOUNTED_READ_ONLY.equals( Environment.getExternalStorageState()); }
  • 16. Multithreads ● Each app has a single foreground thread ● All visual elements are on the main thread (also known for UI thread) ● Don’t block the main thread ! ● Don’t access the user interface from other threads ! ● We should use threads to access files since the operation can be heavy
  • 17. Multithreads (2) ● Standard Java concurrent programming: Thread, Runnable, java.concurrent ● Android-specific background threads: AsyncTask
  • 18. Accessing web service ● To read data from the web, first request the INTERNETpermission in your AndroidManifest. XML <uses-permission android:name=”android.permission.INTERNET” />
  • 19. Accessing web service (2) HttpURLConnection con = null; InputStream is = null; try { String wsUrl = "http://my.web.service.url"; con = (HttpURLConnection) (new URL(wsUrl)).openConnection(); con.setRequestMethod("GET"); //it can be POST or PUT... con.setDoInput(true); con.setDoOutput(true); con.connect(); ...
  • 20. Accessing web service (3) ... // read the response StringBuffer buffer = new StringBuffer(); is = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader (is)); String line = null;
  • 21. Accessing web service (4) ... while ((line = br.readLine()) != null) { buffer.append(line + "rn"); } is.close(); con.disconnect(); result = buffer.toString(); } catch (MalformedURLException e) { e.printStackTrace();} catch (IOException e) { e.printStackTrace();}