Академический Документы
Профессиональный Документы
Культура Документы
bada 1.2.0 Copyright Copyright 2010 Samsung Co., Ltd. All Co., Ltd. All rights reserved. 2010 Samsung Electronics Electronics rights reserved. 1
Contents
Idioms Base
Collection Runtime Utility
Io System Debugging
Overview
The Fundamentals tutorial contains pre-requisite information that you need to start with bada and write your software. Read this tutorial after you have read the SDK tutorial and installed the bada SDK and IDE. Use the bada SDK to access further information about the many examples and sample applications that are explained in the tutorials. There are instances where bada departs slightly from what you may be familiar with. It is important to identify these differences at the beginning so that you can deal with them quickly and easily.
Idioms
Contents
Classes and Interfaces Two-phase Construction
Motivation Construct Method
Samsung bada defines Interface (classes with an I prefix) as an abstract base class where all methods are purely virtual. For example: IList, IMap, and IEvent.
Multiple Inheritance:
To avoid the common pitfalls Object of multiple inheritance, classes must not inherit from more than one base class. Most classes However, multiple interface reside here Very few classes inheritance is permitted. do not derive When inheriting from bada classes from Object or interfaces, do not use the virtual keyword unless there is a strong reason to do so.
public class MyForm :public Osp::Ui::Controls::Form, virtual public Osp::Ui::IActionEventListener { InheritedClass(void); ~ InheritedClass(void);
}; };
Methods
There are no properties in bada. Everything is a method. This is total encapsulation.
This means that you cannot directly access data in bada. Because data cannot be directly accessed, it is impossible for data to become corrupted, or to crash the device through data corruption. This provides a high level of safety for you as the developer, since you do not need to worry about data corruption. This also provides a high degree of security for mobile device users. These limitations on data access prevent malicious software from taking advantage of certain type of security exploits, such as buffer overflows.
10
b) SomeClass* SomeClass::DoSomething()
Call GetLastResult() after executing these methods to get the last result (exception). Return by value (including void) and no exception is thrown.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 11
13
0016.917,EXCEPTION,00,34,Osp::Base::Collection::ArrayList::RemoveItems (675), > [E_OUT_OF_RANGE] The startIndex(20) MUST be less than the number of elements(20).
Exception name
Variable (actual_value)
14
15
Heap
16
IList* A::SearchN(const String& criteria) { // Search with criteria and return the results by storing them in the list. ArrayList* pList = new ArrayList(); // Add the search results to the list. ... return pList; } void MyClass::SomeMethod(void) { A a; IList* pList = a.SearchN(L"Most popular"); ... delete pList; }
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 17
Review
1. 2. 3. 4. 5. 6. Can I play with data corruption and other madness? What is two-phase construction for? How do you check for errors in bada? What does an N postfix signify? What result returns true from an IsFailed call? Can you call a Construct() method more than once or repeatedly?
18
Answers
1. Not really. Samsung bada uses total encapsulation to help insulate you from possible data corruption. 2. Two-phase construction prevents possible resource leaks. 3. Check the result (a type) of a method call. 4. An N postfix in a method name indicates that you must manually delete the instance that it returns to avoid a memory leak. 5. All results except for E_SUCCESS return true in IsFailed. 6. No. All classes with two-phase construction have at least 1 Construct() method, with many having several overloaded Construct() methods in order to facilitate different scenarios. However, only 1 method should be used, and only used once. Samsung bada classes do not guarantee correct behavior if a Construct() method is called more than once.
19
Base
20
Contents
Essential Classes Relationships between Classes Overview Types
String
Example: Create and Modify Strings
UuId
Example: Create a UuId
Buffer
Example: Use Buffers
FAQ
21
Provided by
22
ComparerT
DateTime TimeSpan UuId
23
24
Overview
The Base namespace contains classes and interfaces for base types and enumerations, such as String, Buffer, and DateTime. Object:
The Object class is the base class for most other classes included in the framework. Object provides methods for testing instance equivalence and obtaining an instances hash value. Object makes it easier to define behaviors and characteristics that must be shared by all classes in the framework.
Value types:
Classes inherited from the Number class wrap C++ primitive types, such as char, int, short, long, float, double, and longlong.
25
String (1/2)
A String is a mutable sequence of 2-byte Unicode characters. String capacity:
If no default capacity is specified, the capacity is set to 16 bytes. The maximum possible capacity is 2^32 - 1. Capacity grows at 1.5 * the current length rounded to the nearest multiple of 4. Starting from the default capacity of 16 that is: 16, 24, 36, 54, 80, 120, 180, 272, 408...
Method Append() Insert() Remove() IndexOf() SubString() ToUpper() ToLower() Description Appends the indicated value to the String. Inserts the indicated value at the position. Removes characters within the specified range. Returns the index of the character. Returns the indicated substring. Converts all letters to upper case. Converts all letters to lower case.
26
String (2/2)
You can modify strings using the methods. For example:
1. 2. 3. 4. Prefix a string literal with an upper-case L. Concatenate the string with the Append() method. Convert the string to upper case with the ToUpper() method. Delete a substring from a string with the Remove() method.
1. 2. 3. 4.
str.ToUpper();
str.Remove(0, 4);
// TEST STRING
// STRING
27
28
29
Add (or subtract) time from a DateTime using any of the Add~() methods. Get a part of a DateTime with any of the Get~() methods. Query if it is a leap year with the IsLeapYear() method.
DateTime dt; dt.SetValue(2009, 12, 23); dt.AddYears(10); int year = dt.GetYear(); bool leap = dt.IsLeapYear(); // 2009-12-23 // 2019-12-23 // 2019 // false
30
31
UuId
UuId is a wrapper class for the UUID (Universally Unique Identifier) type and includes several useful operators:
typedef struct { unsigned unsigned unsigned unsigned } UUID;
UuId method and operator Parse()
ToString()
operator!= (const UuId &uuid) operator== (const UuId &uuid) operator= (const UuId &uuid)
32
33
Buffer (1/3)
Buffers contain sequences of a specific primitive type, such as int, long, double, and char.
Property Capacity Limit Position Description The number of elements that a buffer contains. The index of the first element that should not be read or written. The index of the next element to be read or written.
Mark
Stores an index so that later the position can be set to that index. That is, it sets a marker on an index.
Access to data:
Absolute read and write methods access data from index 0 to limit -1, and do not modify the properties. Relative read and write methods access data from position to limit -1, and move the position to the next when one of the methods is applied.
34
Buffer (2/3)
Marking and resetting:
Mark stores the current position when SetMark() is called. The current position is set to the marker when Reset() is called. Markers are invalidated when a position or limit is set to a value less than the markers index, InvalidateMark() is called, or Rewind() is called.
Method Clear() Flip() Rewind() Description Sets the limit to the capacity, the position to zero, and deletes the marker. Sets the limit to the current position and the position to an index. Passing POSITION_TO_ZERO to the method deletes the marker. Sets the position to zero and leaves the limit unchanged.
// //
buf.SetPosition(7); buf.Flip();
// // //
Buffer (3/3)
Buffer<Type> is a parameterized (template-based) class for primitive type arrays:
typedef typedef typedef typedef typedef typedef typedef Buffer<double> DoubleBuffer Buffer<float> FloatBuffer Buffer<int> IntBuffer Buffer<long> LongBuffer Buffer<longlong> LongLongBuffer Buffer<mchar> McharBuffer Buffer<short> ShortBuffer
ByteBuffer is a wrapper class for a byte (unsigned 8-bit integer) array. It defines methods for reading and writing all primitive built-in types to and from a sequence of bytes.
36
37
FAQ
Can I use Buffer<int> or Buffer<MyClass>?
No. Do not use either of them. Buffer<int> is the same as IntBuffer. It is highly recommended to use only pre-defined buffers. The available buffers are as follows:
Buffer DoubleBuffer Primitive type double
FloatBuffer
IntBuffer LongBuffer LongLongBuffer McharBuffer ShortBuffer
float
int long longlong mchar short
38
Collection
39
Contents
Essential Classes Relationships between Classes Overview Interfaces MapEntry ArrayList and LinkedList
Example: Construct and Modify an ArrayList Example: Create and Modify a LinkedListT
ArrayList
LinkedList HashMap MultiHashMap MapEntry
41
42
43
44
45
46
Overview (1/2)
The Collection namespace contains classes and interfaces that define various collections. There are object- and template-based collections:
Object-based collections derive from ICollection and store objects that derive from Object. Template-based collections derive from ICollectionT<Type> and can store primitive types.
For every class or interface available to an object-based collection, there is a corresponding class or interface available to a templatebased collection.
47
Overview (2/2)
IMPORTANT: Object-based collections do not copy objects; they only keep pointers to objects. Do not put stack variables into collections.
ArrayList list; list.Construct(); String str(L"One"); list.Add(str); // Do not put stack variables // into collections. // Use heap variables // with collections.
48
Interfaces (1/4)
ICollection is the base interface for all collection classes.
ICollection
IList
IMap
IMultiMap
An ICollection represents a collection of objects, and defines the size and enumerator:
GetCount() GetEnumeratorN()
49
Interfaces (2/4)
IList represents a collection where individual items can be individually accessed by index.
Methods:
Add(), Remove(), Contains() GetAt(), SetAt() InsertAt(), RemoveAt() AddItems(), InsertItemsFrom(), RemoveItems(), GetItemsN() ContainsAll(), RemoveAll() IndexOf(), LastIndexOf() Sort()
50
Interfaces (3/4)
IMap and IMultiMap represent collections of key-value pairs. All IMap keys must be unique.
IMultiMaps can have more than one element with the same key.
Methods:
Add(), Remove() ContainsKey(), ContainsValue() GetValue(), SetValue() GetKeysN(), GetValuesN() AddItems(), RemoveItems() RemoveAll() GetEnumeratorN(), GetMapEnumeratorN()
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 51
Interfaces (4/4)
IEnumerator facilitates simple iteration over a collection:
GetCurrent() MoveNext() Reset()
IEnumerator
IMapEnumerator
IBidirectionalEnumerator
52
MapEntry
A MapEntry holds a key-value pair. MapEntries are used with the IMapEnumerator interface. IMapEnumerator::GetCurrent() returns a MapEntry object.
IMapEnumerator GetKey() GetValue() GetCurrent() MapEntry Key() Value()
53
SetCapacity()
Add() RemoveAt() Contains() GetAt() SetAt()
54
57
MultiHashMaps can have keys that uniquely map to multiple values. That is, while neither keys nor values are required to be unique, each key-value pair must be unique.
Method Add() Remove() SetValue() GetValue() ContainsKey() ContainsValue() Adds a key-value pair.
Description
Removes the key-value pair containing the specified key. Replaces the value associated with the specified key with a new value. Gets the value associated with the specified key. Returns true if the HashMap contains the specified key. Returns true if the HashMap contains the specified value.
58
Push()
Pop() Peek()
Enqueue()
Dequeue()
60
1
Enqueue
3 2 1
1
61
62
IComparer
IComparer interface implementations compare two object values and return an integer value. Zero value indicates equality. A negative or positive value indicates that the first value is less or greater than the second value, respectively. The following implementations are supplied with bada:
DoubleComparer FloatComparer Int8Comparer IntegerComparer LongComparer LongLongComparer ShortComparer StringComparer
Result
Means
<0
== 0 >0
The StringComparer class tests for equivalence. This means < 0 and > 0 have the same meaning, not equivalent.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 63
FAQ (1/2)
What is the difference between the ArrayList and LinkedList?
ArrayLists store elements in contiguous memory space. This makes accessing ArrayLists by index very fast. However, adding and removing elements is slower than with a LinkedList. LinkedLists store elements in nodes that are connected by pointers. This makes accessing LinkedLists by index slower than accessing ArrayLists by index. However, adding and removing elements is faster than with an ArrayList.
Add or remove ArrayList LinkedList SLOW FAST Access FAST SLOW
64
FAQ (2/2)
Why must I call RemoveAll(true) before deleting an instance of an object-based collection?
Object-based collections do not include the ownership concept for dynamically allocated memory, so the collections only manage pointers to objects on the heap. If you delete the collection, it only deallocates the pointers, and not the real objects on the heap. This is a potential memory leak. To avoid memory leaks, you must delete all objects manually or call RemoveAll(true). However, you do not need to do this in template-based collections because they manage the objects themselves, and not just the pointers.
65
Review
1. What 4-letter word describes a stack? 2. What other 4-letter word describes a queue? 3. What method returns a MapEntry?
66
Answers
1. LIFO or FILO. 2. FIFO. 3. IMapEnumerator::GetCurrent().
67
Runtime
68
Contents
Essential Classes and Relationships Timer
Example: Periodic Timer
69
IRunnable
Mutex
Semaphore
Thread
Monitor
Timer
ITimerEventListener
70
Timer
You can run code at pre-defined intervals using a Timer. Once a timer fires, it does not fire again unless you explicitly set it again. That is, the Timer object is not a periodic timer. You cannot use timers in worker threads. When a timer times out, the ITimerEventListener::OnTimerExpired() event handler is called. You can restart the Timer in the event handler to emulate a periodic timer. For example:
Timer* pTimer = new Timer; pTimer->Construct(*pTimerEventListener); pTimer->Start(1000); // The timer fires after 1000 milliseconds // and the OnTimerExpired event handler // is called. ... void OnTimerExpired(Timer& timer) // Timer event handler. { DoSomethingUseful(); // Do something useful. timer.Start(1000); // Reset the timer. }
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 71
72
Synchronization Objects
Synchronization objects:
Mutex:
Mutual exclusion (mutex) objects allow multiple threads to access a shared resource one at a time in a thread safe manner. A mutex locks an object for exclusive access by a thread. Threads that wish to access a mutex-locked object are queued until the mutex is released.
Semaphore:
Semaphores allow a limited number of threads to access a resource, and keep track of how many threads are accessing that resource.
Monitor:
Monitors provide locks for objects to stop other objects from accessing them when they are in an inconsistent state. Using monitors runs the risk of creating a deadlock. Monitors support mutual exclusion and wait and notify.
73
Examples:
Mutex Mutex* pMutex = new Mutex; pMutex->Create(); pMutex->Acquire(); // Use shared resource pMutex->Release(); Semaphore Semaphore* pSemaphore = new Semaphore; pSemaphore->Create(); pSemaphore->Acquire(); // Use shared resource pSemaphore->Release();
74
Monitors (1/3)
Monitors provide a way to synchronize (lock) access to objects by maintaining a list of threads waiting to access an object. When a thread owns a lock, no other thread may access the object until the owning thread relinquishes the lock. The section of code where shared resources are used is called the critical section. These code blocks are enclosed with the monitors Enter() and Exit() methods as illustrated below.
pMonitor->Enter();
Critical section
75
Monitors (2/3)
The Wait(), Notify(), and NotifyAll() methods can only be called inside of a critical section, between an Enter() and an Exit() call.
Method Enter() Exit() Wait() Notify() Description Marks the start of a critical section (block of code) and locks an object. Marks the end of a critical section (block of code) and releases the lock on the object. Pauses a thread until notified (by another thread). Notifies a waiting thread and releases the locked object to it. Thread execution continues.
NotifyAll()
76
Monitors (3/3)
Threads that have locks (monitors), transfer execution to waiting threads through notifications. Waiting threads resume execution from their last called Wait position. 1. Thread A pauses after 1) Do something and waits for a notification while Thread B is running. 2. Thread B finishes 2) Do something and notifies Thread A. This releases the lock from Thread B and transfers the lock to Thread A. 3. Thread A resumes execution and proceeds to 3) Do something.
Thread A pMonitor->Enter(); Thread B pMonitor->Enter(); // 2) Do something. pMonitor->Notify(); pMonitor->Exit();
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 77
There are 3 main steps in this example. Each is broken down into smaller portions with explanations and code-walk-throughs.
1. Create 2 classes (Producer and Consumer) that each share a monitor and an integer. 2. Create the Producers Run() method. 3. Create the Consumers Run() method.
78
1. Create 2 classes (Producer and Consumer) that each share a monitor and an integer.
The Producer Run() method waits for the Consumer thread to start and sets a value for the shared resource (__pShared). It then notifies the Consumer thread.
class Producer : public Osp::Base::Runtime::Thread { public: Producer(int* pShared, Osp::Base::Runtime::Monitor* pMonitor); Osp::Base::Object* Run(void); private: Osp::Base::Runtime::Monitor* __pMonitor; Shared private int* __pShared; resources };
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 79
class Consumer : public Osp::Base::Runtime::Thread { public: Consumer(int* pShared, Osp::Base::Runtime::Monitor* pMonitor); Osp::Base::Object* Run(void); private: Osp::Base::Runtime::Monitor* __pMonitor; Shared private int* __pShared; resources };
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 80
Object* Producer::Run(void) { // Begin critical section __pMonitor->Enter(); // Wait for the Consumer to start __pMonitor->Wait(); // Produce number value 6 times for (int i = 0; i < 6; i++) { //See next page for loop details } // Exit the monitor __pMonitor->Exit(); return null; }
a b
b)
c)
d)
81
Loop
a b
b)
c)
d }
result r; // Begin critical region __pMonitor->Enter(); // Notify the Producer thread __pMonitor->Notify(); // Wait for notification __pMonitor->Wait(); while (!IsFailed(r)) { //See next page for loop details } // Exit the monitor __pMonitor->Exit(); return null;
d)
83
84
Threading
The thread is the basic unit of flow control inside a program. It is a single, sequential execution of code inside a program. Multiple threads imply multiple, concurrent lines of execution.
Process A Thread 1 Thread 2 ... Thread n Process B Thread 1
Starting a new thread Starting a new process
86
Thread-safety
Since threads can simultaneously use the same resources, these shared resources can fall into an inconsistent state. To prevent this, access to shared resources must be guaranteed to be mutually exclusive. That is, when one thread is using a resource, no other thread may access it. Resources that are categorized as thread-safe can be safely used by multiple threads without fear of falling into an inconsistent state.
Static resources are most often thread-safe. Instances are most often not thread-safe. For example:
Osp::Base::Utility::Math::Sin(x) is thread-safe. The value that Sin() returns is only dependent on the parameters. Osp::Base::UuId::Equals(obj) is not thread-safe. The value returned by Equals() is dependent on the UuId instances, and the expected return value can change if another thread changes the value of the instance of the UuId object.
87
Thread Types
Event-driven threads:
Run event-loops internally. Can use asynchronous calls.
Worker threads:
Execute the main body of the thread and exit. Cannot use asynchronous calls because worker threads do not run event-loops.
88
You can use the default implementation of the Run() method for event-driven threads. (That is, you do not need to implement IRunnable.)
b)
89
Event-driven thread
OnStart()
Runs linearly
Run()
Main body execution continues its eventloop until it receives an exit event notification to stop.
OnStop()
OnStop()
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 90
91
The following example shows how to inherit from Thread to create a worker thread. CMyWorker inherits from Thread and implements the OnStart(), OnStop(), and Run() methods.
result CMyWorker::Construct(void) { return Thread::Construct(); } bool CMyWork::OnStart(void) { return true; } void CMyWorker::OnStop(void) { } Object* CMyWorker:: Run(void) { return null; }
92
93
return true;
} void CTimerThread::OnStop(void) { __pTimer->Cancel(); delete __pTimer; }
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 94
Review
1. How can you set a timer to fire every 5 seconds? 2. What is the main difference between a worker thread and an event-driven thread? 3. What are the 3 basic objects you can use for thread synchronization. 4. What do the Enter() and Exit() methods of a monitor mark?
95
Answers
1. Reset the timer in its OnTimerExpired() method. 2. Worker threads run linearly from start to finish where even-driven threads loop internally. In other words, the main body of execution for an event-driven thread continues its event-loop until it receives an exit event notification to stop. Also, because event-driven threads use events, they, unlike worker threads, can also use asynchronous calls. 3. Mutexes, semaphores, and monitors. 4. They mark the beginning and end of a critical section of code.
96
Utility
97
Contents
Essential Classes and Relationships Relationships between Classes Overview Math
Example: Get the Area of a Circle
StringTokenizer
Example: Split a String into Tokens
StringUtil
Example: Convert a String
Uri
Example: Resolve a URI
Math
StringTokenizer StringUtil Uri Inflator Deflator
Base::Object
Math
StringUtil
StringTokenizer
Uri
Inflator
Deflator
99
Overview
The Utility namespace contains the following useful utility classes: Math, StringTokenizer, StringUtil, Uri, Inflator, and Deflator.
The Math class contains mathematical functions, such as a sine, absolute value, ceiling, floor, logarithm, and exponent functions. You can split strings at delimiters with the StringTokenizer class. You can convert strings to and from mchar buffers and UTF-8 byte buffers with the StringUtil class. You can create and analyze URIs with the Uri class. You can decompress and compress data with the Inflator and Deflator classes.
100
Math
The Math class wraps the native math library.
Mathematical functions Abs() Acos() Asin() Atan() Ceiling() Cos() Cosh() Exp() Floor() GetE() GetPi() Log() Log10() Max() Min() Pow() Rand() Round() Sin() Sinh() Sqrt() Srand() Tan() Tanh()
// 3.141592...
101
102
StringTokenizer
You can use StringTokenizer to cut strings into tokens and count them. If a delimiter is not defined, then the default delimiters are used.
Default delimiters: space, tab, newline, carriage return, and form feed.
: Space (0x20) \t: Tab (0x09) \n: New line (0x0A) \r: Carriage return (0X0D) \f: Form feed (0x0C)
// bada // Sample
103
104
StringUtil
You can convert strings to mchar, base64, and UTF-8 byte buffers with the StringUtil class.
Method GetStringLengthInMb() MbToString() StringToMbN() StringToUtf8N() Utf8ToString() EncodeToBase64String() Description Gets the length of an McharBuffer string. Converts an McharBuffer string to a null-terminated string. Converts from a null-terminated string to an McharBuffer. Converts a Unicode string to UTF-8-encoded format. Converts a UTF-8 string to a Unicode string. Encodes a ByteBuffer into a string consisting of base64 characters.
DecodeBase64StringN()
char* pChar = bada StringUtil"; String str; StringUtil::Utf8ToString(pChar, str); // str = Lbada StringUtil"
105
106
Uri
The Uri class represents a Uniform Resource Identifier (URI) reference as defined by RFC 2396. It provides methods to access individual components of a URI. You can create URIs and access portions or all of a URI with Uri methods.
String uriStr(L"http://www.samsung.com"); Uri uri; uri.SetUri(uriStr);
107
108
void MyClass::InflatorSample(ByteBuffer &buf) { ByteBuffer* pBuf1 = null; // Inflate buf from current position to limit of ByteBuffer buf pBuf1 = Inflator::InflateN(buf); if (null == pBuf1) { // Error case handling } // pBuf1: Inflated data of the buf
...
}
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 109
FAQ
Why is -1 or zero returned when an McharBuffer is filled with data and GetStringLengthInMb() is called? -1 is returned if a null character does not exist between the current position of the McharBuffer and its limit. 0 is returned if the value of the current position of the McharBuffer is null. Call Rewind() and SetPosition() on the McharBuffer before invoking GetStringLengthInMb() to correctly set its current position.
110
Review
1. What does a StringTokenizer do? 2. What class is best to create links to web sites?
111
Answers
1. It splits strings on pre-defined characters with the defaults being the space, form feed, new line, and tab characters. 2. Uri.
112
Io
113
Contents
Essential Classes Relationships between Classes Overview bada File System Directory and File
Example: Navigate a Directory Example: Get File Attributes
Database SQL
Example: Create a Database and Table Example: Run a Query
Registry
Example: Read a Registry Entry
Essential Classes
Features Implements basic database features to create, delete, execute SQL commands, and perform other common database management tasks. Provides a method for navigating the result of DbStatement. Provides a method for creating and evaluating pre-compiled statement. Provides methods for working with directories. Stores the information of each directory entry. Provides methods to access DirEntry class and get Directory information. Provides basic file operations, and input and output, such as create, remove, and read and write. Provides methods for reading the attributes of file. Provides a registry loading and unloading mechanism to every application and the entire system. Provided by Database DbEnumerator DbStatement Directory DirEntry DirEnumerator File FileAttributes Registry
115
Base::Object
Io::File
Io::Directory
Io::Registry
Io::Database
116
Overview
The Io namespace contains input and output classes, such as File, Directory, Databases, and Registry. Every Io class has a subsystem handle as its member. Io includes the following:
File operations, such as create, open, save, copy, move, and delete. Directory operations, such as create, rename, delete, and read directory contents. Registry operations, such as create, read, and delete name-value pairs. Database provides basic methods for managing the bada database system and manipulating database schema.
117
118
/Home
Io: Read and Write /Home/Share Io: Read-only Io: Read and Write /Home/Share2 Io: Read and Write /Share2/[appid] Io: Read-only Io: Read-only Io: Not supported Media: Read-only
/Share/[appid]
/Media/Others
Used to read image data in external memory. Used to read sound data in external memory. Used to read video data in external memory. Used to read theme data in external memory.
/Storagecard/Media/Others
DirEnumerator facilitates iterating over directories to get information on what directories and files they contain.
Directory1 /Directory1
DirEnumerator
Directory2 Directory3
Directory4
/Directory2 /Directory3 /Directory4
121
123
Database
Database thread-safety is guaranteed with a mutex.
Mutex Database Mutex
Thread #2: Tries to acquire the mutex to use the database, fails and is queued.
ID 0
Address New York Boston New York New York Seattle Boston
ID 0 2 3
1 2 3 4 5
124
125
2
3 4 5
Joe
Mark Robert Moe
New York
New York Seattle Boston
126
Registry
The Registry has three parts.
Section is prefixed with a hash symbol (#), and is followed by entries. Entries consist of name-value pairs and are expressed as Name=Value. Entry names can be duplicated in different sections. Entry names must be unique inside of the same section. Entry value can be any of the following types: Integer, Double, Float, String, UuId or Bytebuffer.
#Section1 Name1=1 Name2=string_value Name3=1dda4a68-f063-4b14-abee-9c031f3eb021_msPloc #Section2 Name2=2
127
128
FAQ
Does the Database class guarantee mutual exclusivity for multiple I/O access to a database file?
No. It must be guaranteed by application logic.
129
Review
1. True or false. All directories have children. 2. True or false. You can use T-SQL or PL/SQL in with the database. 3. True or false. Registry names do not need to be unique.
130
Answers
1. False. It is certainly possible to have an empty directory. 2. False. You must use SQLite compatible commands. 3. Trick question. It needs to be qualified. You can have non-unique entry names as long as they do not reside in the same Section. You cannot have identical entry names inside the same Section.
131
System
132
Contents (1/2)
Essential Classes and Relationships Overview SystemTime
Example: Get System Time
SystemInfo
Example: Get System Information
RuntimeInfo SettingInfo
Example: Get Language and Country Code
Battery
Example: Get the Battery Level
Alarm
Example: Create a Daily Alarm
133
Contents (2/2)
Vibrator
Example: Vibrate the Device
PowerManager
Example: Change the Screen Power Management Policy
DeviceManager
Example: Get the Connection State of Accessories
Review Answers
134
Essential Classes
Feature Provides access to the system time and uptime. Provides system information. Provides runtime information. Provides setting information. Provided by SystemTime SystemInfo RuntimeInfo SettingInfo
Battery
Alarm Vibrator PowerManager DeviceManager
135
SystemTime
SystemInfo
RuntimeInfo
SettingInfo
Battery
Vibrator
PowerManager
DeviceManager
Alarm
136
Overview
The System namespace provides device-related information and access to some device features:
System time and uptime. Alarm service. Vibrator device Battery level and charging status Screen power management Device accessory connection state
137
SystemTime
You can get the current system time as UTC, standard, or wall time. UTC is the default.
UTC: Coordinated Universal Time Standard: This is the local time without any DST (Daylight Saving Time) offset. Wall: This is the local time with any DST offset. This is the time that clocks on the wall show.
138
139
SystemInfo
You can retrieve information about system properties and capabilities through SystemInfo by querying a SystemInfo key. Key values can be one of UuId, double, int, String, or bool.
Some popular system information keys PhoneNumber ScreenWidth APIVersion NetworkType BluetoothSupported WPSSupported RSSI ScreenBitsPerPixel OpenGLESVersion CameraCount WiFiSupported TvOutSupported ScreenHeigth PlatformVersion KeyboardType VideoRecordingCodecs GPSSupported FmRadioSupported
140
141
RuntimeInfo
You can get information about memory usage through the RuntimeInfo class:
Memory used by application System-wide available video memory Available storage
Key AllocatedMemory AvailableVideoMemory AvailableInternalStorage AvailableExternalStorage BatteryLevel IsCharging Description Returns the amount of memory used by the application. Returns the system-wide amount of video memory available. Returns the available disk size of the internal storage. Returns the available disk size of the external storage. Returns the current charge remaining in the battery as a percentage. Returns whether the battery is currently charging.
All RuntimeInfo methods are static, so you do not need to create an instance of RuntimeInfo to use it.
142
SettingInfo
You can get information about settings through the SettingInfo class:
Key Description
SilentMode
GPSEnabled Language
Country
All SettingInfo methods are static, so you do not need to create an instance of SettingInfo to use them.
143
144
Battery
You can get information about the battery levels and whether or not the battery is being charged. You can get the battery level either as a percentage of the remaining battery life, or as a pre-defined enumeration:
BATTERY_FULL BATTERY_HIGH BATTERY_LOW BATTERY_CRITICAL BATTERY_EMPTY
145
146
Alarm
You can create a one-time alarm in the system, or a repeating alarm. When the alarm goes off, the alarm listener is called. For repeating alarms, you can set the start and end times along with an alarm period that defines how often the alarm goes off.
147
2. Create an alarm global variable. 3. Set the alarm event listener: Alarm::Construct(*this)
4. Set the alarm: Alarm::Set(dateTime, 60*24, null)
148
Vibrator
You can access and control a devices manner mode vibrator. You can vibrate the device one or more times, and stop vibration. To vibrate it once, merely set the length in milliseconds and the vibration level. To vibrate it more than once, set the following parameters:
Parameter Vibrate on period Vibrate off period Vibration count Length to vibrate for in ms. Length to pause vibration for in ms. Number of times to vibrate. Description
Count = 3
149
150
PowerManager
You can change the screen power management policy using the keepOn and dimming parameters of the PowerManager::KeepScreenOnState()method.
Screen power management policy The screen remains in the ON state until the application moves to the background. The screen is dimmed if no user input is received in a certain amount of time. The screen remains in the ON state until the application moves to the background. The screen is not dimmed. The state of the screen is controlled by the default power management policy of the system. keepOn True dimming True
True
False
False
An application must explicitly call the KeepScreenOnState() method to keep the screen on when returning to the foreground.
151
152
DeviceManager
You can determine whether an accessory is currently connected to the device by using accessory keys with the GetState method of the DeviceManager class:
Key BluetoothHeadset Charger WiredHeadset WiredHeadphone TvOut Bluetooth headset Battery charger Headset (includes the hands-free set) Headphone TV-out Accessory
Use IDeviceEventListener interface to receive an event notifying you of a change in the accessory connection state. All DeviceManager methods are static, so you do not need to create an instance of DeviceManager to use them.
Some devices do not support TV-out. You can confirm the support by using the methods available in the SystemInfo class.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 153
154
Review
1. True or false. The local time is always wall time. 2. What method lets you change the battery? 3. When you read battery levels, how many pre-defined levels are there? 4. How many vibration amplitude levels are there? 5. If you set an alarm, what listener do you use?
155
Answers
1. 2. 3. 4. 5. True. In fact, this is trivially true (that is, by definition). It has nothing to do with the various kinds of times available in bada. None. The battery needs to be physically changed. There are 5 battery levels, but you can also read in percent. There are 101 levels, from 0 ~ 100. IAlarmEventListener.
156
Debugging
157
Contents
Overview AppAssert() AppAssertf() AppLog~ TryCatch() Debugging Output
158
Overview
Samsung bada contains several families of macros to help you with debugging:
Assert macros: These check conditions and kill the process if it is false. They are not compiled into release builds:
AppAssert(condition) AppAssertf(condition, message)
If the condition is false, print message.
Log macros: These log arbitrary information that you can check later:
AppLog(message) AppLogDebug(message) AppLogException(message)
Try macros: These mimic traditional C++ try-catch error handling routines. Unlike the assert macros, try macros do not kill a process:
TryCatch(condition, cleanup, message)
If the condition is false, do the cleanup expression, print message, and goto CATCH.
TryReturnVoid(condition, message)
If the condition is false, print message and return without a value.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 159
AppAssert()
The AppAssert() macro is used to check that programs have no logical errors. If the assertion fails, the current process is killed.
result MyClass::DoSomething(void) { result r = E_SUCCESS; r = mutex.Acquire(); // do something r = mutex.Release();
AppAssert(r == E_SUCCESS);
return r; }
160
AppAssertf()
The AppAssertf() macro is used to check that programs have no logical errors. If the assertion fails, a message is printed out to the console and the current process is killed.
result MyClass::DoSomething(void) { result r = E_SUCCESS; r = mutex.Acquire(); // do something r = mutex.Release(); // If false, console prints "Mutex Release Failed" // and the process is killed. AppAssertf(r == E_SUCCESS, "Mutex Release Failed"); return r; }
161
AppLog~()
AppLog lets you output arbitrary messages that you can later examine:
Bool MyEngine::Init(int value) { AppLogDebug("Invoked with value: %d", value); // Do initialize. .. if (something_wrong) // You can use Try family macros instead. { AppLogException("Something terrible happened."); return false; } AppLog("Initialization successful."); AppLogDebug("Exit.");
return true;
}
162
TryCatch()
TryCatch() tests a condition, and if it is false, prints a message, evaluates a cleanup expression, and goes to CATCH.
const A* MyClass::DoSomething(const mchar* pValue) { result r = E_SUCCESS;
// Do something... // If pValue is null, print "pValue == null" to the // console and return E_INVALID_ARG. TryCatch(pValue != null, r = E_INVALID_ARG, "pValue == null"); SetLastResult(E_SUCCESS); return _pValue; CATCH: SetLastResult(r); return null; }
163
Debugging Output
AppAssert() family:
Assert expression Line number
File name
Detailed message
Timestamp
Used internally
Fully-qualified name
Log message
165