Vous êtes sur la page 1sur 158

bada Tutorial: Fundamentals

(Idioms, Base, Io, System, Debugging)

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

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

Methods Exception Handling Ownership Policy Review Answers

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

Classes and Interfaces (1/2)


Most classes in bada derive from the Object class.
Exceptions: Classes that have only static methods.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

Classes and Interfaces (2/2)


When using inheritance, do not use the virtual keyword, as it can cause problems on the bada target with the currently supported targeting environment and tool chain.
Recommended
public class MyForm :public Osp::Ui::Controls::Form, public Osp::Ui::IActionEventListener { InheritedClass(void); ~ InheritedClass(void);

Not Recommended
public class MyForm :public Osp::Ui::Controls::Form, virtual public Osp::Ui::IActionEventListener { InheritedClass(void); ~ InheritedClass(void);

}; };

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

2-Phase Construction: Motivation


In C++, when a failure occurs in allocating resources during an objects construction, the object is partially constructed and its destructor is not called, possibly causing a resource leak.
class SimpleClass; class ComplexClass { public: ComplexClass (void) { SimpleClass* p1 = new SimpleClass(); SimpleClass* p2 = new SimpleClass(); }

// 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

2-Phase Construction: Construct Method


To prevent resource leaks, resource allocation logic is extracted out of the constructor, and put into the Construct() method.
1. Object obj; class TwoPhaseClass 2. obj.Construct() { public: TwoPhaseClass(void) : p1(null), p2(null) { } ~TwoPhaseClass(void) { delete p1; delete p2; }
result Construct(void) { SimpleClass * p1 = new SimpleClass(); SimpleClass * p2 = new SimpleClass(); } private: SimpleClass* p1; SimpleClass* p2; }; void MyClass::SomeFunction() { TwoPhaseClass a; // Calls the constructor which does not throw an exception. // Calls the Construct() method which allocates two SimpleClass objects. // Destructor is called because a itself is fully constructed. result r = a.Construct(); }
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 9

// Allocate memory. // Construct object.

// 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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

10

Exception Handling (1/4)


Samsung bada uses error results instead of C++ exceptions. C++ exceptions require too large of a runtime for resource-constrained devices and incur too much overhead. All exceptions are caught as the return type result:
The E_SUCCESS result indicates a method succeeded, while all other result values indicate an error. GetLastResult(): Returns the last exception or that set by SetLastResult(). SetLastResult(): Changes the result value. GetErrorMessage(): Returns a char* containing a results message.

There are 3 result reporting method types:


a) result SomeClass::DoSomething()
Result of the method execution is passed as a return value. The method returns pointer of some class if the method execution succeeds, while it returns null if an exception occurs. Calling GetLastResult() after execution of this method gives you the last result (exception). This method returns by value (including void) and you dont need to check the exception in this case.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 11

b) SomeClass* SomeClass::DoSomething()

c) Value-type (or void) SomeClass::DoSomething()

Exception Handling (2/4)


The following demonstrate three different ways to detect errors:
result r = E_SUCCESS; ... // Case 1: The method returns a result. r = list.Construct(...); if (r != E_SUCCESS) // identical to 'if (IsFailed(r))' { // Process the error condition. } // Case 2: The method sets the result in the method body or returns null. pObj = list.GetAt(...); if (GetLastResult() != E_SUCCESS) // or 'if (pObj == null)' { // Process the error condition. } // Case 3 r = pObj2->Construct(..); TryCatch(r == E_SUCCESS, , "[%s] Service could not be initialized.", GetErrorMessage(r)); ... If false goes to CATCH CATCH: delete pObj1; delete pObj2; return;
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 12

Exception Handling (3/4)


The following 4 cases demonstrate handling (propagating) and converting exceptions:
result r = E_SUCCESS; ... goto CATCH condition // Case 1: Use a goto CATCH. r = pList->Construct(...); TryCatch(r == E_SUCCESS, delete pList, "[%s] Propagated.", GetErrorMessage(r)); ... CATCH: SetLastResult(r); Change 'result' value return null; // Case 2: Return a result. r = list.Construct(...); TryReturn(r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r); // Case 3: Return null. r = list.Construct(...); TryReturn(r == E_SUCCESS, null, "[%s] Propagated.", GetErrorMessage(r); // Case 4: Convert an error condition into another error condition. r = list.indexOf(...); TryReturn(r == E_SUCCESS, E_INVALID_ARG, "[E_INVALID_ARG] converted from '%s'.", GetErrorMessage(r));

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

13

Exception Handling (4/4)


Log fields are comma separated. Interpreting log exception messages:
Prefix for exception log Timestamp Used internally Fully-qualified name Line number

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)

Complex objects are represented as shown below:


