Symbian_OS_Using_Contacts_APIs_v1_0_en

  • 格式:pdf
  • 大小:348.02 KB
  • 文档页数:25

S Y M B I A N O SSymbian OS: Using Contacts APIsVersion 1.0April 27, 2004Legal NoticeCopyright © 2004 Nokia Corporation. All rights reserved.Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.Java and all Java-based marks are trademarks or registered trademarks of SunMicrosystems, Inc. Other product and company names mentioned herein may betrademarks or trade names of their respective owners.DisclaimerThe information in this document is provided “as is,” with no warranties whatsoever, including any warranty of merchantability, fitness for any particular purpose, or anywarranty otherwise arising out of any proposal, specification, or sample.Furthermore, information provided in this document is preliminary, and may bechanged substantially prior to final release. This document is provided forinformational purposes only.Nokia Corporation disclaims all liability, including liability for infringement of anyproprietary rights, relating to implementation of information presented in thisdocument. Nokia Corporation does not warrant or represent that such use will notinfringe such rights.Nokia Corporation retains the right to make changes to this specification at any time, without notice.LicenseA license is hereby granted to download and print a copy of this specification forpersonal use only. No other license to any other intellectual property rights isgranted herein.Contents1.Introduction (5)2.Contacts Model (6)2.1Overview (6)2.2vCards (6)2.3Contacts Database (7)2.4Contact Items (7)2.5Contact Fields (8)2.6Contact Groups (8)3.Contacts API (9)3.1Contacts Database Management (9)3.2Accessing Contact Items (11)3.2.1Adding a contact item (11)3.2.2Reading a contact item (14)3.2.3View definitions (15)3.3Searching the Database (17)3.3.1Iterating through contacts (17)3.3.2Creating subsets using filters (18)3.3.3Finding contact items (18)3.4Notification of Changes (20)3.5vCards (21)4.Summary (23)5.Terms and Abbreviations (24)6.References (25)Change HistoryApril 27, 2004 Version 1.0 Initial document release.1.I n t r o d u c t i o nThis document describes how to use the Symbian OS Contacts Model for storingand retrieving contact information. The Contacts Model uses a defined standard for contacts (vCard) and provides a contacts database. The key features aredemonstrated in code examples.2.C o n ta c ts M o d e l2.1 OverviewAny application may retrieve and manipulate the contact data stored in a Symbianmobile phone. A typical example of this is accessing the list of contacts stored in the database in order to select a recipient for an SMS message. This functionality,among others, is provided by the Contacts Model.The architecture of the Contacts Model is very simple. It is based on a contactsdatabase that contains contact items. Each contact item has fields, such as names, addresses, and telephone numbers. A mobile phone may have several contactsdatabases, but there is always one default database. This is the database thatprovides contact data to the Contacts application itself, that is, the data you seewhen you look in the Phonebook.2.2 vCardsA vCard is a type of electronic business card that is supported by many electronicdevices, such as PDAs and mobile phones. The purpose is to allow easytransmission of contact data between these devices using a variety of protocols.vCards can be encoded as plain text as defined in the MIME specification (RFC1521). This encoding ensures that vCards are fully compatible with transferencodings that are limited to a 7-bit character set, such as the encoding used inSMS messages.The vCard standard is fully supported by Symbian OS. A vCard is formatted asfollows:BEGIN:VCARDVERSION:2.1N:Wilkinson;SteveFN:Steve WilkinsonORG:EMCC Software Ltd.TEL;WORK;VOICE:01617779700ADR;WORK;ENCODING=QUOTED-PRINTABLE:;;108 ManchesterRd.=0D=0ACarrington;Manchester;UK;M31 4BD;United KingdomLABEL;WORK;ENCODING=QUOTED-PRINTABLE:108 ManchesterRd.=0D=0ACarrington=0D=0AManchester, UK M31 4BD=0D=0AUnited K=ingdomEMAIL;PREF;INTERNET:steve.wilkinson@REV:20030909T164330ZEND:VCARDMuch of the functionality in the Contacts Model is associated with the handling ofvCards ensuring that developers of Symbian applications can easily write code thatadheres to industry standards for the exchange of electronic business cards andcontacts. This will be discussed in depth in Section 3.5, “vCards,” which includescode examples describing the use of this functionality in detail.Database2.3 ContactsThe clients of the Contacts Model access a database through theCContactDatabase class, which is used to create a new database or open anexisting one. The default database is stored in the contacts.cdb file located in the \system\data\ directory and may be located on and moved between any drivesprovided that the path is given.The CContactDatabase class also provides functionality for accessing contactitems. Contact items can be either read or opened. They must be opened if theintention is to edit or delete the item, although a particular contact item can beopened only by one application at a time. When the changes to the item have beencompleted, they are saved by committing them to the database.Searching and sorting items in the database is another key functionality offered bythis class. The database can be sorted in an ascending or descending order byconstructing an array of sort preferences. This array contains the UIDs of specificcontact fields in the order of which they are to be used in the sorting process, that is, the database is initially sorted by the field in the first location in the array, then theitems that match this field are sorted by the second field in the array, and so on.Once the database has been sorted by all fields in the array, any matching recordsare left in their natural order. Some powerful features are also available forsearching within the database, such as finding specific text in a contact item ormatching a phone number based on the last eight digits. This is especially usefulwhen searching for a phone number that may have been stored in the database with or without the country code. A detailed example that explains searching in adatabase is given in Section 3.3.3, “Finding contact items.”The Contacts Model provides the MContactDbObserver class that an applicationmay be derived from in order to receive change notifications generated by aparticular contacts database. Applications using this observer receive notifications of events, such as adding a new contact to the database, modifying or deleting anexisting contact, and a range of other useful notifications.2.4 Contact ItemsA contacts database may contain several contact items, each one represented by aunique ID. Examples of contact items include:Contact cards, which store the actual data for a contact.Templates, which store default values and attributes for certain fields in a contact card.Contact Groups, which connect an associated set of contacts.Own card, which stores the contact information about the owner of the device.All contact items are derived from the abstract base class CContactItem andaccess to them is managed through the CContactDatabase class as describedearlier. The unique ID of each contact item can be obtained with theCContactItem::Id() function that returns a TContactItemId. TheCContactItem class also contains functionality for manipulating the fields within thecontact item. New fields can be added and inserted, and existing fields can beremoved from the item.Fields2.5 ContactFields within a contact item are represented by the CContactItemField class. For convenience, all fields within a particular contact item are stored within a structureknown as a field set (CContactItemFieldSet). Each contact field stores the actual field data along with a specific storage type for the data. This can be a text string, a date/time value, a store, or an agent, and is represented by the TStorageTypeclass. An agent field is basically a link to another contact and, for example, theSeries 60 Platform implements this by associating the ID of the other contact item to the contact field. Note that numerical contact fields are not supported. All numerical information, such as telephone and fax numbers, are stored as text.There are various attributes that can be set for each contact field, including a labelthat identifies the field to the user, for example, “Fax Number” or “Address.” It is also possible to associate fields that contain telephone numbers to specific speed dialbuttons on the keypad. Fields can also be mapped to fields from the vCardspecification in order to populate contact items to vCards.Groups2.6 ContactA contact group is a contact item that connects an associated set of contacts. Thegroup maintains an array of IDs representing each contact item that belongs to thegroup. Contact items are added to a group with theCContactDatabase::AddContactToGroupL() function and removed from a group with the ContactDatabase::RemoveContactFromGroupL() function.A new contact group is created with theCContactDatabase::CreateContactGroupL() function.3.C o n ta c ts A P I3.1 Contacts Database ManagementThis section describes the API used to manage the contacts database and provides code examples demonstrating how the functionality that is primarily offered by theCContactDatabase class is used. First of all, the following code shows how to openand close a database. There are two overloads of theCContactDatabase::OpenL() function. If the function is not given a parameter,the default database is opened. Alternatively, the application designer may specifyanother database to open by passing in the path and filename of the database file in question.Note that a contacts database does not have a Close() or a similar function. Allresources owned by the CContactDatabase object are simply cleaned up when the object is deleted. However, the CContactDatabase::OpenL() function allocatesthe memory for the CContactDatabase object and passes the ownership to thecaller. Therefore, the caller is not only responsible for deleting this object but also for placing it on the Cleanup stack if the returned object is assigned to an automaticpointer. The same applies to a similar set of functions used for creating a newdatabase as described later.// Open the default contacts database.CContactDatabase* contactsDb = CContactDatabase::OpenL();CleanupStack::PushL(contactsDb);// Count how many contacts are in the default database and then// delete the CContactDatabase object.// Note that all resources owned by the contacts database are freed// upon deletion.TInt numberOfContacts = contactsDb->CountL();CleanupStack::PopAndDestroy(contactsDb);The drive, path, and filename of the current database may be obtained by calling the CContactDatabase::DatabaseDrive() andCContactDatabase::GetDefaultNameL() functions:// Find the drive, path, and filename of the default database.TDriveUnit defaultDbDrive;CContactDatabase::DatabaseDrive(defaultDbDrive);TFileName defaultDbFilePath;CContactDatabase::GetDefaultNameL(defaultDbFilePath);Note: If the following static function is called, the default database file and all contacts previously stored by the contacts application may be deleted.// Delete the default database file.CContactDatabase::DeleteDefaultFileL();The following code example demonstrates how to create a new empty database. The only difference between the CContactDatabase::CreateL() function and the CContactDatabase::ReplaceL() function is that the former leaves with KErrAlreadyExists if the database already exists. As before, if no parameter is specified, these functions create a default database. TheCContactDatabase::FindContactFile() function takes a reference to a descriptor which will return the location of the default database if one exists.The drive where the default database is stored on can be changed by calling the CContactDatabase::SetDatabaseDriveL() function.// Search for a default database on all drives of the Series 60 device.// If one is found, replace it with a new empty default database.// If no default database is found, create a new one.TFileName contactDbFilePath;CContactDatabase* newDefaultContactDb;if(CContactDatabase::FindContactFile(contactDbFilePath)){newDefaultContactDb = CContactDatabase::ReplaceL();}else{newDefaultContactDb = CContactDatabase::CreateL();}CleanupStack::PushL(newDefaultContactDb);// Do something with the database…CleanupStack::PopAndDestroy(newDefaultContactDb);// The default drive is c: - change it to d:_LIT(KMemoryCardDrive, "d");TDriveUnit myMemoryCard(KMemoryCardDrive);CContactDatabase::SetDatabaseDriveL(myMemoryCard);When an item is deleted from the database, the disk space is not freedautomatically, but compression is needed. Since the compression is a relatively heavy task, it is not recommended to compress after every deletion. TheCContactDatabase::CompressRequired() function returns ETrue if compression is needed. Compression is considered necessary whenever more than 256k arewasted due to fragmentation in the database file or for smaller files whenever 50% of the file size is wasted. The actual compression is done by theCContactDatabase::CompactL() function. Note that this function is synchronous and the actual compression may take some time. Therefore, the asynchronous function CContactDatabase::CompressL() is also provided for database compression .// Compress the database if necessary. Note that CompactL() is a synchronous //function and the compression may take some time.if(myContactDb->CompressRequired()){my C ontactDb->CompactL();}In the unlikely event that the contacts database becomes corrupt, theCContactDatabase::RecoverL() function may be used to rollback to the last known normal state. The following code example demonstrates how this function is used:// Check if the database is damaged.// If yes, rollback to the last normal state.if(myContactDb->IsDamaged()){my C ontactDb->RecoverL();}3.2 Accessing Contact Items3.2.1 Adding a contact itemNew contact items are added to the database by calling theCContactDatabase::AddNewContactL() function. However, before this, you can add new fields to the contact item as well as attributes and values to each individual field. The NewL() and NewLC() functions in the CContactItemField class have various overloads for constructing field objects. Apart from the copy constructor, these all take the TStorageType parameter, which determines the format in which the data in the field is stored. Possible values are:KStorageTypeText – used for most fields, including numerical fields.KStorageTypeStore – used for binary field data (for example, an attachment). KStorageTypeContactItemId – used for agent fields.KStorageTypeDateTime – used for date/time fields.In addition to this, it is also possible to specify a field type for each field. These are UIDs represented by the TFieldType class. Possible values are listed in cntdef.h. The following code demonstrates how to create a new contact, add suitable fields, and add the contact to the database. In this example, three text fields with fieldtypes, text labels, and text values are added to a contact. Note that whenever a field is added to a contact, the contact becomes responsible for managing the memory and other resources associated with the field. Therefore, it is not necessary to delete these fields explicitly – popping them from the cleanup stack it is sufficient.// Some literal strings for the fields:_LIT(KForenameLabel,"Forename");_LIT(KSurnameLabel,"Surname");_LIT(KWorkPhoneLabel,"Work Phone");_LIT(KForename,"Steve");_LIT(KOtherForename,"Bob");_LIT(KSurname,"Wilkinson");_LIT(KWorkPhone,"+441617779700");// Open the default contacts database:CContactDatabase* contactsDb = CContactDatabase::OpenL();CleanupStack::PushL(contactsDb);// Create a contact card and add some fields:CContactItem* contact = CContactCard::NewLC();CContactItemField* field = CContactItemField::NewLC(KStorageTypeText, KUidContactFieldFamilyName);field->SetMapping(KUidContactFieldVCardMapUnusedN);field->SetLabelL(KSurnameLabel);field->TextStorage()->SetTextL(KSurname);contact->AddFieldL(*field);CleanupStack::Pop();field = CContactItemField::NewLC(KStorageTypeText, KUidContactFieldGivenName);field->SetMapping(KUidContactFieldVCardMapUnusedN);field->SetLabelL(KForenameLabel);field->TextStorage()->SetTextL(KForename);contact->AddFieldL(*field);CleanupStack::Pop();field = CContactItemField::NewLC(KStorageTypeText, KUidContactFieldPhoneNumber); field->SetMapping(KUidContactFieldVCardMapTEL);field->SetLabelL(KWorkPhoneLabel);field->TextStorage()->SetTextL(KWorkPhone);contact->AddFieldL(*field);CleanupStack::Pop();// Add the new contact to the database and set it as the own card:contactsDb->AddNewContactL(*contact);contactsDb->SetOwnCardL(*contact);CleanupStack::PopAndDestroy(2); // contact contactsDbThe contact card that represents the electronic business card of the owner of the Symbian mobile phone can be set by calling theCContactDatabase::SetOwnCardL() function.Note that the CContactItemField::SetMapping() function is called for each of the fields created earlier. This function associates a field with one of the standard vCard fields and is required if the contact will be populated from or will generate a vCard. This mapping is also needed if the application developer wants the contact to be displayed in the Phonebook application.The following table indicates how some fields are mapped between Symbian OS and vCard.Property name Symbian OS property mapped vCard property First name KUidContactFieldVCardMapUnusedN NLast name KUidContactFieldVCardMapUnusedN NCompany KUidContactFieldVCardMapORG ORGJob title KUidContactFieldVCardMapTITLE TITLETelephone KUidContactFieldVCardMapTEL TELE-mail KUidContactFieldVCardMapEMAILINTERNET EMAIL;INTERNET Table 1: Mapping between Symbian OS and vCard3.2.2 Reading a contact itemWhenever a contact item is opened for editing, it is locked to prevent simultaneous edits from other clients of the Contacts Model and it remains locked until it is either committed or closed. Therefore, unless you wish to edit a contact item, the item should be opened as read only with the CContactDatabase::ReadContactL() or ReadContactLC() function.The following code example demonstrates how to read information from a contact, in this case the own card contact:// Open the default contacts database:CContactDatabase* contactsDb = CContactDatabase::OpenL();CleanupStack::PushL(contactsDb);// Get the ID of the own card and open the contact:TContactItemId ownCardId = contactsDb->OwnCardId();CContactItem* ownCard = contactsDb->ReadContactL(ownCardId);CleanupStack::PushL(ownCard);TInt count = ownCard->CardFields().Count();contactsDb->CloseContactL(ownCard->Id());CleanupStack::PopAndDestroy(); // ownCardThe following code example shows how to open a contact for editing. The fields within a CContactItemFieldSet are indexed and the index of a particular field may be obtained by calling the CContactItemFieldSet::Find() function with the UID of the field that you are searching for. In the following example, the index that represents the forename field of the contact is obtained and this is subsequentlyused to modify the text in the field. Once editing the contact has been completed,the changes can be committed to the database by calling theCContactDatabase::CommitContactL() function. TheCContactDatabase::CloseContactL() function closes the contact without saving the changes.ownCard = contactsDb->OpenContactL(ownCardId);CleanupStack::PushL(ownCard);TInt index = ownCard->CardFields().Find(KUidContactFieldGivenName);ownCard->CardFields()[index].TextStorage()->SetTextL(KOtherForename);contactsDb->CommitContactL(*ownCard);CleanupStack::PopAndDestroy(2); // ownCard contactsDb3.2.3 View definitionsWhen reading or opening a contact item using the CContactDatabase class, a view definition may be specified to indicate which fields should be retrieved. Apart from the fields set, a view definition specifies the use (CContactItemViewDef::TUse ) and the mode (CContactItemViewDef::TMode ). The use indicates whether fields should be included in or excluded from the view and can have the following values: EIncludeFields - include specified fields in the view.EMaskFields - exclude specified fields from the view.The mode indicates whether hidden fields should be included in the view and can have the following values: EIncludeHiddenFields - include hidden fields in the view.EMaskHiddenFields - exclude hidden fields from the view.The following code example demonstrates how to use the CContactItemViewDef class to specify a view definition when reading a contact with the ReadContactL() function:// Open the default contacts database:CContactDatabase* contactsDb = CContactDatabase::OpenL();CleanupStack::PushL(contactsDb);CContactItemViewDef *itemViewDef = CContactItemViewDef::NewLC(C ContactItemViewDef::EIncludeFields, C ContactItemViewDef::EMaskHiddenFields); itemViewDef->AddL(KUidContactFieldGivenName);itemViewDef->AddL(KUidContactFieldFamilyName);// Get the ID of the own card and open the contact:TContactItemId ownCardId = contactsDb->OwnCardId();TInt count;if( ownCardId!=KNullContactId ){CContactItem* ownCard = contactsDb->ReadContactL(ownCardId, *itemViewDef); C leanupStack::PushL(own Card);count = ownCard->CardFields().Count();contactsDb->C lose C ontactL(own Card->Id());CleanupStack::PopAndDestroy(); // ownCard} CleanupStack::PopAndDestroy(2); // itemViewDef contactsDb The view definition may be created either with theCContactItemViewDef::NewLC() or the NewL() function with the use and the mode specified. After that, the AddL() function is called for each field type in order to add it to the view.The CContactDatabase class has a default view definition that is used for allreading operations when the view definition has not been specified. TheCContactViewDef class owns the items view definition (CContactItemViewDef ) to store all settings (filed types, a mode, and a use). TheCContactDatabase::SetViewDefinitionL() function is used to set a new view definition. The following code will give the same result as the previous example but the SetViewDefinition() function is used to specify the view definition.// Open the default contacts database:CContactDatabase* contactsDb = CContactDatabase::OpenL();CleanupStack::PushL(contactsDb);CContactItemViewDef *itemViewDef = CContactItemViewDef::NewL(C C ontactItemViewDef::EIncludeFields, C C ontactItemViewDef::EMaskHiddenFields); itemViewDef->AddL(KUidContactFieldGivenName);itemViewDef->AddL(KUidContactFieldFamilyName);CContactViewDef *viewDef = CContactViewDef::NewL(itemViewDef);contactsDb->SetViewDefinitionL(viewDef);// Get the ID of the own card and open the contact:TContactItemId ownCardId = contactsDb->OwnCardId();TInt count;if( ownCardId!=KNullContactId ){CContactItem* ownCard = contactsDb->ReadContactL(ownCardId);C leanupStack::PushL(own Card);count = ownCard->CardFields().Count();contactsDb->C lose C ontactL(own Card->Id());CleanupStack::PopAndDestroy(); // ownCard}CleanupStack::PopAndDestroy(); // contactsDb3.3 Searching the Database3.3.1 Iterating through contactsTraverse through a contacts database can be implemented with the TContactIter class. This class provides a set of functions for iteration through all contact items. All functions operate with the contact item ID (TContactItemId ), which is used to access a particular contact item. Using the TContactIter is rather simple and the following code example demonstrates iteration through all contacts in the default contacts database.// Open the default contacts database:CContactDatabase* contactsDb = CContactDatabase::OpenL();CleanupStack::PushL(contactsDb);TContactIter iter(*contactsDb);TContactItemId cardId;while( ( cardId = iter.NextL() ) != KNullContactId ){CContactItem* card = contactsDb->ReadContactL(cardId);C leanupStack::PushL(card);TInt nField = card->CardFields().Find(KUidContactFieldGivenName);TInt fField = card->CardFields().Find(KUidContactFieldFamilyName);if( nField!=KErrNotFound && fField!=KErrNotFound ){TPtrC name = card->CardFields()[nField].TextStorage()->Text();TPtrC fName = card->CardFields()[fField].TextStorage()->Text();iEikonEnv->InfoWinL(name, fName);}contactsDb->C lose C ontactL(card->Id());CleanupStack::PopAndDestroy(); // card}CleanupStack::PopAndDestroy(); // contactsDb3.3.2 Creating subsets using filtersFilters provide a useful tool to get a subset of contact items based on their typeand/or state. A contact item state can be created, modified, or deleted. The corresponding date and time has to be specified for any state. The contact item's type can be contact card, contact card group, contact card template, or own card. Any combination of the contact item’s types can be specified for filtering.The CCntFilter class is used to keep filter parameters. When a filter is created with either the NewL()or NewLC() function, SetXXX() functions are called to setup parameters, where XXX is a parameter name (see SDK documentation for the complete list of the functions). The CCntFilter::SetFilterDateTime() should be used to specify the modification time used by the filter. When all parameters have been specified, the ContactDatabase::FilterDatabaseL() function is called and it returns an array of filtered contact item IDs. The following code example demonstrates how to setup the filter to select modified contact cards.// Open the default contacts database:CContactDatabase* contactsDb = CContactDatabase::OpenL();CleanupStack::PushL(contactsDb);CCntFilter *filter = CCntFilter::NewLC();filter->SetContactFilterTypeALL(EFalse);filter->SetContactFilterTypeCard(ETrue);_LIT(KFilterDate,"20040101:");filter->SetFilterDateTime( TTime(KFilterDate) );filter->SetIncludeModifiedContacts(ETrue);contactsDb->FilterDatabaseL(*filter);TInt count = filter->iIds->Count();CleanupStack::PopAndDestroy(2); // filter contactsDb3.3.3 Finding contact itemsThere are some functions that allow searching for an item in a contacts database: CContactDatabase::FindLC() and CContactDatabase::FindInTextDefLC(). These functions have asynchronous variants as well. FindLC() or FindAsynL() take a text string and the field definition as search parameters. The field definition indicates a subset of fields that are used in the search and, in fact, it is an array of。