Getting GLib events in Symbian UI applications

Symbian UI applications run an event loop that is based on CActiveScheduler. The active scheduler is started by the UI framework immediately after the UI has been created (that is after ConstructL() of CEikAppUi-derived class).

To receive events from GLib event sources, an active object can be added to the active scheduler especially for this purpose. The active object runs one iteration of the glib event loop every time it gets scheduled.

Note: The scheduling logic in the sample code provided below is based on a simple timer; more complex scheduling logic can be implemented depending on the requirement of the application.
/********* GlibEventHandler.h *********************/

class CGlibEventHandler: public CActive
{
public:
	static CGlibEventHandler* NewL();
	~CGlibEventHandler();
       void RunL();
       void DoCancel();
       void Start();
       void Stop();
private:
       CGlibEventHandler();
       void ConstructL();	
       RTimer iTimer;
};

/********* GlibEventHandler.h *********************/


/********* GlibEventHandler.cpp *******************/

CGlibEventHandler* CGlibEventHandler::NewL()
{
       CGlibEventHandler* self = new(ELeave) CGlibEventHandler();
       CleanupStack::PushL(self);
       self->ConstructL();
       CleanupStack::Pop();
       return self;
}

CGlibEventHandler::CGlibEventHandler():CActive(EPriorityStandard)
{
}
	
void CGlibEventHandler::ConstructL()
{
	User::LeaveIfError(iTimer.CreateLocal());
	CActiveScheduler::Add(this);	
}

CGlibEventHandler::~CGlibEventHandler()
{
	Cancel();
	iTimer.Close();		
}

void CGlibEventHandler::Start()
{
	iTimer.After(iStatus, TTimeIntervalMicroSeconds32(1000));
	SetActive();	
}
	
void CGlibEventHandler::Stop()
{
	Cancel();
}
	
void CGlibEventHandler::RunL()
{
	g_main_context_iteration(NULL, FALSE);
	iTimer.After(iStatus, TTimeIntervalMicroSeconds32(1000));
	SetActive();	
}
	
void CGlibEventHandler::DoCancel()
{
	iTimer.Cancel();	
}

/********* GlibEventHandler.cpp *******************/

The following is done in the application:

GMainLoop* mainloop = g_main_loop_new(NULL, FALSE);
CGlibEventHandler* glibeventhandler = NULL;
glibeventhandler = CGlibEventHandler::NewL();
glibeventhandler->Start();