0050.989,EXCEPTION,.. (), > [..] Thread(name:Consumer priority:5 ...) ..

Object (property1:value1 property2:value2 ...)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

14

Ownership Policy (1/3)


Ownership implies responsibility to delete dynamically allocated memory and avoid memory leaks. That is, whatever owns an object MUST delete it when it is finished. For example:
Object* pObj = new Object(); ... delete pObj; // Must be deleted to avoid a memory leak.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

15

Ownership Policy (2/3)


Exclusive ownership means that the ownership cannot be shared. There are 2 rules for obtaining ownership:
The new operator takes ownership of the allocated memory space. Ownership can be transferred, but it cannot be shared.

Ownership pObject1 Ptr

Heap

Object1 pObject2 Ptr

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

16

Ownership Policy (3/3)


If a method has an N postfix, the caller MUST delete the returned instance after the caller is finished with the object. Otherwise, the memory for the object is leaked.
Class ArrayList { public: IList* SearchN(const String& criteria) const; }; 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 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?

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

DateTime and TimeSpan


Example: Create and Use DateTimes

UuId
Example: Create a UuId

Buffer
Example: Use Buffers

FAQ

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

21

Essential Classes (1/2)


Feature
Provides the root class for most classes in bada. Wraps the native bool. Provides a parameterized class for the primitive array type. Provides the base class for buffers. Object Boolean Buffer BufferBase

Provided by

Wraps the native byte (unsigned 8-bit integer) array.


Provides the abstract base for all numeric value types. Wraps the native mchar (Unicode character). Wraps the native double. Enables comparing Doubles. Wraps the native float. Enables comparing Floats. Wraps the native char (signed 8-bit integer). Enables comparing Int8s. Wraps the native int (singed 32-bit integer). Enables comparing Integers.

ByteBuffer
Number Character Double DoubleComparer Float FloatComparer Int8 Int8Comparer Integer IntegerComparer

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

22

Essential Classes (2/2)


Feature
Wraps the native short (signed 16-bit integer). Enables comparing Shorts. Wraps the native long (singed 32-bit integer). Enables comparing Longs. Short ShortComparer Long LongComparer

Provided by

Wraps the native long long (singed 64-bit integer).


Enables comparing LongLongs. Represents a Unicode string. Enables comparing Strings. Enables comparing primitive types. Represents a date and time. Represents an amount of time in milliseconds. Wraps the native UUID.

LongLong
LongLongComparer String StringComparer ComparerT DateTime TimeSpan UuId

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

23

Relationships between Classes

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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()

Returns the index of the character.


Returns the indicated substring. Converts all letters to upper case. Converts all letters to lower case.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 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.

String str(Ltest); str.Append(L String); // test String

str.ToUpper();
str.Remove(0, 4);

// TEST STRING
// STRING

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

27

Example: Create and Modify Strings


Learn how to use the String class.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ BaseExample.cpp, StringExample() 1. Create an empty String. 2. Append an integer value to the String instance: String::Append(value) 3. Insert text into the String instance: String::Insert(value, atPosition) 4. Create a String instance with some text: String::String(value) 5. Get a substring from the String instance: String::SubString(start, end, string)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

28

DateTime and TimeSpan (1/2)


A DateTime represents an instance of a specific date and time ranging from 12:00:00 am (Midnight), January 1, 1 A.D., to 11:59:59 pm, December 31, 9999 A.D. A TimeSpan represents a time duration measured in milliseconds. DateTime vs. TimeSpan:
A DateTime represents a single instant in time where a TimeSpan represents an amount of time. Both include addition and subtraction methods. You cannot add 2 DateTimes together. You can add a TimeSpan to a DateTime to get a second DateTime. You can add a TimeSpan to a TimeSpan to get a second TimeSpan.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

29

DateTime and TimeSpan (2/2)


Set DateTimes values with:
Year, month, and day Year, month, day, hour, minutes, and seconds Another DateTime A TimeSpan since January 1, 1 A.D. 00:00:00 am

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

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

30

Example: Create and Use DateTimes


Learn how to use the DateTime class.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ BaseExample.cpp, DateTimeExample() 1. Create a DateTime instance. 2. Set the DateTime instance year, month, and day: DateTime::SetValue(yyyy, mm, dd) 3. Add several years to the DateTime instance: DateTime::AddYears(years) 4. Add several months to the DateTime instance: DateTime::AddMonths(months) 5. Add several days to the DateTime instance: DateTime::AddDays(days) 6. Get the year portion from the DateTime instance: DateTime::GetYear() 7. Get the month portion from the DateTime instance: DateTime::GetMonth() 8. Get the day portion from the DateTime instance: DateTime::GetDay() Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

x; s1; s2; c[8];

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)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

