Saturday, 16 April 2011

QuickStartGuide - Everything is asynchronous

Another area that bada is similar to Symbian - and indeed any other modern smartphone platform - is the way that it deals with asynchronous requests. In bada, almost any request, whether waiting for a response to an HTTP request, retrieving location information or getting information from one of the built in sensors, is dealt with asynchronously. In Symbian C++, asynchronous requests are wrapped up in ActiveObjects and managed by the ActiveScheduler object, which invokes the RunL() method of the appropriate ActiveObject when a response is received to an asynchronous request. This provides a form of co-operative multi-tasking within a single application thread.

In bada, responses to asynchronous requests are dealt with by listeners. For example, the proximity sensor is one of the sensors managed by the bada SensorManager class. Here’s the code which will register a listener to handle sensor events. pSensorManager contains an instance of the SensorManager class:

      // add the sensor event listener
    if (pSensorManager->IsAvailable(SENSOR_TYPE_PROXIMITY ))
          r = pSensorManager->AddSensorListener
               (*this, SENSOR_TYPE_PROXIMITY , minInterval, true);

The first parameter of the AddSensorListener() method is the listener object which handles sensor events. It is an object of the class ISensorEventListener. But we’re passing the form to act as the listener, so how does this work ? Well, ISensorEventListener is an interface class which the ProximityForm derives from:

class ProximityForm :
       public Osp::Ui::Controls::Form,
       public Osp::Uix::ISensorEventListener

      // ISensorEventListener method
       virtual void  OnDataReceived (Osp::Uix::SensorType sensorType,
                       Osp::Uix::SensorData &sensorData, result r);


Since ISensorEventListener  is an interface class,  it consists of pure virtual functions, all of which the class that derives from it must implement- this is the only form of multiple inheritance which bada supports. In the case of the ISensorEventListener, there is just one method: OnDataReceived. The ProximityForm must implement this to handle sensor related events:

void  ProximityForm::OnDataReceived (SensorType sensorType,
                                     SensorData &sensorData, result r)

        long time;
        sensorData.GetValue((SensorDataKey)PROXIMITY_DATA_KEY_TIMESTAMP , time);


To separate the user interface from the rest of the code, it’s common to provide another class, such as a manager class, to act as a listener, rather than the form.
In bada, most of the application processing is done in the main thread, but like both Symbian C++ and Qt, you can create multiple threads and synchronise thread handling using mutexes and semaphores.

No comments:

Post a Comment

Please don't post spam. Its tiresome.

Note: only a member of this blog may post a comment.