És un sistema bàsic que proporciona Android per guardar dades bàsiques de preferències (o similar) en una aplicació Android. Els valors s'emmagatzemen com a parelles clau-valor ((key-value pairs).
NOTA: Sense que sigui exactament el mateix però com a comparativa "pedagògica" podem veure les preferències com quelcom similar a les variables de sessió en programació web. http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
Normalment amb les preferències farem dos operacions, establir-les o obtenir-les. Es solen obtenir les preferències al mètode OnCreate:
@Override protected void onCreate(Bundle state){ super.onCreate(state); . . . // Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); }
i per establir les preferències s'utilitza una clase especial anomenada Editor:
// We need an Editor object to make preference changes. // All objects are from android.context.Context SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); // Commit the edits! editor.commit();
Podeu consultar diversos exemples:
Recursos:
En temps de compilació es posible proveir de fitxers a la vostra aplicació colocant-los a la carpeta:
res/raw
Aquests recursos són conegut com a Recursos crus (raw resources).
Aquests fitxer es poden obrir amb:
openRawResource()
On openRawResource() té la següent signatura.
public InputStream openRawResource (int id, TypedValue value) Throws Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
On:
NOTA: només es pot utilitzaar en recursos on cada recurs té un nom de fitxer i no pas en recursos com els strings
El Resource Id normalment és:
R.raw.<filename>
Aquest mètode retorna un InputStream.
IMPORTANT: Els recursos crus poden ser llegit però no modificats
Vegeu també:
Si s'utilitza Emmagatzemament intern (aka Internal Storage ) aleshores des dades es guarden a la memoria del dispositiu (normalment una memoria flash integrada).
Llegir un fitxer d'entrada
String FILENAME = "hello_file"; String string = "hello world!"; FileInputStream fis = openFileInput(FILENAME, Context.MODE_PRIVATE); fos.read(); fos.close();
IMPORTANT: Cal tenir en compte que el mètode openFileInput només es pot aplicar dins d'activitats Android!
IMPORTANT: El nom del fitxer no pot tenir separadors de camí (path separators com per exemple /)
Vegeu també FileInputStream.
Escriure a un fitxer de sortida
Un exemple:
String FILENAME = "hello_file"; String string = "hello world!"; FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close();
IMPORTANT: El codi anterior s'ha d'executar a una activitat Android
La forma de treballar en fitxers és similar a Java, s'utilitzen Streams Java, de fet a l'exemple utilitzem un FileOutputStream. El mètode més important és el mètode:
openFileOutput
L'API Android el defineix de la següent manera
FileOutputStream openFileOutput(String name, int mode) Open a private file associated with this Context's application package for writing.
On:
IMPORTANT: el nom del fitxer no pot tenir separadors de camí (path separators com per exemple /)
Per tant es tracta d'un fitxer privat de l'aplicació (no és accesible no per a l'usuari), que es guarda al context de l'aplicació.
Recursos:
TODO:
El emmagatzematge extern (aka External Storage ) serveix per guardar dades públiques que s'emmagatzemen a un memòria compartida externa.
Tots els dispositius compatibles amb Android suporten una "memòria externa" que sol ser un medi d'emmagatzemament removible com per exemple una targeta SD, però cal tenir en compte que també pot ser no removible (memoria SD interna).
Els fitxers que es guarden a la memoria externa són accesibles per tothom.
TODO: It's possible that a device using a partition of the internal storage for the external storage may also offer an SD card slot. In this case, the SD card is not part of the external storage and your app cannot access it (the extra storage is intended only for user-provided media that the system scans).
NOTA: Cal tenir en compte que la memòria externa pot deixar d'estar disponible si l'usuari munta la SD card o la treu del sistema.
com comprovar si està disponible o no la memòria externa
El primer mètode que sempre cal cridar és:
getExternalStorageState()
per tal de comprovar si està disponible o no. Un exemple:
boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; }
Accedir als fitxers de la memòria externa:
A partir de la versió API Level 8 cal utilitzar:
getExternalFilesDir()
La descripció a l'API Java és:
File getExternalFilesDir(String type) Returns the absolute path to the directory on the external filesystem (that is somewhere on Environment.getExternalStorageDirectory()) where the application can place persistent files it owns.
Per tal d'obrir un fitxer, on:
En dispositius amb múltiples usuaris (tal i com ho gestiona el UserManager), cada usuari té el seu external storage independent de la resta d'usuaris (isolat). Les aplicaciones només tenen accés als external storages de cada usuari.
Un exemple de codi:
void createExternalStoragePrivateFile() { // Create a path where we will place our private file on external // storage. File file = new File(getExternalFilesDir(null), "DemoFile.jpg"); try { // Very simple code to copy a picture from the application's // resource into the external file. Note that this code does // no error checking, and assumes the picture is small (does not // try to copy it in chunks). Note that if external storage is // not currently mounted this will silently fail. InputStream is = getResources().openRawResource(R.drawable.balloons); OutputStream os = new FileOutputStream(file); byte[] data = new byte[is.available()]; is.read(data); os.write(data); is.close(); os.close(); } catch (IOException e) { // Unable to create file, likely because external storage is // not currently mounted. Log.w("ExternalStorage", "Error writing " + file, e); } } void deleteExternalStoragePrivateFile() { // Get path for the file on external storage. If external // storage is not currently mounted this will fail. File file = new File(getExternalFilesDir(null), "DemoFile.jpg"); if (file != null) { file.delete(); } }
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external // storage is not currently mounted this will fail. File file = new File(getExternalFilesDir(null), "DemoFile.jpg"); if (file != null) { return file.exists(); } return false;
}
Amb API Level 7 o inferior:
getExternalStorageDirectory()
Que obre el root del storage extern. es pot utilitzar la carpeta:
/Android/data/<package_name>/files/
On:
Hiding your files from the Media Scanner
Include an empty file named .nomedia in your external files directory (note the dot prefix in the filename). This will prevent Android's media scanner from reading your media files and including them in apps like Gallery or Music. Saving files that should be shared
If you want to save files that are not specific to your application and that should not be deleted when your application is uninstalled, save them to one of the public directories on the external storage. These directories lay at the root of the external storage, such as Music/, Pictures/, Ringtones/, and others.
In API Level 8 or greater, use getExternalStoragePublicDirectory(), passing it the type of public directory you want, such as DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES, or others. This method will create the appropriate directory if necessary.
If you're using API Level 7 or lower, use getExternalStorageDirectory() to open a File that represents the root of the external storage, then save your shared files in one of the following directories:
Music/ - Media scanner classifies all media found here as user music. Podcasts/ - Media scanner classifies all media found here as a podcast. Ringtones/ - Media scanner classifies all media found here as a ringtone. Alarms/ - Media scanner classifies all media found here as an alarm sound. Notifications/ - Media scanner classifies all media found here as a notification sound. Pictures/ - All photos (excluding those taken with the camera). Movies/ - All movies (excluding those taken with the camcorder). Download/ - Miscellaneous downloads.
Saving cache files
If you're using API Level 8 or greater, use getExternalCacheDir() to open a File that represents the external storage directory where you should save cache files. If the user uninstalls your application, these files will be automatically deleted. However, during the life of your application, you should manage these cache files and remove those that aren't needed in order to preserve file space.
If you're using API Level 7 or lower, use getExternalStorageDirectory() to open a File that represents the root of the external storage, then write your cache data in the following directory:
/Android/data/<package_name>/cache/
The <package_name> is your Java-style package name, such as "com.example.android.app".
Recursos:
Store structured data in a private database.
Vegeu Android bundle i també Parcel
Store data on the web with your own network server.
Vegeu Android HTTP