32

Example: Create a UuId


Parse a String to create a UuId.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ BaseExample.cpp, UuIdExample() 1. Create a UuId instance. 2. Create a String that contains a UUID value. 3. Parse the String with the UuId: UuId::Parse(string) 4. Get a String representation of the UuId instance: UuId::ToString()

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

ByteBuffer buf; buf.Construct(10);

// //

position: 0 limit, capacity: 10

buf.SetPosition(7); buf.Flip();

// // //

position: 7 position: 0 limit: 7, capacity: 10


Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 35

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

36

Example: Use Buffers


Learn how to use the Buffer class.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ BaseExample.cpp, BufferExample() 1. Construct an IntBuffer with a specified capacity: IntBuffer::Construct(size) 2. Declare an array of integers. 3. Copy all values from the integer array to the IntBuffer instance: IntBuffer::SetArray(array, index, length) 4. Construct a DoubleBuffer with the same size as the IntBuffer: DoubleBuffer::Construct(size) 5. Read a value from the IntBuffer and write it to the DoubleBuffer: IntBuffer::Get(value) DoubleBuffer::Set(value)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

HashMap and MultiHashMap


Example: Construct and Use a HashMap

Stack and Queue


Example: Construct and Use a Stack

ICompare FAQ Review Answers


Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 40

Essential Classes (1/4)


Feature Represents a last-in, first-out (LIFO) collection. Represents a first-in, first-out (FIFO) collection. Represents a collection that is individually accessed by index. Represents a collection that is sequentially accessed. Represents a collection of key-value pairs that are organized based on the keys hash code. Represents a collection of key-value pairs that are organized based on the keys hash code. Duplicated keys are allowed, but key-value pairs must be unique. Represents a key-value pair. Stack Queue ArrayList LinkedList HashMap MultiHashMap Provided by

MapEntry

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

41

Essential Classes (2/4)


Feature Represents a first-in, last-out template-based collection Represents a first-in, first-out template-based collection Represents a template-based collection that is individually accessed by index. Represents a template-based collection that is sequentially accessed. Represents a template-based collection of key-value pairs that are organized based on the keys hash code. Represents a template-based collection of key-value pairs that are organized based on the keys hash code. Duplicated keys are allowed, but key-value pairs must be unique. Represents a template-based key-value pair. StackT QueueT ArrayListT LinkedListT HashMapT MultiHashMapT Provided by

MapEntryT

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

42

Essential Classes (3/4)


Feature Represents a collection of objects, and defines the size, enumerator, and synchronization mechanism. Provided by ICollection

Enables iteration over a collection.


Represents a collection that is accessed by index. Represents a collection of key-value pairs. Represents a collection of key-value pairs that may have duplicated keys. Enables iteration over a map. Represents a collection of key-value pairs indexed by the keys hash value. Enables comparisons of two objects.

IEnumerator
IList IMap IMultiMap IMapEnumerator IHashCodeProvider IComparer

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

43

Essential Classes (4/4)


Feature Represents a template-based collection of objects, and defines the size, enumerator, and synchronization mechanism. Provided by ICollectionT

Enables iteration over a template-based collection.


Represents a template-based collection that is accessed by index. Represents a template-based collection of key-value pairs. Represents a template-based collection of key-value pairs that may have duplicated keys. Enables iteration over a template-based map. Represents a template-based collection of key-value pairs indexed by the keys hash value. Enables comparisons of two template-based objects.

IEnumeratorT
IListT IMapT IMultiMapT IMapEnumeratorT IHashCodeProviderT IComparerT

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

44

Relationships between Classes (1/2)


Object-based collections

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

45

Relationships between Classes (2/2)


Template-based collections

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

String* pStr = new String(L"One"); list.Add(*pStr);

Template-based collections are mainly used for primitive types.


ArrayListT<int> list; list.Construct(); int value = 10; list.Add(value);

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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()

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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()

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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 methods: GetKey() GetValue() GetCurrent()

IMapEnumerator

IBidirectionalEnumerator

IBidirectionalEnumerator methods: MovePrevious() ResetLast()

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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()

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

53

ArrayList and LinkedList


An ArrayList is a collection of objects that can be individually accessed by index. The capacity of an ArrayList is the number of elements the list can hold. As elements are added to a list, the capacity is automatically increased as required through reallocation. The default capacity is 10. A LinkedList is a collection of objects that can be sequentially accessed.
List Methods
SetCapacity() Add() RemoveAt() Contains() GetAt() SetAt() Sets the list capacity. Adds an object to the end of the list. Removes an object at an index. Returns true if the list contains the specified object. Gets the object at the specified index. Replaces an object at the specified index with another object.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

54

Example: Construct and Modify an ArrayList


