Académique Documents
Professionnel Documents
Culture Documents
Version 1.0b1 Copyright 2010 Samsung Electronics Co., Ltd. All rightsLtd. All rights reserved 1 Copyright 2010 Samsung Electronics Co., reserved.
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
Version 1.0b1 Copyright 2010 Samsung Electronics Co., Ltd. All rightsLtd. All rights reserved 4 Copyright 2010 Samsung Electronics, Co., reserved.
Contents
Classes and Interfaces 2-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.
Not Recommended
public class MyForm :public Osp::Ui::Controls::Form, virtual public Osp::Ui::IActionEventListener { InheritedClass(void); ~ InheritedClass(void);
}; };
// Out-of-memory error.
~ComplexClass (void) { delete p1; delete p2; } private: SimpleClass* p1; SimpleClass* p2; }; void MyClass::SomeFunction() { ComplexClass a; // Calls the constructor, which throws an exception. // Destructor is not called and p1 is leaked. }
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 8
// Out-of-memory error.
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()
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
Review
1. 2. 3. 4. 5. 6. Can I play with data corruption and other madness? What is 2-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. 2-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 2-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
Version 1.0b1 Copyright 2010 Samsung Electronics Co., Ltd. All rightsLtd. All rights reserved 20 Copyright 2010 Samsung Electronics, Co., reserved.
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
ByteBuffer
Number Character Double DoubleComparer Float FloatComparer Int8 Int8Comparer Integer IntegerComparer
22
Provided by
LongLong
LongLongComparer String StringComparer 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...
Methods
Append() Insert() Remove() Appends the indicated value to the String. Inserts the indicated value at the position. Removes characters within the specified range.
IndexOf()
SubString() ToUpper() ToLower()
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 long unsigned short unsigned short unsigned char } UUID;
UuId Methods and Operators Parse() ToString() Parses a string representation of a UuId. Returns a string from a UuId.
operator!= (const UuId &uuid) Operators must be balanced on the operator== (const UuId &uuid) right side by something of type UuId that contains a UuId value. operator= (const UuId &uuid)
32
33
Buffer (1/3)
Buffers contain sequences of a specific primitive type, such as int, long, double, and char.
Buffer Properties
Capacity Limit
Position Mark
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. 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.
Buffer Methods
Clear() Flip()
Rewind()
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 Primitive Type
DoubleBuffer
FloatBuffer IntBuffer LongBuffer
double
float int long
LongLongBuffer
McharBuffer ShortBuffer
longlong
mchar short
38
Collection
Version 1.0b1 Copyright 2010 Samsung Electronics Co., Ltd. All rightsLtd. All rights reserved 39 Copyright 2010 Samsung Electronics, Co., reserved.
Contents
Essential Classes Relationships between Classes Overview Interfaces MapEntry ArrayList and LinkedList
Example: Construct and Modify an ArrayList Example: Create and Modify a LinkedListT
MapEntry
41
MapEntryT
42
IEnumerator
IList IMap IMultiMap IMapEnumerator IHashCodeProvider IComparer
43
IEnumeratorT
IListT IMapT IMultiMapT IMapEnumeratorT IHashCodeProviderT IComparerT
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
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.
HashMap Methods
Add() Remove() SetValue() GetValue() ContainsKey() ContainsValue() Adds a key-value pair. 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.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 58
1
Enqueue
3 2 1
1
61
62
ICompare
ICompare interface implementations compare two object values and get an integer result. A result of zero indicates equality. A negative or positive result 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
<0 == 0 >0
Means
Value1 is less than value2. Value1 is equal to value2. Value1 is greater than value2.
The StringComparer class tests for equivalence. That is, < 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
Version 1.0b1 Copyright 2010 Samsung Electronics Co., Ltd. All rightsLtd. All rights reserved 68 Copyright 2010 Samsung Electronics, Co., reserved.
Contents
Essential Classes and Relationships Synchronization Objects Mutexes and Semaphores Monitor
Example: Use a Monitor
Review Answers
69
Provides a timer.
Provides a synchronization primitive that grants exclusive access to a shared resource. Provides a synchronization object that maintains a count between zero and a maximum value. Provides for mutual exclusion with waiting and notification.
Timer
Mutex Semaphore Monitor
Thread
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(); mutex->Acquire(); // Use shared resource mutex->Release();
Semaphore
Semaphore* pSemaphore = new Semaphore; pSemaphore >Create(); semaphore->Acquire(); // Use shared resource semaphore->Release();
74
Monitor (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
Monitor (2/3)
The Wait(), Notify(), and NotifyAll() methods can only be called inside of a critical section, between an Enter() and an Exit() call.
Monitor Methods Enter() Marks the start of a critical section (block of code) and locks an object.
Exit()
Wait() Notify()
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.
76
Monitor (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.
a) 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
b)
a b
c)
d)
Object* Producer::Run(void) { result r; // Begin critical section r = __pMonitor->Enter(); // Wait for the Consumer to start r = __pMonitor->Wait(); // Produce number value 6 times for (int i = 0; i < 6; i++) { //See next page for loop details } // Exit the monitor r = __pMonitor->Exit(); return null; CATCH2: __pMonitor->Exit(); return null; }
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 81
Loop
a b
b)
c)
d)
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
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
Version 1.0b1 Copyright 2010 Samsung Electronics Co., Ltd. All rightsLtd. All rights reserved 97 Copyright 2010 Samsung Electronics, Co., reserved.
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
Base::Object
Math
StringUtil
StringTokenizer
Uri
99
Overview
The Utility namespace contains 4 useful utility classes: Math, StringTokenizer, StringUtil, and Uri.
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.
100
Math
The Math class wraps the native math library.
Mathematical Functions
Abs() Acos() Asin() Atan() Ceiling() Floor() Cos() Cosh() Exp() 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 and UTF-8 byte buffers with the StringUtil class.
StringUtil Methods GetStringLengthInMb() MbToString() StringToMbN() StringToUtf8N() Utf8ToString() 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.
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
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.
109
Review
1. What does a StringTokenizer do? 2. What class is best to create links to web sites?
110
Answers
1. It splits strings on pre-defined characters with the defaults being the space, form feed, new line, and tab characters. 2. Uri.
111
Io
Version 1.0b1 Copyright 2010 Samsung Electronics Co., Ltd. All rightsLtd. All rights reserved 112 Copyright 2010 Samsung Electronics, Co., reserved.
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
114
Base::Object
Io::File
Io::Directory
Io::Registry
Io::Database
115
Overview
The Io namespace resides under the Base namespace, and 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.
116
/Home
/Home/Share
/Share/[appid]
Used to read data for other bada applications. (The shared data application ID must be known beforehand.)
Read-only
117
Read-only Read-only Io
/Media/Videos /Media/Themes
/Media/Others
/Storagecard/Media/Images
/Storagecard/Media/Sounds /Storagecard/Media/Videos
/Storagecard/Media/Themes
/Storagecard/Media/Others
118
DirEnumerator facilitates iterating over directories to get information on what directories and files they contain.
Directory1 /Directory1
DirEnumerator
Directory2 Directory3
Directory4
/Directory2 /Directory3 /Directory4
119
121
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 Name Kevin Joe Mark Address New York New York New York
ID 0 2 3
2
3 4 5
Joe
Mark Robert Moe
New York
New York Seattle Boston
122
123
4
5
Robert
Moe
Seattle
Boston
124
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
125
126
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.
127
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.
128
Answers
1. False. It is certainly possible to have an empty directory. 2. False. You must use bada-compatible SQL. 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.
129
System
Version 1.0b1 Copyright 2010 Samsung Electronics Co., Ltd. All rightsLtd. All rights reserved 130 Copyright 2010 Samsung Electronics, Co., reserved.
Contents
Essential Classes and Relationships Overview SystemTime
Example: Get System Time
SystemInfo
Example: Get System Information
RuntimeInfo
Example: Get Available Memory
SettingInfo
Example: Get Language and Country Code
Battery
Example: Get the Battery Level
Alarm
Example: Create a Daily Alarm
Vibrator
Example: Vibrate the Device
Review Answers
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 131
SystemInfo
SystemTime
Battery
Vibrator
Alarm
132
Overview
The System namespace provides device-related information and access to some device features:
System time and uptime. Alarm service. Operating the vibrator device. Battery level and charging status.
133
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.
134
135
SystemInfo
You can get information about system properties and capabilities through SystemInfo by querying a SystemInfo key. Key values are one of UuId, double, int, or string.
Some Popular System Information Keys
PhoneNumber
ScreenHeigth PlatformVersion PlatformVersionPatch KeyboradType VideoRecordingCodecs GPSSupported
IME
ScreenWidth PlatformVersionMajor PlatformVersionIdentifier NetworkType BluetoothSupported
RSSI
ScreenBitsPerPixel PlatformVersionMinor OpenGLESVersion CameraCount WiFiSupported
136
137
RuntimeInfo
You can get information about memory usage through the RuntimeInfo class:
Key
AllocatedMemory AvailableMemory
Memory used by application Memory available to application System-wide available video memory Available storage
Description
Returns the amount of memory used by the application. Returns the amount of memory available to the application.
AvailableVideoMemory
AvailableInternalStorage AvailableExternalStorage BatteryLevel
IsCharging
All RuntimeInfo methods are static, so you do not need to create an instance of RuntimeInfo to use it.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 138
139
SettingInfo
You can get information about settings through the SettingInfo class:
Key
SilentMode GPSEnabled Language Country
Description
This value indicates whether the phone is in silent mode. This value indicates whether use of the GPS is permitted by the user. This value indicates the current language setting in ISO 639-2 format. This value indicates the current country setting in ISO 3166-1 alpha-2 format.
All SettingInfo methods are static, so you do not need to create an instance of SettingInfo to use them.
140
141
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
142
143
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.
144
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)
145
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:
Multiple Vibration Parameters Vibrate on period Vibrate off period Vibration count Vibration level (amplitude) Length to vibrate for in ms. Length to pause vibration for in ms. Number of times to vibrate. Vibration intensity from 0 ~ 100.
Vibrate on period Vibration level (amplitude) on off on Vibrate off period off on off
Count = 3
146
147
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?
148
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.
149
Debugging
Version 1.0b1 Copyright 2010 Samsung Electronics Co., Ltd. All rightsLtd. All rights reserved 150 Copyright 2010 Samsung Electronics, Co., reserved.
Contents
Overview AppAssertion() AppAssertionf() AppLog~ TryCatch() Debugging Output
151
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:
AppAssertion(condition) AppAssertionf(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. 152
AppAssertion()
The AppAssertion() 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();
AppAssertion(r == E_SUCCESS);
return r; }
153
AppAssertionf()
The AppAssertionf() 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. AppAssertionf(r == E_SUCCESS, "Mutex Release Failed"); return r; }
154
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; }
155
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; }
156
Debugging Output
AppAssertion() family:
Assert expression Line number
File name
Detailed message
Timestamp
Used internally
Fully-qualified name
Log message
158