App settings and file storage programming overview (Android versus Windows Store apps)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Learn about key similarities and differences between app settings and file storage programming models for Android and Windows Store apps.

Introduction

Most apps need some way to save info about their state. Apps typically save their state info by using some kind of storage either within the device or hosted in a cloud service. App state includes data about the app's configuration, reference info, and transactional info. This is typically in the form of name-value pairs, private app-specific data files, and end-user files such as pictures, videos, and music.

Top

App settings

Apps typically need some type of configuration settings to control the apps' behaviors. Examples of this include the name of a data file or the URL to an external web service that an app relies on. App settings are private to each app and fit well into the name-value storage models provided by both Android and Windows Store apps. Android names an app's private storage as Internal Storage. This separates it from External Storage, which can be accessed by multiple Android apps.

Android apps: app setting storage

The following code snippet example shows storing name-value pair inside of a Settings.txt file in Internal Storage.

SharedPreferences _appSettings = this.getSharedPreferences("Settings.txt", 0);
SharedPreferences.Editor editor = _appSettings.edit();
editor.putString("datafilename", "testdata.txt");
editor.commit();

Windows Store apps: app settings storage

Windows Store app storage is managed through the ApplicationData class that includes not only name-value pair storage but also app-specific file management through the LocalSettings and LocalFolder properties, respectively. In addition to the app's local private storage, the Windows Runtime offers similar classes for managing app-specific remote storage if the end user signs in to Windows 8 with a Microsoft account. The LocalSettings property also enables storage of composite data in addition to name-value pairs. The following is a code snippet example for the LocalSettings property.

ApplicationDataContainer lc = ApplicationData.Current.LocalSettings;
lc["datafilename"] = "tesdata.txt";
ApplicationDataCompositeValue adcv = new ApplicationDataCompositeValue();
adcv["name"] = "John";
adcv["location"] = "Chicago";
lc.Values["userattributes"] = adcv;

Top

App files

Apps can store private data files that are downloaded along with the app or that are updated while the app is being used. These files include files such as SQLite databases, XML files, app-specific images, and audio files. Both Android and the Windows Runtime have APIs for doing file input/output (I/O) in private storage.

Android apps: app file storage

The following code snippet example shows storing a testdata.txt file in an app's private directory.

String data = "<data>...</data>";
FileOutputStream stream = openFileOutput("testdata.txt", Context.MODE_PRIVATE);
stream.write(data.getBytes());
stream.close();

If needed, directories can be created by using the Activity.getDir and File.createNewFile APIs in Android.

Windows Store apps: app file storage

All Windows Runtime I/O calls are asynchronous and require the use of the await keyword for Windows Store apps. These calls return a generic Task class that, when awaited, suspends the method's progress and sends control back to the caller. This reduces the complexity around writing callback handlers for transferring app state from handlers to the app's main logic. Following is a code snippet example showing this in practice.

StorageFolder lf = ApplicationData.Current.LocalFolder;
String data = "<data>...</data>";
StorageFile dataFile =
    await lf.CreateFileAsync("testdata.txt", CreateCollisionOption.ReplaceExisting);
if (dataFile!=null)
    await FileIO.WriteTextAsync(dataFile, data);

In Windows Store apps, the user's Downloads folder is partitioned for each app by the package family (which is specified in each app's manifest). In Android, the Downloads folder is a well-known folder that can be read from, and written to, all Android apps with a single WRITE_EXTERNAL_STORAGE permission.

The following code snippet example accesses the Downloads folder from a Windows Store app.

StorageFile dataFile = await Windows.Storage.DownloadsFolder.CreateFileAsync("dataFile.txt");
await FileIO.WriteTextAsync(dataFile, "sample data");

Top

External file I/O

Apps can read from, and write to, well-known shared folders containing files such as music, pictures, and videos.

Android apps: external file storage

Apps can access external file storage locations for downloads, videos, music, and pictures by calling the Activity.getExternalFilesDir method with the relevant string constant as an argument from the android.os.Enviroment class. For example, getExternalFilesDir(Environment.DIRECTORY_PICTURES) gets a reference to the pictures directory to work with files by using java.io. As of the date that this article was published, all directories in external storage are accessible to all apps for reading and writing after the WRITE_EXTERNAL_STORAGE permission is specified in an app's manifest.

Here's a code snippet example that shows how a file can be created in an external storage location.

String data = "<data>...</data>";
String dir = getExternalFilesDir(null);
File dataFile = new File(dir, "datafile.txt");
OutputStream stream = new FileOutputStream(dataFile);
stream.write(data.getBytes());
stream.close();

Here's an Android code snippet example for accessing the pictures directory.

String dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File photo = new File(dir, "SeattleSkyLine.png");

Windows Store apps: external file storage

The Windows Runtime enables apps to do file I/O against well-known folders like Music, Pictures, and Videos. Apps need to declare their folder access needs in their manifest for each of these well-known folders through the <capabilities> tag with one <capabiltity> tag for each target folder. Windows Store apps can only access these well-known folders and the private directories discussed previously. Well-known folders are accessed through the KnownFolders class. The Windows Runtime allows richer access to these well-known folders compared to the single-permission access model for Android. Also, all well-known folders in Windows 8 are user-specific. In Android there is no notion of a current user, so all well-known folders are shared across the system.

The following code snippet sample shows creating a document in the user's Pictures folder.

StorageFolder storageFolder = Windows.Storage.KnownFolders.PicturesLibrary;
StorageFile file = await storageFolder.CreateFileAsync("SeattleSkyline.png",
   CreationCollisionOption.ReplaceExisting);

When using the Microsoft Visual Studio graphical editor instead of the XML text editor to edit a manifest, use the Capabilities tab to specify the Pictures Library capability

The Windows Runtime has APIs for downloading and uploading large amounts of data to external storage through the BackgroundTransfer namespace. The BackgroundDownloader and BackgroundUploader classes are among many that are designed to transfer large files (such as videos and photos) over the Internet. These objects run as a background tasks, which the Windows Runtime can suspend and restart as needed to complete downloads and uploads.

The following code snippet example shows how to use the BackgroundDownloader class to download an image file from the Internet.

StorageFile faviconFile;
try {
    faviconFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
        "bing.ico", CreationCollisionOption.GenerateUniqueName);
}
catch {}

BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation downloadOp =
    downloader.CreateDownload(new Uri(@"https://bing.com/favicon.ico"), faviconFile);

await downloadOp.StartAsync();

For the preceding code to work, the app's manifest must specify the Internet Client and Pictures Library capabilities, as shown in this manifest code snippet example.

<Capability Name="internetClient" />
<Capability Name="picturesLibary" />

Other well-known folders like Music and Videos follow similar patterns.

Top