Learn how to use an ArrayList.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ CollectionExample.cpp, ArrayListExample()
1. Construct an ArrayList: ArrayList::Construct() 2. Add elements to the list: ArrayList::Add(object) 3. Get an element from the list: ArrayList::GetAt(index) 4. Insert an element into the list: ArrayList::InsertAt(object, index) 5. Remove an element from the list: ArrayList::Remove(object) ArrayList::RemoveAt(index) 6. Sort the list: ArrayList::Sort(comparer) 7. Get an enumerator and use it to access elements in the list: ArrayList::GetEnumeratorN() 8. Delete all elements in the list: ArrayList::RemoveAll()
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 55

Example: Create and Modify a LinkedListT (1/2)


Learn how to use a LinkedListT.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ CollectionExample.cpp, LinkedListTExample() 1. Create a LinkedListT.

2. Add elements into the list: LinkedListT::Add()


3. Get all elements from the list: LinkedListT::GetAt()

4. Insert an element into the list: LinkedListT::InsertAt()


5. Sort the list: LinkedListT::Sort() 6. Remove an element from the list: LinkedListT::Remove() LinkedListT::RemoveAt()
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 56

Example: Create and Modify a LinkedListT (2/2)


7. Remove an element at a specified index from the list: LinkedListT::RemoveAt() 8. Get an enumerator and use it to iterate through the list: LinkedListT::GetEnumeratorN()

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

57

HashMap and MultiHashMap


A HashMap is a collection of associated key-value pairs that are organized based on the hash code of the key. The default capacity is 16. HashMaps cannot contain duplicate keys. Each key maps to one value.

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

Example: Construct and Use a HashMap


Learn how to use a HashMap:
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \CollectionExample.cpp, HashMapExample() 1. Construct a HashMap: HashMap::Construct() 2. Add key-value pairs to the HashMap: HashMap::Add() 3. Use a key to get a value: HashMap::GetValue() 4. Use a key to remove a value: HashMap::Remove() 5. Get an enumerator and use it to iterate through the HashMap: HashMap::GetMapEnumeratorN()

6. Delete all key-value pairs: HashMap::RemoveAll()


Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 59

Stack and Queue (1/2)


A stack is a last-in, first-out (LIFO or FILO) collection of objects. If the stack reaches its capacity, the capacity is automatically increased to accommodate more elements.
Methods Push() Pop() Peek() Inserts an object at the top of the stack. Gets and removes the object at the top of the stack. Gets the object at the top of the stack without removing it.

A queue is a first-in, first-out (FIFO) collection of objects.


Objects stored in a queue are inserted at one end and removed from the other. Capacity is automatically increased to accommodate more elements.
Methods Enqueue() Dequeue() Inserts an object at the end of the queue. Gets and removes the element at the beginning of the queue.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 60

Stack and Queue (2/2)


LIFO stack
Push Pop

1
Enqueue

3 2 1

Stack: 3 is Last In, so it is, First Out.

Queue: 1 is First In, so it is, First Out.


FIFO queue
Dequeue

1
61

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

Example: Construct and Use a Stack


Learn how to use a stack.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \CollectionExample.cpp, StackExample() 1. Construct a stack and specify its capacity: Stack::Construct(capacity) 2. Push an element onto the stack: Stack::Push(object) 3. Peek at an element to view its value without removing it: Stack::Peek() 4. Pop an element from the stack to get its value and remove it: Stack::Pop() 5. Delete all elements from the stack: Stack::RemoveAll()

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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?

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

66

Answers
1. LIFO or FILO. 2. FIFO. 3. IMapEnumerator::GetCurrent().

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

Threading Thread-safety Thread Types Thread Programming Timer


Example: Periodic Timer

Review Answers

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

69

Essential Classes and Relationships


Feature Provided by

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

Provides a thread class that can be inherited.


<<interface>>

Thread

IRunnable

Mutex

Semaphore

Thread

Monitor

Timer

ITimerEventListener

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

Example: Periodic Timer


Create a timer and reset it in the event handler so that it mimics a periodic timer.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \RuntimeExample.cpp, TimerExample()

1. Create a class and implement an ITimerEventListener in it.


2. Create a timer. 3. Initialize the timer and set the listener: Timer::Construct(listener)

4. Start the time: Timer::Start(milliseconds)


5. When the time elapses, set the time again in the event handler: Timer::Start(milliseconds)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

73

Mutexes and Semaphores


Methods:
Acquire(): Acquires the resource if it is not acquired. Release(): Releases the resource.

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();

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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();

Start critical section

Critical section

// 1) Do something. // 2) Wait, Notify, // or NotifyAll.


pMonitor->Exit(); End critical section

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

