The Android File System • Onboard: Linux Architecture • User privileges – Initially quite limited; some directories hidden – Rooting gives users super user access o Procedure is different for different devices o Destroying the operation of the device: bricking • Onboard data: Applications have their reserved storage areas (sandbox) • External data – SD card or USB connection – Public shared: /mnt/sdcard/ – Writing to external storage has no security protection
61
Embed
The Android File System Onboard: Linux Architecture User privileges – Initially quite limited; some directories hidden – Rooting gives users super user.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
The Android File System• Onboard: Linux Architecture• User privileges
– Initially quite limited; some directories hidden– Rooting gives users super user access
o Procedure is different for different deviceso Destroying the operation of the device: bricking
• Onboard data: Applications have their reserved storage areas (sandbox)
• External data– SD card or USB connection– Public shared: /mnt/sdcard/– Writing to external storage has no security protection
Managing Data (Alternatives)• Application Direct Access: Read only from res/raw or assets directories• Web-based: Interact through web-URLs to access cloud-based data• Direct File I/O: Read/write files onboard or on SD cards
– Use Standard Java stream and Random Access File classes– Restriction: Onboard file I/O restricted to application sandbox– Restriction: SD card writes requires access permission
• Preferences: Key/Value pairs of data• Database Tables: Use the built-in SQL-Lite database facility• Increase functionality:
– Content Providers: expose data to other applications– Services: background processes that run detached from any view
Application Direct Access• Static application files
– Custom codecs that are not widely supported– XML-based configuration data
• Store either in res/raw or in assets– res/raw enables creating sub-directories for specific device configurations– Files stored either in res/raw or in assets are not pre-compiled by Android– Files stored directly in the application are read-only and cannot be modified– Access using standard Java I/O operations
InputStream is = app.getResources().openRawResource(R.raw.foo); in = BufferedReader in = new BufferedReader(new InputStreamReader(is)));
InputStream rawRes = context.getAssets().open(“foo.bar"); Reader r = new BufferedReader(new InputStreamReader(rawRes, "UTF8"));
Note: Use lower case alphanumerics to name files in res/raw
int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = httpConnection.getInputStream();
processStream(in); // Use standard Java DOM parsing classes}
IntentFilter f = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));registerReceiver(receiver, f); }BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent)
{ String id = DownloadManager.EXTRA_DOWNLOAD_ID; long[] references = intent.getLongArrayExtra(id); // Array of
• To designate location which shares with music playersrequest.setDistinationInExternalPublicDir
(Environment.DIRECTORY_MUSIC, fileName);
Note: We cannot download to internal storage using DownloadManager
SD Card File IO• SD Card path: getExternalStorageDirectory()• How: Use standard Java File I/O• Notes:
– Manifest: "android.permission.WRITE_EXTERNAL_STORAGE"– Application manifests can set preference to SD Card installation– Check SD Availability in Java:
• Convention: write to /Android/data/<package_name>/files/• Example
File sdCard = Environment.getExternalStorageDirectory();File dir = new File (sdcard.getAbsolutePath()
+ " /Android/data/<package_name>/files/ ");dir.mkdirs(); // Make directories with missing parents.File file = new File(dir, "filename"); // Instantiate a file objectFileOutputStream f = new FileOutputStream(file); // Open for writing
Writing to Internal Storage• Writing to internal storage
– Each application has a designated directory to which to write files– There is a maximum storage amount, varying per device– Flags exist to control inter-application access
• MODE_PRIVATE - No access for other applications • MODE_WORLD_READABLE - Read access for other applications • MODE_WORLD_WRITABLE - Write access for other applications • MODE_WORLD_READABLE | MODE_WORLD_WRITABLE - Read / Write access
• Open file for writing new BufferedWriter(
new OutputStreamWriter(openFileOutput(fileName, MODE_PRIVATE)));
Onboard File I/O• Write to a designated place for each application
– Where: /data/data/package/files/ using onboard storage– How: Use standard java.io classes, with relative, not absolute, paths– Applications can:
o Write into its application directoryo Create subdirectorieso Give read/write permissions to other applications
• Android Helper classes in the Context object– getDir(String fileName, int permissions): Creates or access directory– getFilesDir(): Get absolute path to application directory– getCacheDir(): Get non-permanent temporary storage directory– openFileInput(String fileName): Open a file for input– openFileOutput(String fileName, int permissions): Create a new file
Note: There is also a sharedPreferences directory for preferences, a databases directory for SQLite tables, and a cache directory
Copy File from Serverpublic void DownloadFile(String fileURL, String fileName) { try { HttpURLConnection c = (HttpURLConnection) fileURL.openConnection();
c.setRequestMethod("GET");c.setDoOutput(false); // Tru for “POST” with intent to send to serverc.connect(); // Establish connection with serverInputStream in = c.getInputStream(); // Ready to read
File root = Environment.getExternalFilesDir(null); // Application area// Prepare output streamFileOutputStream out = new FileOutputStream(new File(root, fileName)); byte[] buffer = new byte[1024];int len = 0; // Note the buffer overflow possibilitywhile ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } // Write
Notes:1.puts can be chained: editor.putInt(“intKey”, 22).putLong(“LongKey”, 0);2.editor.apply() works asynchronously, editor.commit() is synchronous3.editor.clear() erases all of the preference keys4.editor.remove(“Key”) deletes a preference5.Shared preferences use a file name for multi-activity sharing
Preference Views
• Preference Screen The view on the left View on the right appears
When the user clicks after preference screen clicked
• Selection Screen Modal Dialog on the right Saves selection and disappears
Define Main Android Activity// This is MainActivity.java@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.main); // Assuming there is a TextView layouttv = (TextView)findViewById(R.id.text1);setOptionText(); // Helper method to get user preference and adjust view
}@Override public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater();
// Inflate main menu XML with link to preference optioninflater.inflate(R.menu.mainmenu, menu);return true; // Menu is now active
}
Main Activity Selection Responses@Override public boolean onOptionsItemSelected (MenuItem item){ if (item.getItemId() == R.id.menu_prefs)
{ Intent intent = new Intent().setClass(this, com.syh.PreferenceActivity.class);this.startActivityForResult(intent, 0); // Second parameter is for a switch in
listener} else if (item.getItemId() == R.id.menu_quit) { finish(); }return true; // Start preference menu when its item is selected
}@Override public void onActivityResult(int reqCode, int resCode, Intent data){ super.onActivityResult(reqCode, resCode, data);
<CheckBoxPreference android:key="show_total_travel_time_column_pref"android:title="Total Travel Time"android:summary="Show Total Travel Time column" />
android:title=“Set Package Name" android:summary="Set the package name for generated code">
<EditTextPreference android:key="package_name_preference"android:title="Set Package Name" android:dialogTitle="Package Name" android:summary="Set the package name for generated code" />
Preference Fragments• Android versions 3.0 and newer recommend using fragments for
preferences instead of activities
• Check Android Version: if (Build.VERSION.SKK_INT<Build.VERSION_CODES.HONEYCOME)
{ /* Use preference activity approach */ }else { /* Use preference fragment approach */ }
• Implementation Steps1. Define preference screens in XML (as shown on previous slides)2. Add PreferenceFragment to the activity using the FragmentManager3. Create the PreferenceFragment class
Preference Fragment in an Activitypublic class PreferenceFragmentActivity extends Activity { @Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentManager manager = getFragmentManager();FragmentTransaction trans = manager.beginTransaction();MyFragment fragment = new MyFragment();trans.replace(android.R.id.content, fragment1); trans.addToBackStack(null); trans.commit();
}} Note: Don’t add the fragment to the application manifest
Preference Fragment Classpublic class MyFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
// configure the preferences from an XML fileaddPreferencesFromResource(R.xml.preferences);
– Lightweight database system– Standards-compliant– Single Tier (no server involved)– Open source
• Standard SQL queries“SELECT ID, CITY, STATE FROM STATION WHERE LAT_N > 39.7;”
• Application content providers provide – Standard interface to SQL tables to other applications– For application private tables, content providers are not needed
Authorities / URI
• Definition: An authority is a registered name on an android device (ex: Content Provider name. Authorities must be unique on the system.
• Registration: Accomplished in an application manifest
• Syntax: com.company.someProvider
• Examples: org.acorns.LessonProvider or com.android.provider.BookProvider
• Analogy: Authorities are to Android what domain names are to the Web
• Activity access using URIs– Syntax: content://authority-name/path-segment/path-segment/…
– Access book table: content://com.anroidbook.provider.BookProvider/books
• Activity Interface: Through Content Providers, which fill in abstract methods
Purpose: Publish application SQL tables and data for external activity access
MIME Types
• Definition: Industry standard way to indicate a particular data format
• Syntax: Two text strings separated by slashes
• First part (category): application, audio, image, text, video, etc
• Second Part (codec): html, css, xml, pdf, rtf, etc.
• Examples: text/htm, application/pdf, image/jpeg, audio/mpeg, etc.
• Android MIME Types (Similar syntax as standard MIME types)
– First Parto Access single items: vnd.android.cursor.itemo Access multiple items: vnd.android.cursor.dir
– Second Part: vnd.yourCompany.type– Examples: vnd.android.cursor.dir/vnd.google.note or
vnd.android.cursor.item/vnd.google.note
Purpose: Indicate a type of data that a content provider deals with
Content Provider Framework
• An application registers its content provider using its manifest• The code for the content provider is written• An application request data using the published MIME type• Android looks through the registered manifests for an
appropriate provider• The provider activity is launched to manipulate or return data• If more than one provider exists, the user selects the one to use• Android Built-in content providers:
• Register an authority using the AndroidManifest.xml file– Definition: An authority is a registered name– Analogy: authority is to an Android device what a domain name is
to the Internet
• Syntax: ( Using a package name minimizes redundancies on a system)<provider android:name="fooProvider"
A well-defined interface to data for application access
MIME Types
• Specifies the data type an activity can process– Register in the AndroidManifest.xml file– Example: "vnd.android.cursor.dir/vnd.google.note"
OR "vnd.android.cursor.dir/vnd.google.note"
• Sample Syntax: vnd.android.cursor.<opt>/vnd.company.type– vnd: non-standard type (vendor)– android.cursor: required for ContentProvider Manifest registrations – item: single record; dir: collection of records– google: company name– note: content type
– Uniform resource identifier (URI) Identifies the name of a resource, but not necessarily information regarding its location
– Uniform resource Location (URL) is a URI, that identifies a resource location– Text usage: URI for content providers; URL for referring to Web locations
• URI of a content providercontent://com.company.fooProvider/content://com.acorns.provider.Lessons/content://com.google.provider.NotePad/
• Note: Android provided shortcut URIs: contacts for com.google.android.contacts
• Refer to the notes SQLite notes tablecontent://com.google.provider.NotePad/notes/
• Refer to the tenth notecontent://com.google.provider/NotePad/notes/10
Register the Provider <provider android:name="NotePadProvider" android:authorities="com.google.provider.NotePad" />
• Plan the Database• Extend the ContentProvider class• Fill in a variety of methods to be overloaded
– onCreate(): When the database is created– onUpgrade(): When the database layout changes– getType(): Return the MIME data type– query(): Handle queries to the data– insert(), delete(), and update() methods
A Managed Query in Content Provider
// Specify needed columns string[] projection = new string[]
{ People._ID, People.NAME, People.NUMBER };
// Specivy URI using static Contacts constantsUri contactUri = Contacts.People.CONTENT_URI;
// Invoke a content provider queryCursor cursor = managedQuery( contactUri,projection, //Which columns to returnnull, null, // Selection and WHERE clausesContacts.People.NAME + " ASC"); // Order-by (ascending by name)
Purpose: Query SQL lite table for relevant data (cursor)Definition: An Android cursor is a collection of rows of data
Other classes exist (ex: SQLiteQueryBuilder) for using standard SQL strings
Navigating through a cursor• Manipulate the cursor (row pointer)
– if (cursor.moveToFirst() == false)– cursor.isBeforeFirst(), cursor.isAfterLast, cursor.isClosed()– while (cursor.moveToNext()) { /* code here */ }– for (cursor.moveToFirst(); !cursor.isAfterLast(); cur.moveToNext) { … }
• Get column numbers from names– int nameColumn = cursor.getColumnIndex(People.NAME);– int phoneColumn = cursor.getColumnIndex(People.NUMBER);
• Get Data from column– String name = cursor.getString(nameColumn);– String number = cursor.getString(phoneColumn);
• Prerequisites: Know column names, data types, column name to index relationship
After a query, the cursor points before the first; use moveToFirst(); use moveToNext() for the initial access
Other Access Methods• AddContentValues values = new ContentValues();values.put(BookProviderMetaData.BookTableMetaData.BOOK_NAME, "book1");values.put(BookProviderMetaData.BookTableMetaData.BOOK_AUTHOR, "author-1");ContentResolver resolve = context.getContentResolver();URI uri = BookProviderMetaData.BookTableMetaData.CONTENT.URI;Uri inserted = resolve.insert(uri, values);
• Delete: Assume that bookIndex is pre-definedContentResolver resolve = context.getContentResolver();URI uri = BookProviderMetaData.BookTableMetaData.CONTENT.URI;Uri delURI = uri.withAppendedPath(uri, Integer.toString(bookIndex));resolve.delete(delUri, null, null);
Content Resolver• Definition: A Content Resolver is an Android class that
matches the URI to an available Content Provider that can handle the data
• Purpose: Separate the provider from the data, enabling the possibility of multiple content providers available to handle the same data types
• Access: Use a collection of method calls to insert, retrieve, delete, update data records
• Example: (insert a new note into the notepad)ContentResolver resolver = activity.getContentResolver();Uri newUri = resolver.insert(Notepad.Notes.CONTENT_URI,
values);
Note: values is an instance of the ContentValues class
Store Files in an SQLite DatabaseSteps
1. Create the SQLite table with a column called _data2. Get a writeable output stream3. Write the file to the reserved column name _data
I/O Example//Use a content resolver to insert the recordContentResolver contentResolver = activity.getContentResolver();Uri newUri = contentResolver.insert(Notepad.Notes.CONTENT_URI, values);//Use the content resolver to get an output stream directlyOutputStream outStream = contentResolver().openOutputStream(newUri);writeFileToRecord(outStream);outStream.close();
ContentValues object contains a set of values
Note: The data is actually stored in a separate area. The _data column contains the Uri reference to the data
DataBase Helper• Purpose
– Manage database creation and version management– Responsible for creating and upgrading an SQLite database– Defer database opening and updating to the first use– Avoids blocking application startup with compute intensive database
upgrades– Contains methods for getWritableDatabase and
getReadableDatabase– Simplifies Content Provider access to files– Eliminates concern over whether the application was terminated
• Implementation– Create a class that extends SQLiteOpenHelper– Override onCreate() and onUpgrade() methods
Helper Code (Two tables: Employees, Department)
public class DatabaseHelper extends SQLiteOpenHelper { static final String dbName="demoDB";
static final String employees="Employees";static final String colID="EmployeeID"; static final String colName="EmployeeName"; static final String colAge="Age"; static final String colDept="Dept";
static final String depts="Department"; static final String colDeptID="DeptID"; static final String colDeptName="DeptName";static final String viewEmps="ViewEmps";
public DatabaseHelper(Context context) // Constructor{ super(context, dbName, null /* Extension to cursor class */, 1 /* version */); }
This application will need to override onCreate and onUpgrade
db.execSQL("CREATE TRIGGER fk_empdept_deptid "+" BEFORE INSERT ON "+employees+" FOR EACH ROW BEGIN" + " SELECT CASE WHEN ( (SELECT " + colDeptID + " FROM " +
depts + " WHERE " + colDeptID + "=new." + colDept + " ) IS NULL)" + " THEN RAISE (ABORT, 'Foreign Key Violation') END;" + " END;");
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); int aX= cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.ALBUM); int tX = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.TITLE); String[] result = new String[cursor.getCount()]; while (cursor.moveToNext()) { String title = cursor.getString(tX), album = cursor.getString(aX);
result[cursor.getPosition()] = title + " (" + album + ")"; }
cursor.close();
Using the Android provided Media Store Content Provider
Other Native Content Providers: Browser, Contacts, Calendar, Call log
Accessing the Contact Listint iDCol = ContactsContract.Contacts.ID;int nameCol = ContactsContract.Contacts.DISPLAY_NAME;Uri uri = ContactsContract.Contacts.CONTENT_URI;String[] projection = { iDCol, nameCol }; Cursor cursor = getContentResolver().query(uri, projection, null, null, null);int nameIndex = cursor.getColumnIndexOrThrow(nameCol); int idIndex = cursor.getColumnIndexOrThrow(contactIDCol); String[] result = new String[cursor.getCount()]; while(cursor.moveToNext()) { String name = cursor.getString(nameIndex);
String id = cursor.getString(idIndex); result[cursor.getPosition()] = name + " (" + id + ")";
} cursor.close();
Searchable Applications• Expose the application to search-facilities• Alternatives
– Search bar appearing after hardware search button pressed or a program method call
– Search widget placed somewhere on the application view
– Quick Search implemented as a home screen widget
– Enable voice search
Making an Application Searchable• In the manifest
– Create an xml file with the searchable attributes– Mark the application searchable– Define the intent for the activity processing searches
• Either create a search activity– Launch when the search is initiated– Process and display the results
• Or use a search dialog (floating search box)– Hidden by default, but can be initiated by calling
onSearchRequested(), which is an Activity class method– If the device doesn’t contain a dedicated search button, add a menu
option or widget that calls onSearchRequested()• Or use the SearchView widget
•The label (required attribute) becomes visible when search is launched and contains the search application name•The hint appears in the search box before users enter a query. It contains a hint about what can be searched•Other attributes are for search suggestions and voice search
// Get the intent, verify the action and get the queryIntent intent = getIntent();if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query); // Process the request}
}
Services• Services handle background
events separate from a View• Services reside in the main thread
of the launching process! Use thread facilities to avoid blocking the main thread
• Only foreground activities have a higher priority, so services are rarely terminated by the OS
• Proper Handling– Main activity makes requests– Service starts worker threads to
4. Start and stop of the service in the main activity5. Use separate threads for compute-bound operations
– Bind service to the main activities so the main activity can call service class methods and then update its user interface views
6. Self-terminate the service when it is no longer needed
Starting and Stopping Services• Explicitly start My Service
Intent intent = new Intent(this, MyService.class); // TODO Add extras if required. startService(intent); }
• Implicitly start a music Service Intent intent = new Intent(MyMusicService.PLAY_ALBUM); intent.putExtra(MyMusicService.ALBUM_NAME_EXTRA, "United"); intent.putExtra(MyMusicService.ARTIST_NAME_EXTRA, "Pheonix"); startService(intent);
• Explicitly stop My Service : stopService(new Intent(this, MyService.class));
• Implicitly stop Music ServicestopService(new Intent(MyMusicService.PLAY_ALBUM));
Creating a Bindable Service
public class LocalService extends Service { private final IBinder binder = new LocalBinder(); public class LocalBinder extends Binder
public void onButtonClick(View v) { if (bound) { int num = service.getRandomNumber(); Toast.makeText(this, "number: "+num, Toast.LENGTH_SHORT).show(); } }
}
Updating the GUI from a Service1. The activity registers a listening object with the service2. The service broadcasts an intent and the activity responds3. Use a Handler in an activity
private final Handler handler = new Handler(); // Process queue of runnablesprivate OnClickListener buttonListener = new OnClickListener() { public void onClick(View v)
{ new Thread(new Runnable() { pubic void run()
{ //.... hard work in separate thread handler.post(new Runnable() { public void run() { // ... update the UI } });
}).start(); } };}
Note: There are other possibilities. For example, one could use AsyncTask, IntentService or Loader objects