NotifyAll() Notifies all waiting threads. Thread execution continues.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

// 1) Do something. pMonitor->Wait(); // 3) Do something. pMonitor->Exit();

Transfers lock from B to A

Example: Use a Monitor (1/8)


Create 2 threads that pass access to a shared private resource between themselves. Producer produces (writes) the value for the shared resource, while Consumer consumes (reads) the value.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \RuntimeExample.cpp, ThreadExample() (Osp::Base::Runtime::Monitor)

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

78

Example: Use a Monitor (2/8)


Create the Producer class.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \RuntimeExample.cpp, ThreadExample() (Osp::Base::Runtime::Monitor)

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

Example: Use a Monitor (3/8)


Create the Consumer class.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \RuntimeExample.cpp, ThreadExample() (Osp::Base::Runtime::Monitor)
b) The Consumer Run() method waits for a notification from the Producer thread and reads the value of the shared resource (__pShared). It then notifies the Producer thread so that the producer thread can increment the value of the shared resource (__pShared).
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

Example: Use a Monitor (4/8)


Create the Producers Run() method.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ RuntimeExample.cpp, ThreadExample() (Osp::Base::Runtime::Monitor)
2. In the Producers Run() method:
a) Enter() the monitor. This marks the start of the critical section where the lock is obtained. Wait() for the Consumer to start. The entire process relies on both threads, so you must ensure that the other thread is alive. You do this letting the Producer thread wait here and calling Notify() at the beginning of the Consumer thread. Enter() the monitor. This marks the start of the critical section where the lock is obtained. Wait() for the Consumer to start. The entire process relies on both threads, so you must ensure that the other thread is alive. You do this letting the Producer thread wait here and calling Notify() at the beginning of the Consumer thread.

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

Example: Use a Monitor (5/8)


Create the Producers loop.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \RuntimeExample.cpp, ThreadExample() (Osp::Base::Runtime::Monitor)

During Step 2c, in the Producers Run() method:


The loop increments the shared integer, __pShared. It then passes control to the Consumer thread and continues execution. If __pShared is 5, the loop exits; otherwise execution continues and pauses until the Consumer thread passes control back. // Produce number value 6 times for (int i = 0; i < 6; i++) { *__pShared = i; // Notify consumer thread Pass control over to the Consumer r = __pMonitor->Notify(); thread and continue execution. if (*__pShared == 5) break; // Wait until consumer thread reads the value r = __pMonitor->Wait(); Pause for the Consumer thread. }
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 82

Loop

Example: Use a Monitor (6/8)


Create the Consumers Run() method.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ RuntimeExample.cpp, ThreadExample() (Osp::Base::Runtime::Monitor) Consumer::Run(void) { result r; // Begin critical region r = __pMonitor->Enter(); // Notify to producer thread r = __pMonitor->Notify(); // Wait for notification r = __pMonitor->Wait(); while (!IsFailed(r)) { //See next page for loop details } // Exit monitor r = __pMonitor->Exit(); return null; CATCH2: __pMonitor->Exit(); return null; }
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 83

3. In the Consumers Run() method (similarly to Step 2):


a) Enter() the monitor. This marks the start of the critical section where the lock is obtained. Pass control back to the Producer (tell it Consumer has started). The entire process relies on both threads, so you must ensure that both threads are running. You do this by waiting in the Producer thread and calling Notify() at the beginning of the Consumer thread. Loop. This is where you do all of the heavy-lifting for the Consumer. That is, this is the job or task that you want to perform. Exit() the monitor. This marks the end of the critical section where the lock is released.

a b

b)

c)

d)

Example: Use a Monitor (7/8)


Create the Consumers loop.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \RuntimeExample.cpp, ThreadExample() (Osp::Base::Runtime::Monitor)

During Step 3c, in the Consumers Run() method:


The loop in the Consumer thread only reads the shared resource (__pShared) and waits. while (!IsFailed(r)) { // Notify producer thread Pass control over to the Producer r = __pMonitor->Notify(); thread and continue execution. if (*__pShared == 5) break; Loop // Wait for notification Pause for the Producer thread. r = __pMonitor->Wait(); }

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

84

Example: Use a Monitor (8/8)


Create the Producer and Consumer.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \RuntimeExample.cpp, ThreadExample() (Osp::Base::Runtime::Monitor)

4. Create the Producer:


Producer::Producer(int* pShared, Monitor* pMonitor) : __pShared(pShared), __pMonitor(pMonitor) { }

5. Create the Consumer:


Consumer::Consumer(int* pShared, Ptr<Monitor> pMonitor) : __pShared(pShared), __pMonitor(pMonitor) { }
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 85

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

Thread 2 ... Thread n

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

88

Thread Programming (1/6)


Threading can be done in 2 ways:
a) Define a new class and inherit from Thread:
Implement any or all of Threads 3 virtual methods:
OnStart() Run() OnStop() class MyThread: public Thread { //... }

You can use the default implementation of the Run() method for event-driven threads. (That is, you do not need to implement IRunnable.)

b)

Define an IRunnable object and pass it to a thread instance:


Threads execute the Run() method in an Irunnable implementation. You can execute any IRunnable object by passing it to a thread.

class MyRunnable: public IRunnable, public Object{ //... }

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

89

Thread Programming (2/6)


Where worker threads run in a linear fashion, event-driven threads, as their name implies, run based on events and loop until they receive an event notification to stop. Worker thread
OnStart()

Event-driven thread
OnStart()

Runs linearly

Main body of execution for thread.

Run()

Run until exit event

Main body execution continues its eventloop until it receives an exit event notification to stop.

Threads exit here.

OnStop()

OnStop()
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 90

Thread Programming (3/6)


The following example shows a worker thread where an instance (pTask) of an IRunnable implementation (CMyTask) is passed to a Thread instance (pThread).
CMyTask* pTask = new Task; Thread* pThread = new Thread; pThread->Construct(*pTask); pThread->Start(); delete pThread; delete pTask; class CMyTask : public IRunnable, public Object { public: CMyTask(void); ~CMyTask(void); public: void* Run(void); } CMyTask::CMyTask(void) { // ... } ~CMyTask::CMyTask(void) { // ... } void* Run(void) { // ... }

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

91

Thread Programming (4/6)


class CMyWorker : public Thread { public: CMyWorker(void); ~CMyWorker(void); result Construct(void); public: bool OnStart(void); void OnStop(void); void* Run(void); } CMyWork::CMyWorker(void) { // ... } ~CMyWorker::CMyWorker(void) { // ... }

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; }

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

92

Thread Programming (5/6)


The following example demonstrates a timer in an event-driven thread. The code immediately below shows the interface. The implementation follows immediately after.
class CTimerThread : public ITimerEventListener, public Thread { public: CTimerThread (void); ~CTimerThread (void); result Construct(void); public: bool OnStart(void); void OnStop(void); public: void OnTimerExpired(Timer& timer); private: Timer* __pTimer; } CTimerThread::CTimerThread(void) :__pTimer(null) { } ~CTimerThread::CTimerThread(void) { }

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

93

Thread Programming (6/6)


This example shows the implementation for a timer that resets every 60 seconds.
result CTimerThread::Construct(void) { result r = E_SUCCESS; r = Thread::Construct(THREAD_TYPE_EVENT_DRIVEN); } void CTimerThread::OnTimerExpired(Timer& timer) { __pTimer->Start(60*1000); } result CTimerThread::OnStart(void) { __pTimer = new Timer; __pTimer->Construct(*this); __pTimer->Start(60*1000); 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?

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

FAQ Review Answers


Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 98

Essential Classes and Relationships


Feature Wraps the native math libraries. Splits strings at specified delimiters. Converts between strings and McharBuffers and UTF-8 ByteBuffers. Facilitates building and analyzing URIs. Math StringTokenizer StringUtil Uri Provided by

Base::Object

Math

StringUtil

StringTokenizer

Uri

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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()

double value1 = 2.0; double value2 = Math::GetPi();

// 3.141592...

double minValue = Math::Min(value1, value2); // 2.0

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

101

Example: Get the Area of a Circle


Get the area of a circle.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ UtilityExample.cpp, MathExample() 1. Get the area by multiplying by the radius squared (r2): Math::GetPi() Math::Pow(radius, 2)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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)

String str(Lbada Sample code); StringTokenizer st(str);

String token; st.GetNextToken(token); st.GetNextToken(token);

// bada // Sample

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

103

Example: Split a String into Tokens


Use the StringTokenizer class to split a string into tokens.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ UtilityExample.cpp, StringTokenizerExample() 1. Create a sample string instance. 2. Create a StringTokenizer with a string and a delimeter: StringTokenizer::StringTokenizer() 3. Check if there are more tokens. If not, go to step 6: StringTokenizer::HasMoreTokens()

4. Get the next token: StringTokenizer::GetNextToken()


5. Go to step 2. 6. End.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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"

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

105

Example: Convert a String


Convert a String into an McharBuffer.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ UtilityExample.cpp, StringUtilExample() 1. Create a sample String. 2. Convert the String to an McharBuffer: StringUtil::StringToMbN(string) 3. Get the length of the string in the McharBuffer: StringUtil::GetStringLengthInMb(mcharBuff) 4. Convert the McharBuffer back to a String: StringUtil::MbToString(mcharBuff, string)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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);

String scheme = uri.GetScheme(); // http String host = uri.GetHost(); // www.samsung.com

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

107

Example: Resolve a URI


Resolve one URI against another URI.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ UtilityExample.cpp, UriExample() 1. Create 2 Uris: Uri::SetUri() 2. Resolve one Uri against the other: Uri::Resolve() 3. Get the content of the Uri as a String and check the result: Uri::ToString()

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

109

Review
1. What does a StringTokenizer do? 2. What class is best to create links to web sites?

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

FAQ Review Answers


Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 113

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

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

114

Relationships between Classes

Base::Object

Io::File

Io::Directory

Io::Registry

Io::Database

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

116

bada File System (1/2)


Every bada application is assigned a private storage area in the file system when it is installed. This is the application home directory. There are simple rules regarding file system access:
Absolute paths are always used in the Io namespace. The path delimiter is a single slash (/). Applications can only access the following directories:
Directory Usage Home directory for bada applications. Used to share data with other bada application. It is strongly recommended that the application should remove data in this folder as soon as they are not needed anymore to save system storage. Permission Read and Write Read and Write Namespace for access methods Io Notes CWD (Current Working Directory) is not supported. Only absolute paths are allowed system-wide. The file system is case-sensitive by default. However, if the execution environment is WIN32, the file system is caseinsensitive.

/Home

/Home/Share

/Share/[appid]

Used to read data for other bada applications. (The shared data application ID must be known beforehand.)

Read-only

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

117

bada File System (2/2)


Directory Usage Used to read resource files, such as the icon file that was shipped with the application package. Used to read data provided by an app control by its name Used to read image data. Used to read sound data. Used to read video data. Used to read theme data. Used to read additional media data. 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. (To manipulate the user data stored here, use the Media namespace.) CWD (Current Working Directory) is not supported. Only absolute paths are allowed system-wide. The file system is case-sensitive by default. However, if the execution environment is WIN32, the file system is case-insensitive. Permission Read-only Namespace for access methods Io Notes /Res

/Share/AppControl/ [appcontrol-name] /Media/Images /Media/Sounds

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

Used to read additional media data in external memory.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

118

Directory and File


Directories and files behave the same as on most common file systems.
Directories can contain other directories and files.

DirEnumerator facilitates iterating over directories to get information on what directories and files they contain.
Directory1 /Directory1
DirEnumerator

Directory2 Directory3

Directory4
/Directory2 /Directory3 /Directory4

sun.gif rain.gif snow.gif

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

119

Example: Navigate a Directory


Get a list of files and directories in a specific directory.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ IoExample.cpp, DirectoryExample() 1. Construct a Directory to get the list of specific files in a directory: Directory::Construct(directoryName) 2. Use an enumerator to read the list of files: Directory::ReadN() 3. Move the DirEnumerator to the first position: DirEnumerator::MoveNext() 4. Get a DirEntry to retrieve file information: DirEnumerator::GetCurrentDirEntry() 5. Retrieve the file information through the DirEntry: DirEntry::GetName() DirEntry::GetFileSize() DirEntry::IsDirectory() DirEntry::IsReadOnly()... 6. Move the DirEnumerator to the next position: DirEnumerator::MoveNext() 7. Repeat steps 4 to 6.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 120

Example: Get File Attributes


Get different file attributes from a file.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ IoExample.cpp, FileAttributeExample() 1. Get the FileAttributes: File::GetFileAttributes() 2. Read the attributes from the FileAttributes: GetDateTime() GetFileSize() GetLastModifiedTime() IsDirectory() IsHidden() IsNomalFile() IsReadOnly() IsSystemFile()

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

121

Database
Database thread-safety is guaranteed with a mutex.
Mutex Database Mutex

Thread #1: Keeps the mutex and uses the database.

Thread #2: Tries to acquire the mutex to use the database, fails and is queued.

DbEnumerator facilitates data retrieval and iteration over columns

in query result sets.


DbEnumerator

ID 0 Name Kevin Joe Mark Address New York New York New York

Name Kevin Julie

Address New York Boston

ID 0 2 3

2
3 4 5

Joe
Mark Robert Moe

New York
New York Seattle Boston

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

122

Example: Create a Database and Table


Create a new database with a table.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ IoExample.cpp, TableExample() 1. Construct a new database: Database::Construct(dbFileName, false) 2. Execute SQL to create a table: Database::ExecuteSql(sql, true)

Note: You must use bada-compatible SQL.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

123

Example: Run a Query


Run a SELECT statement on a table.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ IoExample.cpp, QueryExample() 1. Construct an existing database: Database::Construct(dbFileName, false) 2. Create a SQL statement to bind variables: Database::CreateStatementN(sql) 3. Bind data to the SQL: DbStatement::BindString(varIndex, string) 4. Execute the SQL statement: Database::ExecuteStatementN() 5. Move the cursor to the next (first) position: DbEnumerator::MoveNext()
ID 0 1 2 3 Name Kevin Julie Joe Mark Address New York Boston New York New York

4
5

Robert
Moe

Seattle
Boston

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

125

Example: Read a Registry Entry


Create a registry section, name-value pair, and read the name-value pair.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src\ IoExample.cpp, RegistryExample()

1. Construct a new Registry: Registry::Construct(regName, true)


2. Create a section: Registry::AddSection(secName) 3. Add a name-value pair to the new section: Registry::AddValue(secName, entryName, value) 4. Get the value from the section using the entry name: Registry::GetValue(secName, entryName, valueOut)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

How can I handle text files?


Samsung bada does not differentiate between text files and other file types. This means that bada does not run any translation between CRLF and LF. (This is the same behavior as Unix and GNU Linux systems.) As a result, you need to understand the following guidelines:
In terms of opening and creating text files:
Do not use the b (binary) open mode flag with File::Construct(). (Although b open mode is recognized by File::Construct() for the purpose of code compatibility, it has no effect on actual file operations.)

In terms of text I/O:


Use File::Read (Osp::Base::String &) and File::Write(Osp::Base::String &), if you want to handle the file as unit of text.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

Essential Classes and Relationships


Feature Provides access to the system time and uptime. Provides system information. Provides information on battery levels and charge status. Provides access to the system alarm. Provides access to the system vibrator. SystemTime SystemInfo Battery Alarm Vibrator Provided by

SystemInfo

SystemTime

Battery

Vibrator

Alarm

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

You can get the current system uptime in milliseconds.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

134

Example: Get System Time


Get the current system time for UTC, standard, and wall time modes.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \SystemExample.cpp, SystemTimeExample() 1. Get the system time in UTC mode: SystemTime::GetCurrentTime(time) 2. Get the system time in standard mode: SystemTime::GetCurrentTime(STANDARD_TIME, time) 3. Get the system time in wall mode: SystemTime::GetCurrentTime(WALL_TIME, time)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

136

Example: Get System Information


Get the list of audio recording codecs available to the device.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \SystemExample.cpp, SystemInfoExample() 1. Construct a SystemInfo: SystemInfo::Construct() 2. Get the list of audio recording codecs from the system information: SystemInfo::GetValuesN(AudioRecordingCodecs, VALUE_TYPE_STRING)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

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.

IsCharging

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.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 138

Example: Get Available Memory


Get the amount of available memory.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \SystemExample.cpp, RuntimeInfoExample() 1. Get the available memory from RuntimeInfo: RuntimeInfo::GetValue(LAvailableMemory, value);

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

140

Example: Get Language and Country Code


Get the language and country code.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \SystemExample.cpp, SettingInfoExample() 1. Get the language and country codes from RuntimeInfo: RuntimeInfo::GetValue(LLanguage, language); RuntimeInfo::GetValue(LCountry, country);

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

142

Example: Get the Battery Level


Get the battery level as a percentage of the remaining battery life and check if the battery is currently being charged.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \SystemExample.cpp, BatteryExample()

1. Get the battery level in percent: Battery::GetCurrentLevelInPercentage()


2. Get whether or not the battery is being charged: Battery::IsCharging()

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

144

Example: Create a Daily Alarm


Create an alarm that goes off at the same time every day.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \SystemExample.cpp, AlarmExample() 1. Create a class and implement IAlarmEventListener in it.

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)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

146

Example: Vibrate the Device


Set the device to vibrate multiple times.
Open \<BADA_SDK_HOME>\Examples\Fundamentals\src \SystemExample.cpp, VibratorExample() 1. Construct a Vibrator: Vibrator::Construct() 2. Start the vibrator: Vibrator::Start(onPeriod, offPeriod, count, level) 3. Wait long enough for the vibration to finish: Thread::Sleep(milliseconds)

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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?

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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.

TryReturn(condition, value, message)


If the condition is false, print message and return value.

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; }

// Process dies if false.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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; }

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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; }

AppLogDebug() and AppLogException() work in a similar manner.

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

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; }

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

156

Debugging Output
AppAssertion() family:
Assert expression Line number

Assertion failed(input == 3),MyFile.cpp (675), > detailed message.

File name

Detailed message

AppLog() and AppLogDebug():


Prefix for user application log Line number

0021.381,INFO,00,34,MyNamespace::MyClass::MyMethod (675), > log message.

Timestamp

Used internally

Fully-qualified name

Log message

AppLogException() and Try family:


See Exception Handling in the Idioms section.
Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 157

Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved.

158

Vous aimerez peut-être aussi