Sunday, November 18, 2007

How can I reduce the size of my GCCE-produced binaries?

GCCE-build binaries are significantly larger binaries than produced with the GCC toolchain prior to Symbian OS v9, and the RVCT 2.2. toolchain from Symbian OS v9. This is because it uses, as recommend, a low level of compiler optimisation (-O1).

You can reduce this binary size for the GCCE target by specifying the REL_OPTIMISATION value to -O2 in the toolchain configuration files:
\epoc32\tools\compilation_config\gcce.mk and
\epoc32\tools\compilation-config\armv5_abiv2.mk.

Tuesday, November 06, 2007

How to add a ring tone for a specific contact stored in contacts database.

void AddRingtoneForContactL(const TDesC& aRingtone,TContactItemId aId)
{
CContactDatabase* ContactDb = CContactDatabase::OpenL();
CleanupStack::PushL(ContactDb);

CContactItem* SelItem = ContactDb->OpenContactL(aId);
CleanupStack::PushL(SelItem);

TInt RIndex = SelItem->CardFields().Find(KUidContactFieldRingTone);

if (RIndex != KErrNotFound)
{
SelItem->RemoveField(RIndex);
}

CContactItemField* contactField = CContactItemField::NewLC(KStorageTypeText,KUidContactFieldRingTone);

contactField->TextStorage()->SetTextL(aRingtone);

contactField->SetLabelL(_L("tone"));
contactField->SetMapping(KUidContactFieldVCardMapUnknown);

contactField->SetId(2);

SelItem->AddFieldL(*contactField);
CleanupStack::Pop();//ContactField
ContactDb->CommitContactL(*SelItem);

CleanupStack::PopAndDestroy(2);//ContactDb,SelItem
}

Saturday, November 03, 2007

How to launch a message editor

         CClientMtmRegistry *cltReg = CClientMtmRegistry::NewL( *iSession );
CleanupStack::PushL( cltReg );

CBaseMtm *mtm = cltReg->NewMtmL( aEntry.iMtm );
CleanupStack::PushL( mtm );

CMtmUiRegistry *reg = CMtmUiRegistry::NewL( *iSession );
CleanupStack::PushL( reg );

CBaseMtmUi *ui = reg->NewMtmUiL( *mtm );
CleanupStack::PushL( ui );

mtm->SwitchCurrentEntryL( aEntry.Id() );
//Editor are embedded.
ui->SetPreferences( EMtmUiFlagEditorPreferEmbedded );

CMsvOperationActiveSchedulerWait *waiter = CMsvOperationActiveSchedulerWait::NewLC();

CMsvOperation* op = ui->ViewL( waiter->iStatus );

waiter->Start();

delete op;
CleanupStack::PopAndDestroy( 5, cltReg );

How to change the GCC-E optimization level to speed up your application

It is possible to change the default level of optimization used by GCC-E. This may result in code running up to three or four times as fast on the phone.

In the SDK, find the file epoc32\tools\compilation_config\GCCE.mk and edit it with a text editor.

Search for the lines:

#------------------------------------------------------------------------------------------------------------------------------
# Release Mode Options
#------------------------------------------------------------------------------------------------------------------------------

# Optimization Level in RELEASE mode
REL_OPTIMISATION=

Change the last line so that it reads:

REL_OPTIMISATION= -O2 -fno-unit-at-a-time

(You can find more information on the optimization options of GCC at http://gcc.gnu.org/onlinedocs/gcc-4.1.1/gcc/Optimize-Options.html#Optimize-Options)

Once you have changed this file, go to your project. Type abld clean to ensure any existing object files are deleted, then build your project as usual.

Note 1: turning up the optimization level will make it more likely that your code makes assumptions which aren't honored by the compiler. If your code doesn't behave as it should, try setting back the optimization level to its initial setting.

Note 2: as explained in the GCC documentation, there are some compatibility issues with unit-at-a-time mode (enabled by -O2), hence the suggestion to disable it.

Note 3: a developer has reported getting the linker error: "undefined reference to `typeinfo for MTmTextLayoutForwarder'". This was solved by adding the following line to the mmp file: "LIBRARY form.lib tagma.lib".
Change softkeys dynamically (either right or left or both)
The article shows how Softkeys (not CBA) can be changed dynamically. Either left or right or both can be changed.
Changing right softkey
Cba()->RemoveCommandFromStack(2, EBack);
Cba()->AddCommandToStackL(2,ECancel,_L("Cancel"));
Cba()->DrawDeferred();

So instead of handling EBack in HandleCommandL ECancel will be handled.
Similarly the left softkey can be changed by
Cba()->RemoveCommandFromStack(0, ESave);
Cba()->AddCommandToStackL(0,EOk,_L("Ok"));
Cba()->DrawDeferred();

Note
•Header File - #include
•Link against - eikcoctl.lib
How to know which defined in your environment.
You can use "abld build -v" to see which macros are actually defined in your environment.

Sunday, October 28, 2007

Minimal Symbian V9.x FrameWork Required to Start a Console Application

Assuming that my Applcation name is MyApp.exe

MyApp_req.rss

#include <appinfo.rh>

UID2 KUidAppRegistrationResourceFile
UID3 0x<your UID>

RESOURCE APP_REGISTRATION_INFO
{
app_file="MyApp";
}

MyApp.MMP to Compile registration file.
START RESOURCE    <your app>_reg.rss
#ifdef WINSCW
TARGETPATH \private\10003a3f\apps
#else
TARGETPATH \private\10003a3f\import\apps
#endif
END


Add this line your PKG File to install the registration File {MyApp_reg.rSC}
"...epoc32\release\data\z\\private\10003a3f\import\apps\MyApp_reg.rsc"-"!:\private\10003a3f\import\apps\MyApp_reg.rsc"
MD5 HexDigest for Symbian

SymbianOS provides a CMD5 class for hashing 8-bit strings, but neglects to supply a hexdigest function to supply the Hash as a hex string, as required by many web services such as Flickr.

Calling CMD5::Hash() returns an 8bit binary descriptor of the hash. This snippet of code provides the HEX representation in ASCII in line with what HexDigest() returns in java and python etc.

 HBufC8* Md5HexDigestLC(const TDes8& aString)
{
CMD5* md5 = CMD5::NewL();
CleanupStack::PushL(md5);

TPtrC8 hashedSig(md5->Hash(aString));

HBufC8* buf = HBufC8::NewL(hashedSig.Length() * 2);
TPtr8 bufPtr = buf->Des();

for(TInt i=0; i< hashedSig.Length(); i++)
{
bufPtr.AppendFormat(_L8("%+02x"),hashedSig[i]);
}
CleanupStack::PopAndDestroy(md5);
CleanupStack::PushL(buf);
return buf;
}
Get a Error Code with Python Script.

The code below Download error code reference from NewLC and stores the error code reference to a c:/temp folder. Forgetting error meaning just pass error code as argument like below.

python geterr -11


The Script is as below


import urllib
import re
import os
import pickle
import sys

temp = "c:\\temp\\"
picklefilename = os.path.join(temp, "kerr_lookupdata.txt")
try:
os.mkdir(temp)
except:
pass

# common variables

def extractErrorInfo(matchstr):

rawstr = r"""<tr class="\D*"><td>\s*<strong class="\D*">(.*)</strong>\s*</td>\s*<td>\s*(.*)\s*</td>\s*<td>\s*<i class="spip">(.*)</i>\s*</td>\s*</tr>"""
rawstr2 = r"""<tr class="\D*"><td>\s*<strong class="\D*">(.*)</strong>\s*</td>\s*<td>\s*(.*)\s*</td><td>\s*.*"""
rawstr3 = r"""<td>\s*(\w*)\s*</td>.*<td>\s*([-0-9]*)\s*</td>"""

# method 1: using a compile object
compile_obj = re.compile(rawstr)
match_obj = compile_obj.search(matchstr)

if(match_obj == None):
compile_obj2 = re.compile(rawstr2)
match_obj = compile_obj2.search(matchstr)

if(match_obj == None):
compile_obj3 = re.compile(rawstr3)
match_obj = compile_obj3.search(matchstr)

if(match_obj):
# Retrieve group(s) from match_obj
all_groups = match_obj.groups()

# Retrieve group(s) by index
group_1 = match_obj.group(1)
group_2 = match_obj.group(2)
try:
poo = group_3 = match_obj.group(3)
except IndexError:
return (group_1.strip(), group_2.strip(), "")
else:
return (group_1.strip(), group_2.strip(), group_3.strip())
else:
return None

def extractcodes(line):
fields = extractErrorInfo(line)
if(fields):
params = list(extractErrorInfo(line))
params[1] = params[1].replace("--","-")
params[0] = params[0].replace("\"","")
params[0] = params[0].replace("\'","")
params[0] = params[0].replace("\\","")
params[2] = params[2].replace("\"","")
params[2] = params[2].replace("\'","")
params[2] = params[2].replace("\\","")

try:
params[1] = int(params[1])
except ValueError:
return None
return params
return None


def test():
tcs = ["""<tr class="row_even"><td> <strong class="spip">KErrNotFound</strong> </td><td>-1</td><td><i class="spip">Unable to find the specified object</i></td></tr>""",
"""<tr class="row_odd"><td><strong class="spip">KErrEtelNotCallOwner</strong> </td><td>-2000</td><td> </td></tr>""",
"""<tr class="row_even"><td> KErrAvctpBadAddress</td><td> -6400 </td><td><i class="spip">AVCTP bad address </i> </td></tr>""",
"""<tr class="row_even"><td> KErrAvctpBadAddress</td><td> --6400 </td><td><i class="spip">AVCTP bad address </i> </td></tr>""",
"""<tr class="row_even"><td> KErrAvctpBadAddress</td><td> MOO </td><td><i class="spip">AVCTP bad address </i> </td></tr>"""]

for testcase in tcs:
print extractcodes(testcase)

def regenerateErrorFile():
file = urllib.urlopen("http://newlc.com/Symbian-OS-Error-Codes.html")
lines = file.readlines()

lookupcode = -5
look_up = {}

for line in lines:
fields = extractcodes(line)
if(fields):
look_up[fields[1]]= (fields[0],fields[2])

output = open(picklefilename,"wb")
pickle.dump(look_up, output)
return look_up

#test()

try:
pkl_file = open(picklefilename, 'rb')
lookup = pickle.load(pkl_file)
pkl_file.close()
except IOError:
print "Re-Generating file"
lookup = regenerateErrorFile()



args = sys.argv
if(len(args)!=2):
print "Usage kerr <errorcode>"
print "e.g kerr -1"
sys.exit()

try:
errtupe = lookup[int(args[1])]
print "%s [%s]"% errtupe
except:
print "Unknown error"

Saturday, October 20, 2007

Nokia and maemo {no capital latter}
Forum Nokia has launched support for the maemo platform to enable our current customers to innovate on maemo platform by providing them an easy way to access needed tools and SDKs and other familiar services. We will also provide maemo application developers a sales channel through Nokia Software Market.

Maemo platform is based on the Linux operating system, and is one of the core platforms for Nokia’s high-end products. Today maemo is the basis of the operating system used in a range of Wi-Fi enabled Internet Tablets. The platform provides you with similar capabilities to a desktop environment. Nokia has already launched three devices based on maemo, and there are more devices on the way.

for more information
http://maemo.org
http://www.forum.nokia.com/main/plat...emo/index.html

Sunday, October 14, 2007

How to change wait note text at runtime

Many a times it is needed to show updates on wait notes. This can be achieved with the following:
The resource file
RESOURCE DIALOG r_waitnote
{
flags = EAknWaitNoteFlags;
buttons = R_AVKON_SOFTKEYS_CANCEL;
items =
{
DLG_LINE
{
type = EAknCtNote;
id = EGeneralNote;
control = AVKON_NOTE
{
layout = EWaitLayout;
singular_label = "Receiving File : %d Bytes";
plural_label ="%d %% Recieved";
imagefile = "z:\\system\data\avkon.mbm";
imageid = EMbmAvkonQgn_note_progress;
imagemask = EMbmAvkonQgn_note_progress_mask;
animation = R_QGN_GRAF_WAIT_BAR_ANIM;
};
}
};
}

Here singular_label is what will be shown as soon as the dialog is executed. To change the label CAknWaitNotes SetTextL function is used.

• Create and Execute the dialog
iDlg = new(ELeave)CAknWaitDialog( (REINTERPRET_CAST(CEikDialog**,&iDlg)));
iDlg->SetTone( CAknNoteDialog::EConfirmationTone );
iDlg->SetCallback( this );
iDlg->SetTextL(_L("Please Wait..."));
iDlg->ExecuteLD(R_WAITNOTE);
• Change label as and when required
_LIT(KFormat,"%d %% Recieved");
str.Format(KFormat,kb);
iDlg->SetTextL(str)

• Dismiss the dialog
if(iDlg)
{
iDlg->ProcessFinishedL();
iDlg = NULL;
}

How to Show Copyright (c) Symbol.

_LIT(KTxtAbout,"Copyright \251 2007");

Wednesday, October 10, 2007

S60 3rd Ed. FP 2 , SDK Beta Includes Web Runtime Engine


Today the S60 3rd Edition, Feature Pack 2 for C++ SDK Beta went live on Forum Nokia and with that a WRT testing environment. Note, this is a beta version, but the included WRT engine is close to final and developers are encouraged to use it. See the Tools and SDK’s: Nokia Tools web page

Additionally, a number of docs went up including
- Introducing Web Run-Time
- Getting Started with Nokia web Widget development
- Web Run-Time API Reference
- Porting Apple Dashboard widgets to S60

The getting started and the Porting guides include example widgets.
See http://www.forum.nokia.com/main/resources/documentation/index.html

Note: What i was looking for is a Partial Screen Widget that i can use in my Symbian.C++ code as a Control. So a Useless Feature to me.....

Thursday, September 27, 2007

Easiest way to query Access Point (IAP)

void CAppView::AccessPointL()
{
iConnOK=EFalse;

CApSettingsHandler* settingsHandler = CApSettingsHandler::NewLC(
ETrue,
EApSettingsSelListIsPopUp ,
EApSettingsSelMenuSelectNormal,
KEApIspTypeAll,
EApBearerTypeAll,
KEApSortNameAscending);

TUint32 originallyFocused(0);
// 0 is not valid IAP id. Failed if 0 after RunSettingsL().
TUint32 selectedIap(0);

// Show the dialog
settingsHandler->RunSettingsL(originallyFocused, selectedIap);

// The CApUtils API is deprecated/removed, the following code can be
used
// to convert the WapAP Id to IAP Id
if (selectedIap)
{
CCommsDatabase* db = CCommsDatabase::NewL();
CleanupStack::PushL(db);

CCommsDbTableView* wapTable;
wapTable = db->OpenViewMatchingUintLC( TPtrC(WAP_ACCESS_POINT),
TPtrC(COMMDB_ID), selectedIap );
User::LeaveIfError( wapTable->GotoFirstRecord() );

TBuf<100> wapBearer;
wapTable->ReadTextL(TPtrC(WAP_CURRENT_BEARER), wapBearer);

if ( wapBearer == TPtrC(WAP_IP_BEARER) )
{
CCommsDbTableView* bearerTable;
bearerTable = db->OpenViewMatchingUintLC( TPtrC(wapBearer),
TPtrC(WAP_ACCESS_POINT_ID),
selectedIap );
User::LeaveIfError( bearerTable->GotoFirstRecord() );
bearerTable->ReadUintL(TPtrC(WAP_IAP), iIap );
CleanupStack::PopAndDestroy( bearerTable ); // bearerTable
}
else
{
User::Leave( KErrInvalidBearerType );
}
CleanupStack::PopAndDestroy(2); // db, wapTable,
}
else
{
iIap = 0;
}

CleanupStack::PopAndDestroy(settingsHandler);

if(!iIap)
{
iConnOK=EFalse;
}
else
{
iConnOK=ETrue;
}
}


Header Files : ApSettingsHandlerUI.h
Link against : apsettingshandlerui.lib
Installing sis file programmatically


RFile rFile;
RApaLsSession lsSession;
User::LeaveIfError(lsSession.Connect());
CleanupClosePushL(lsSession);
TThreadId threadId;

_LIT(KMyCertFile, "c:\\data\\app.sis");

if(BaflUtils::FileExists(CEikonEnv::Static()->FsSession(), KMyCertFile))
{
User::LeaveIfError(rFile.Open(CEikonEnv::Static()->FsSession(), KMyCertFile, EFileRead));
}

lsSession.StartDocument(rFile, threadId, NULL);
lsSession.ClearFsSession();
lsSession.Close();

Monday, September 24, 2007

How to prevent build-in camera application to be autolaunched

If your phone has a camera, nomrally if you open the camera cover{at least in my N70}, there will be a build-in app to be launched to captrue phones. But when you write your own camera apps, you might not want the build-in app to be launched, how to do this?

The theory is quite simple, camera cover open/close event is actually a KeyEvent, if you can capture this KeyEvent which window server dispatchs inside your application, you can prevent the default app being launched. Here's how:
void CHelloWorldAppUi::HandleForegroundEventL( TBool aForeground )
{
if( aForeground ) // switch to the foreground
{
iForeground = ETrue;
iOpenCameraKey = iEikonEnv->RootWin().CaptureKey( EKeyDevice1D, 0, 0 );
}
else
{
iForeground = EFalse;
iEikonEnv->RootWin().CancelCaptureKey( iOpenCameraKey );
}
}



It doesn't make sense if you capture this KeyEvent all the time, so I capture the key when my app is in foreground, release the key when my app is in background. So the default could be autostarted when this app is in backgrond.
How to convert HBuf to TBuf

_LIT(KSomeText, "Symbian");

HBufC* heapBuffer=HBufC::NewLC(15);
*heapBuffer = KSomeText;
TBuf<15> buffer(*heapBuffer);
CleanupStack::PopAndDestroy( heapBuffer );

Sunday, September 23, 2007

Hiding Your Application from task list

If you want to hide the application from the system task list add this method to the document class:
void CApplicationDocument::UpdateTaskNameL(CApaWindowGroupName* aWgName)
{
CAknDocument::UpdateTaskNameL(aWgName);
aWgName->SetHidden(ETrue);
}
or put in this code:
CEikonEnv::Static()->RootWin().SetOrdinalPosition(0, ECoeWinPriorityNeverAtFront);
Restart Phone With Low CAPABILITY

RWsSession iWs;
User::LeaveIfError(iWs.Connect());
TWsEvent e;
e.SetType(EEventPointer);
iWs.SendEventToOneWindowGroupsPerClient(e);
iWs.SendEventToAllWindowGroups( e);
Lock phone from code

RAknKeyLock keyLock;
User::LeaveIfError(keyLock.Connect());
CleanupClosePushL(keyLock);
keyLock.EnableKeyLock();
keyLock.Close();
CleanupStack::PopAndDestroy();

How can I determine the application language at run time?

The current language the application is using to display its UI can be retrieved with
TLanguage lang = CEikAppUi::ApplicationLanguageL();
For a non-localized application, this value is TLanguage::ELangNone (0xFFFF).
Note that this value may be different from the language returned by
User::Language();
which represents the language of the current locale (system-wide setting).

Thursday, September 06, 2007

Trolltech's "Green Phone" stack architecture

Trolltech, best known for development tools and Linux application stacks for phones and other mobile devices, will ship an "open" Linux-based phone in September,2006. The "Greenphone" features a user-modifiable Linux OS, and is meant to jumpstart a third-party native application ecosystem for Linux-based mobile phones.




Wednesday, September 05, 2007

Get cell broadcast

Header file
#ifndef __CBUTIL_H__
#define __CBUTIL_H__

#include <e32base.h>
#include <Etel3rdParty.h>

#include <etelmm.h>
#include <etel.h>
#include <etelmmcs.h>
#include <flogger.h>
#include <csmshandler.h>

class CCBUtil : public CActive
{
public:
CCBUtil();

static CCBUtil* NewL();

void ConstructL();

~CCBUtil();

private:
void RunL();

void DoCancel();

private:
RFileLogger iLog;

TRequestStatus iReqStatus;

RTelServer iServer;

RMobilePhone iPhone;

RMobileBroadcastMessaging iBroadcastMsg;

TBuf8<88> iGsmMsgdata;

CSmsHandler* iSmsHandler;

};

#endif // __CBUTIL_H__

Source File
#include "cbutil.h"
#include <eikenv.h>
#include <Etelmm.h>
#include <Etel3rdparty.h>
#include <stdio.h>

_LIT(KGsmModuleName,"phonetsy.tsy");

CCBUtil::~CCBUtil()
{
Cancel();
iPhone.Close();
iServer.UnloadPhoneModule(KGsmModuleName);
iServer.Close();
iLog.CloseLog();
iLog.Close();
}

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


void CCBUtil::ConstructL()
{
RTelServer::TPhoneInfo iPhoneInfo;
iServer.Connect();
iServer.LoadPhoneModule(KGsmModuleName);
TInt enumphone;
User::LeaveIfError(iServer.EnumeratePhones(enumphone));
if (enumphone < 1)
{
User::Leave(KErrNotFound);
}
User::LeaveIfError(iServer.GetPhoneInfo(0, iPhoneInfo));
User::LeaveIfError(iPhone.Open(iServer,iPhoneInfo.iName));
iBroadcastMsg.Open(iPhone);
RMobileBroadcastMessaging::TMobileBroadcastAttributesV1 iAttrInfo;
TPckg<RMobileBroadcastMessaging::TMobileBroadcastAttributesV1> iDes(iAttrInfo);
iBroadcastMsg.ReceiveMessage(iStatus,iGsmMsgdata,iDes);
SetActive();
}

CCBUtil::CCBUtil()
: CActive(EPriorityNormal)
{
CActiveScheduler::Add(this);
}

void CCBUtil::RunL()
{
if(iStatus==KErrNone)
{
RFs fs;
fs.Connect();
RFile file;
TBuf<32> aFileName = _L("C:\\log.txt");
fs.Delete(aFileName);
file.Replace(fs,aFileName,EFileWrite);
file.Write(iGsmMsgdata);
file.Close();
fs.Close();

FILE* fp;
fp = fopen("c:\\log.txt","rb");

char locationString[94];
char cbuf;
int char_cnt = 0;
unsigned int bb = 0;

unsigned char ur, curr, prev = 0;
int cnt = 0;
for ( cnt = 0; cnt < 6; cnt++)
fread(&cbuf, 1, 1, fp);

while(fread(&cbuf,1,1,fp))
{
unsigned char aa = (1<< (7 -bb%7))-1;
ur = cbuf & aa;
ur = (ur << (bb)) | prev;
curr = cbuf &(0xff ^ aa);
curr = curr >>(7-bb);
prev= curr;
if(ur == 0xd)
{
break;
}

locationString[char_cnt] = ur;
bb = ++bb % 7;
char_cnt++;
if ( bb== 0 )
{
locationString[char_cnt++] = prev;
prev =0;
}
}

locationString[char_cnt] = '\0';
fclose(fp);
int len = 0;
while (locationString[len] != NULL )
len++;

HBufC* nameHeap = HBufC::NewLC(len);
TPtr namePtr(nameHeap->Des());
TBuf<250> messageText;

for (int i = 0; i < len; i++)
namePtr.Append((TChar)locationString[i]);

messageText.Copy(namePtr);

CAknInformationNote* informationNote = new ( ELeave )
CAknInformationNote;
informationNote->ExecuteLD(messageText);

CleanupStack::PopAndDestroy(nameHeap);
}
else
{
CAknInformationNote* informationNote = new ( ELeave )
CAknInformationNote;
informationNote->ExecuteLD(_L("Error :p"));
}
iBroadcastMsg.Close();
}

void CCBUtil::DoCancel()
{
}

Yes, i admit that the above code does not work every time. If you have some fix to above code please send the fix to me at my email id skumar.mobiledev@gmail.com

Saturday, September 01, 2007

How to restart device pragmatically


enum TSWStartupReason
{
// Normal startup reasons (100..149)

// Nothing set the (default value).
ESWNone = 100,

// Restore Factory Settings (Normal)
ESWRestoreFactorySet = 101,

// Language Switched
ESWLangSwitch = 102,

// Warranty transfer
ESWWarrantyTransfer = 103,

// Possibly needed for handling power off & charger connected use case.
ESWChargerConnected = 104,

// Restore Factory Settings (Deep)
ESWRestoreFactorySetDeep = 105
};

class SysStartup
{
public:
IMPORT_C static TInt ShutdownAndRestart(const class TUid& aSource, TSWStartupReason aReason);
};

Implementation

TUid uid = {0x};
SysStartup::ShutdownAndRestart( uid, ESWNone);


Friday, August 31, 2007

Motorola MotoMAGX

Motorola’s MotoMAGX Linux platform is based on three things: an open source Linux operating system, kick ass J2ME support and something they call “WebUI.” [HTTP + CSS + AJAX + WebKit].

Thursday, August 30, 2007

Types of Phones

1. Any mobile phone
-Voice calls
-SMSs
-Contacts

2. Feature phone
-Voice calls
-SMSs
-Contacts
-MMSs
-Email
-WAP
-Camera
-Colour Display

3. Smartphone
-Voice calls
-SMSs
-Contacts
-MMSs
-Email
-WAP
-Camera
-Colour Display
-Access to OS
-Application background execution
Compatibility aspects to the S60 platform:

1. Source compatibility: means that the application or a client code can be rebuilt without a need to modify the code.

2. Binary compatibility: means that no rebuild is needed and the application or a client code thus runs on the S60 phone. Potential issues come along when there is a new compiler and tool chain; The S60 3rd Edition introduces new compilation tools (RVCT, GCC EABI), which cause a full binary break.
Symbian Run Modes

Symbian runs in 2 Modes.

1. User mode – kernel services can only be accessed through the EUSER.DLL. The lack of a proper kernel port does not stop the development of user-side components because the platform provides a complete Kernel Port for the PC environment under the Windows Operating System. This is called the emulator.

2 Kernel mode – EUSER.DLL is an interface between common code and hardware-specific code. In the other words, kernel mode means that the software is run on the target hardware.
S60 ecosystem.
1. Licensees.
2. Product Creation Community (PCC)
• Boutiques – experts in designing complete S60 phones and managing entire S60 phone projects
• Competence Centers – top-tier software companies with deep S60 end-to-end understanding and extensive S60 project support
• Wireless Technology Providers – experts on the hardware platforms or hardware components upon which S60 phones are built
• Contractors – skilled software companies offering focused expertise in specific technology areas
3. 3rd party developers.
S60 architecture

S60 architecture consists of ...
1. Cellular modem controlled by modem software.
2. Domestic Operating System (DOS).
3. Application processor engine controlled by Symbian OS.
4. S60 software.

Nokia’s Mobile Software (MSW) is the organization behind the S60 platform.

Monday, August 13, 2007

Coding for Mobile on Mobile

If you are thinking to do this Hmmmm. you need some rest. ;-)
OR
Do what i do use http://www.j2medit.com/

Saturday, August 11, 2007

How to use TLex to Parse tokens from String.

  _LIT8(KSomeConstString,"first,second,third,fourth");

TLex8 lex(KSomeConstString);
TChar ch;
TBuf8<50> token;

while((ch = lex.Get()) != 0 )
{
while ((ch = lex.Peek()) != ',')
lex.Inc();

token.Copy(lex.MarkedToken());
/*
Now we have the string in token,
do something..
*/
lex.Inc();
lex.Mark();
}

Friday, August 10, 2007

"C++/C Development with Eclipse" Then and Now

In the Past i have tried to use Eclipse for my day to day development, But at that time it too me around 6 hours before i could install all the req. tools and started my developmentBut that is also not a smooth road.

But Now {2 day} i found a good Eclipse CDT bundle for Windows with that i start and running in 30 mins. I suggest you take a look in to it.

http://wascana.sourceforge.net/
LiMo [Linux Mobile] Platform architecture
How to hide Status Pane

CEikonEnv* iEnv = CEikonEnv::Static();
CEikStatusPane* statusPane=Env->AppUiFactory()->StatusPane();
statusPane->MakeVisible(EFalse);
Include files:
#include <eikspane.h>
#include <eikenv.h>

Link against: eikcore.lib

Tuesday, August 07, 2007

Sending Application in Background using RSS

Add the "Launch" field in application info resource in your Project .RSS file
RESOURCE APP_REGISTRATION_INFO
{
app_file="projectname";
localisable_resource_file="\\resource\\apps\\projectname_loc";
hidden = KAppIsHidden;
embeddability = KAppNotEmbeddable;
newfile = KAppDoesNotSupportNewFile;
// Launches the application in background.
launch =KAppLaunchInBackground;

}
Why we require to launch a application in Background ?
One use case may be the running wallpaper where a server with GUI runs in BackGround.

Sunday, August 05, 2007

Java Verified Signing Flow.
How to get the Resource File from Installation
_LIT(KIconFile,"!:\\Data\\MyApp\\MyApp.mbm");
TFileName myCompleteFileName(KIconFile());
CompleteWithAppPath(myCompleteFileName);
Symbian Symbianed Flow For Symbian V9

Capability Mobile Diagarm For Symbian v9
The "capabilities" model was introduced in Symbian OS v9.x (S60 3rd Edition onwards). There are 20 capabilities, which are divided into four groups:


Symbian V9 Security Description.

A capability is an access token that corresponds to an access permission of sensitive system resources.

Basic capabilities

LocalServices
Grants access to "short-link" connections such as Bluetooth and infrared. These connections are not billable transactions. An example of this kind of action is device-to-device file transfer.

Location
Grants access to the location of the device, such as network cell ID.

NetworkServices
Grants access to remote service and might involve cost for the user. Typical use cases are dialing a normal GSM voice call or sending a text message.

ReadUserData
Grants read-only access to confidential user data. Typical use cases are reading contacts, messages, and calendar events.

WriteUserData
Grants write access to user data. Typical use cases are adding or deleting contacts, messages, or calendar events.

UserEnvironment
Grants access to live confidential information about the user and his/her immediate environment. An example of a typical protected resource in a mobile device is a camera.

Extended capabilities

PowerMgmt
Grants access to kill any process running in the system or completely turn off the device.

ProtServ
Grants the right to a server to register with the protected name. Protected names start with a “!”. The kernel will prevent servers without ProtServ capability from using such a name and therefore will prevent protected servers from being impersonated.

ReadDeviceData
Grants read-only access to sensitive system data such as device settings.

WriteDeviceData
Grants write access to sensitive system data such as device lock settings, system time, and time zone.

SurroundingsDD
Grants access to logical device drivers that provide input information about the surroundings of the mobile phone, for example global positioning system (GPS) device drivers.

SwEvent
Grants access to simulate key presses and capture such events from any application. Typical example is a screen-shot application.

TrustedUI
Grants access to create a trusted UI session and display dialogs in a secure UI environment. Typical example is password dialog.

Platform-approved capabilities

AllFiles
Grants read-only access to all data caged directories and write access to /private –directory. NOTE! AllFiles will not be granted for a filemanager type of application.

CommDD
Grants access to communication device drivers such as WiFi, USB, and serial device drivers.

DiskAdmin
Grants access to disk administration functions such as formatting a drive or mounting/unmounting drive partitions.

MultimediaDD
Grants access to critical multimedia device drivers such as camera and sound.

NetworkControl
Grants access to modify or access network protocol controls such as dropping all connections from the mobile phone.

Manufacturer-approved capabilities

DRM (digital rights management)
Grants access to DRM-protected content in plain form.

TCB
Grants write access to /sys and /resource directories in the mobile phone.
Using FlashLite with Symbian C++

Code for S60 V3:


void CSWF2SISAppUi::LaunchSwfL( const TDesC &aFlashAppName )
{
iHandler = CDocumentHandler::NewL( NULL );
iHandler->SetExitObserver(this);

TUid KUidFlash21 = { 0x200077D6 };
TDataType dtype(KUidFlash21);

TInt error = iHandler->OpenFileEmbeddedL( aFlashAppName, dtype );
}

void CSWF2SISAppUi::HandleServerAppExit (TInt /* aReason */)
{
Exit();
}

Code for S60 FP1:


void CSWF2SISAppUi::LaunchSwfL( const TDesC &aFlashAppName )
{
iHandler = CDocumentHandler::NewL( NULL );
iHandler->SetExitObserver(this);

TUid KUidFlash21 = { 0x200077D6 };
TDataType dtype(KUidFlash21);

TInt error = iHandler->OpenFileEmbeddedL( aFlashAppName, dtype );
}

void CSWF2SISAppUi::NotifyExit (TExitMode aMode)
{
Exit();
}

Get Phone Screen Size
Header:  w32std.h
Library: ws32.lib

TPixelsAndRotation ScreenSize;
iCoeEnv->ScreenDevice()->GetDefaultScreenSizeAndRotation(ScreenSize);
TInt width = ScreenSize.iPixelSize.iWidth;
TInt height = ScreenSize.iPixelSize.iHeight;

iLogger.WriteFormat(_L("Width : %d, Heigth : %d"), width, height);
Find out all the Message server entries.


CMsvEntry *inbox=iSession->GetEntryL(KMsvGlobalInBoxIndexEntryId);
CMsvEntrySelection *children=inbox->ChildrenWithMtmL(KUidMsgTypeSMS); // KUidMsgTypeMultimedia
for(TInt i=0;i<children->Count();i++)
{
CMsvEntry *child=inbox->ChildEntryL((*children)[i]);
const TMsvEntry &entry=child->Entry();
...
}
A color picker in Symbian S60 v3

TBool noneExist = EFalse;
TBool noneChosen = EFalse;
TRgb colour = KRgbDarkGray;

CArrayFixFlat<TRgb>* colours = new(ELeave) CArrayFixFlat<TRgb>(6);
colours->AppendL(KRgbBlack);
colours->AppendL(KRgbDarkGray);
colours->AppendL(KRgbRed);
colours->AppendL(KRgbSymbianOrange);
colours->AppendL(KRgbBlue);
colours->AppendL(KRgbWhite);
colours->AppendL(KRgbCyan);
colours->AppendL(KRgbYellow);
colours->AppendL(KRgbGreen);

CAknColourSelectionGrid *d = CAknColourSelectionGrid::NewL( colours, noneExist, noneChosen, colour);
if(d->ExecuteLD())
{
///Here you get the selected color..this you can use in your draw method.
//selectedColor = colour;

DrawNow();
}

Saturday, August 04, 2007

How to Hide Application from User Menu
In your ApplicationName_reg.rss file you will find a structure RESOURCE APP_REGISTRATION_INFO, you need to add the following line, to the resource.
BYTE hidden = KAppIsHidden;
This application will be a hidden application, and it will not be shown in Applications list.
Mobile DRM

Several articles I read recently on Mobile DRM:

Roberto Nunes’s Forum Nokia Blog:
DRM and some more TLA (tree letters abbreviations)
DRMs - Part 2
DRMs - Part 3 OMA DRM
DRMs - Part 4 - Conclusions

medialoper.com:
Microsoft Zune’s Big Innovation: Viral DRM
ipodnn.com:
MS defends Zune temporary DRM

Friday, August 03, 2007

How to detect if an application is launched by user or the startup list

It is sometimes useful to be able to detect whether an application is started at boot time by the Startup List API (present only in S60 3rd Edition) or by the user, and passing Symbian Signed - which is generally required to have an application which requires auto boot feature - makes this almost mandatory. So How we can archive it let us try

First, we will modify the application registration file and add some opaque_data field in the APP_REGISTRATION_INFO resource. The content and value of these data does not really matter, you just need to specify something: :

#include <appinfo.rh>
#include <uikon.rh>

RESOURCE APP_REGISTRATION_INFO
{
...
opaque_data = r_startup_detect;
}


RESOURCE NUMBER_INT8 r_startup_detect
{
value = 1;
}

The opaque_data and other launch parameters will be ignored by the startup list when launching the application. Thus, detecting whether they are present or not allows to differentiate whether the application has been launched at boot time or by the user.

To do this, we will override the ProcessCommandParametersL() function in your AppUI:



TBool CMyAppUi::ProcessCommandParametersL( CApaCommandLine &aCommandLine )
{
if(aCommandLine.OpaqueData().Length() > 0)
{
// Opaque data exists,
// app. has been manually started from the menu
}
else
{
// Opaque data not present,
// App. has been auto-started from start up
// or after Installation !!!
}
return CEikAppUi::ProcessCommandParametersL( aCommandLine );
}

Thursday, August 02, 2007

How to launch an application with its UID

LaunchAppWithUIDL(const TUid aAppUid)
{
RApaLsSession apaLsSession;
User::LeaveIfError(apaLsSession.Connect());
CleanupClosePushL(apaLsSession);

TApaAppInfo appInfo;
TInt retVal = apaLsSession.GetAppInfo(appInfo, aAppUid);

if(retVal == KErrNone)
{
CApaCommandLine* cmdLine = CApaCommandLine::NewLC();
//cmdLine->SetLibraryNameL(appInfo.iFullName); // Pre Symbian V9
cmdLine->SetExecutableNameL(appInfo.iFullName);
cmdLine->SetCommandL(EApaCommandRun);
User::LeaveIfError( apaLsSession.StartApp(*cmdLine) );

CleanupStack::PopAndDestroy(cmdLine);
}
else
{
// Application with UID can't be found!
}

CleanupStack::PopAndDestroy(&apaLsSession);
}

Tuesday, July 31, 2007

How to Install an empty file or directory (which is not included in the SIS file).

Pre-Symbian OS v9.0:
""-"C:\Documents\deleteme", FN
""-"C:\Documents\deleteme1\", FN
""-"C:\Documents\deleteme2\*.*", FN
""-"C:\Documents\created.txt", FN
Symbian OS v9.0 and beyond:

""-"C:\private\<process SID>\deleteme", FN
""-"C:\private\<process SID>\deleteme1\", FN
""-"C:\private\<process SID>\deleteme2\*.*", FN
""-"C:\private\<process SID>\created.txt", FN

Monday, July 30, 2007

How to Sending SMS in Symbian 9

User::LeaveIfError(sendAs.Connect());
CleanupClosePushL(sendAs);

RSendAsMessage sendAsMessage;
sendAsMessage.CreateL(sendAs, KUidMsgTypeSMS);
CleanupClosePushL(sendAsMessage);

// prepare the message
sendAsMessage.AddRecipientL(aRecipient, RSendAsMessage::ESendAsRecipientTo);
sendAsMessage.SetBodyTextL(aMessageBody);

// send the message
sendAsMessage.SendMessageAndCloseL();

// sendAsMessage (already closed)
CleanupStack::Pop();

// sendAs
CleanupStack::PopAndDestroy();

Sunday, July 29, 2007

How to get the free space of every drive

Following Code can get you the free space in a drive.

RFs iFs;
iFs.Connect();
TInt err = iFs.Volume( volinfo, EDriveC );
TInt64 space = volinfo.iFree;
iFs.Close();
"iFree" is the amount of free space on the disk in bytes.

Note: Volume() will return KErrNotReady if the drive contains no media.

Saturday, July 28, 2007

Increase the heap size of an application

The default heap size of an application is 1MB, that means on target if you application tried to allocate more than 1MB memory, the allocation will fail. Probably new (ELeave) will leave.

What if you really want your application to allcoate more than 1MB memory? For example, you are developing an image processing application which needs to load big pictures.

There's a way to use a user define heap instead of the default heap, you can do this like:

GLDEF_C TInt E32Main()
{
RHeap *heap = UserHeap::ChunkHeap( NULL, 1024 * 4, 1024 * 1024 * 2 ); // 2MB
if( heap )
{
User::SwitchHeap( heap );
}
TInt ret = EikStart::RunApplication( NewApplication );
if ( heap )
{
heap->Close();
}
return ret;
}

You switch the heap to your own one, which allow you to allocate 2MB in this case

Friday, July 27, 2007

Prevent object being created on stack

In Symbian, sometimes we don't want the calling function to create a object of your class on stack, because the stack resource is rare. Is there any way we can restrict do this?

Answer is Yes.

We should make class destructor private, rather than public or protected.

Example

class CTest : public CBase
{
private:
~CTest ();
}

Thursday, July 26, 2007

When to use () and [] in PKG files?

The () are used for software dependencies, while [] are used for product dependencies. () will work in most cases, but it will throw an error if you state your file supports both UIQ 3 and S60 (which is valid for shared DLLs).

Note that, as the time of this writing, some of the documentation uses
(0x101F6300), 3, 0, 0, {"UIQ30ProductID"}
(0x101F6300), 3, 0, 0, {"Series60ProductID"}
when it should have instead
[0x101F6300], 3, 0, 0, {"UIQ30ProductID"}
[0x101F6300], 3, 0, 0, {"Series60ProductID"}

Wednesday, July 25, 2007

[Revisiting] Bluetooth Power Status Check
In my last post i showed how to detect that Blue tooth is ON / OFF in S60 v3 but in Pre-S60v3 SDKs it is bit tricky. Here is one way of achiving same thing using libs from OLD S60 v1.2 SDK. [I found this method in Forum Nokia Posted by a respected member.]
Note : Use it on your Own Rsk.


#ifndef BT_ENG_HACK_H
#define BT_ENG_HACK_H
// link against BTENG.LIB copied from SDK 1.2

// these are headers that are just not included
// in the SDK, so I had to reverse engineer them
//C:\Symbian\tilion\group>"c:\Program Files\Borland\CBuilder6\Bin\expdump.exe"
// C:\Symbian\Series60_1_2_B\epoc32\release\winsb\udeb\BTENG.LIB
class MBTMCMSettingsCB
{
};
class CBTMCMSettings;
class CBTMCMSettings
{
public:

static CBTMCMSettings* NewLC(MBTMCMSettingsCB *x);
static CBTMCMSettings* NewL(MBTMCMSettingsCB *x);

void SetPowerStateL(TBool a, TBool b);
void GetPowerStateL(TBool &a);
TInt GetConnectionStatus(int &a);
};
#endif




Powered by Qumana

Tuesday, July 24, 2007

New Blogging Tool [Qumma]

Hello Guys i got a new Tool to Blog. It is Qumana. Looks good till now let me see if it can meet my requiments.


Powered by Qumana


Bluetooth Power Status Check

Here is the Code that shows How to check that BlueTooth is ON or OFF in Symbian V9





CRepository *cRepository = CRepository::NewL(KCRUidBluetoothPowerState);
TInt bluetoothStatus=0;
User::LeaveIfError( cRepository ->Get(KBTPowerState, bluetoothStatus) );



Monday, July 23, 2007

How to Launch the browser in an embedded mode.
LaunchBrowserEmbedded()
{
CApaProcess *pApaProcess = Document()->Process();

TUid id;
id.iUid = 0x10008d39;
iDoc = pApaProcess->AddNewDocumentL(KNullDesC , id);

iDoc->EditL(this, ETrue);

TApaTaskList taskList( iEikonEnv->WsSession() );
id.iUid = 0x10208b93;//this
TApaTask task = taskList.FindApp( id );
if ( task.Exists() )
{
task.SendMessage(TUid::Uid(0), _L8("4 http://news.google.com/xhtml"));
}
}
Note:
you have to provide NotifyExit() in your AppUi to delete iDoc.

Sunday, July 22, 2007

Compress / Decompress A File with less memory usage.

void CompressAFile(TDesC& aSrcName, TDesC& aDstName)
{
RFs fs;
User::LeaveIfError(fs.Connect());
fs.SetSessionPath(_L("C:\\")); // change to your req. Path

RFile file;
TInt err = file.Open(fs,aDstName,EFileRead);

CEZFileToGZip* zip = CEZFileToGZip::NewLC(fs, aSrcName, file);
TInt tempi = 0;
while(zip->DeflateL()) // while loop req. donot remove
{
tempi++;
}
CleanupStack::PopAndDestroy(); // zip

file.Close();
fs.Close();
}


void DeCompressAFile(TDesC& aSrcName, TDesC& aDstName)
{
RFs fs;
User::LeaveIfError(fs.Connect());
fs.SetSessionPath(_L("C:\\")); // change to your req. Path

RFile file;
TInt err = file.Open(fs,aDstName,EFileRead);

CEZGZipToFile *zip = CEZGZipToFile::NewLC(fs, aSrcName, file);
TInt tempi = 0;
while(zip->InflateL()) // while loop req. donot remove
{
tempi++;
}
CleanupStack::PopAndDestroy(); // zip

file.Close();
fs.Close();
}

Saturday, July 21, 2007

Retrieving Phone's Manufacturer ,Model & IMEI number Using CTelephony

---- Header --------
CTelephony* iTel;
CTelephony:: TPhoneIdV1Pckg iInfoPkg;
CTelephony:: TPhoneIdV1 iInfo;


---- CPP File ------

void Request()
{
iTel=CTelephony::NewL();
iTel->GetPhoneId(iStatus,iInfoPkg);
SetActive();
}

void RunL()
{
switch(iStatus.Int())
{
case KErrNone:
{
TBuf
CTelephony::KPhoneModelIdSize + CTelephony::KPhoneSerialNumberSize> phoneInfo;
phoneInfo.Copy(iInfo.iManufacturer);
phoneInfo.Append(iInfo.iModel);
phoneInfo.Append(iInfo..iSerialNumber);
}
break;
default:
{
//Return error
}
break;
}
}

Friday, July 20, 2007

How to get Names of all installed applications

The following code sample shows how to get an array containing names of the installed applications.

CDesCArray* GetInstallAppListL(void)
{
CDesCArrayFlat* appArray = new(ELeave)CDesCArrayFlat(10);
CleanupStack::PushL(appArray);

RApaLsSession apaSession;
TRAPD(err, apaSession.Connect());

if(err != KErrNone)
{
CleanupStack::Pop(appArray);
return NULL;
}

CleanupClosePushL(apaSession);

TRAPD(errn, apaSession.GetAllApps());

if(err != KErrNone)
{
CleanupStack::Pop(appArray);
CleanupStack::PopAndDestroy(apaSession);
return NULL;
}

TInt errno(KErrNone);
TApaAppInfo appInfo;

do
{
errno = apaSession.GetNextApp(appInfo);
if(KErrNone == errno && appInfo.iCaption.Length())
{
appArray->AppendL(appInfo.iCaption);
}

}while(KErrNone == errno);

CleanupStack::PopAndDestroy(apaSession);

CleanupStack::Pop(appArray);
return appArray;
}

Sunday, June 17, 2007

How to check what serial ports are available in WM5/6?

I use the following code to check for available ports in Windows Mobile 5 and 6

[CODE]
private string[] GetAvailableCommPorts()
{
ArrayList commPorts = new ArrayList();
string port = "COM";
for (int i=1;i<=99;i++) { try { string portName = port+i.ToString()+":"; new OpenNETCF.IO.Serial.Port(portName).Query(); commPorts.Add(port+i.ToString()); } catch { } } return (string[]) commPorts.ToArray(typeof(string)); }

[/CODE]

Sunday, March 18, 2007

Get Caller Number

Below is the code illustarating how to get the remote party's telephone number. It is different for S60 3rd Edition and previous versions.

In V8 and Below
#include

void GetRemotePartyPhoneNumberL(TDes& aPhoneNumber)
{
RTelServer etel;

// Connect to ETel server
User::LeaveIfError(etel.Connect());
CleanupClosePushL(etel);

// Load phone module. This is just to be on the safe side
// because it should have been loaded already
_LIT(KTsyName, "phonetsy.tsy");
User::LeaveIfError(etel.LoadPhoneModule(KTsyName));

RTelServer::TPhoneInfo phoneInfo;

// Get phone info. We need phone's name to open a phone
const TInt KPhoneIndex = 0;
User::LeaveIfError(etel.GetPhoneInfo(KPhoneIndex, phoneInfo));

RPhone phone;

// Open the phone
User::LeaveIfError(phone.Open(etel, phoneInfo.iName));
CleanupClosePushL(phone);

RPhone::TLineInfo lineInfo;

// Get line info. We need line's name to open it
const TInt KLineIndex = 0;
User::LeaveIfError(phone.GetLineInfo(KLineIndex, lineInfo));

RLine line;

// Open the line
User::LeaveIfError(line.Open(phone, lineInfo.iName));
CleanupClosePushL(line);

RLine::TCallInfo callInfo;

// Get call info. We need call's name to open it and get the info we need
const TInt KCallIndex = 0;
User::LeaveIfError(line.GetCallInfo(KCallIndex, callInfo));

RMobileCall call;

// Open the call
User::LeaveIfError(call.OpenExistingCall(line, callInfo.iCallName));
CleanupClosePushL(call);

RMobileCall::TMobileCallInfoV1 mobCallInfo;
RMobileCall::TMobileCallInfoV1Pckg mobCallInfoPckg(mobCallInfo);

// Get the call's info
User::LeaveIfError(call.GetMobileCallInfo(mobCallInfoPckg));

// We successfully got the call's info.
// Now copy the remote party's phone number to the target descriptor
aPhoneNumber.Copy(mobCallInfoPckg().iRemoteParty.iRemoteNumber.iTelNumber);

// Close all handles
CleanupStack::PopAndDestroy(4); // call, line, phone, etel
}

In V9 and above
void GetRemotePartyPhoneNumberL(TDes& aPhoneNumber)
{
// Create a CTelephony object
CTelephony* telephony = CTelephony::NewLC();

CTelephony::TCallInfoV1 callInfoV1;
CTelephony::TCallInfoV1Pckg callInfoV1Pckg(callInfoV1);

CTelephony::TCallSelectionV1 callSelectionV1;
CTelephony::TCallSelectionV1Pckg callSelectionV1Pckg(callSelectionV1);

CTelephony::TRemotePartyInfoV1 remotePartyInfoV1;
CTelephony::TRemotePartyInfoV1Pckg remotePartyInfoV1Pckg(remotePartyInfoV1);

callSelectionV1.iLine = CTelephony::EVoiceLine;
callSelectionV1.iSelect = CTelephony::EInProgressCall;

// Get the call info
User::LeaveIfError(telephony->GetCallInfo(callSelectionV1Pckg,
callInfoV1Pckg, remotePartyInfoV1Pckg));
// Copy the remote party's phone number to the target descriptor
aPhoneNumber.Copy(remotePartyInfoV1Pckg().iRemoteNumber.iTelNumber);

CleanupStack::PopAndDestroy(); // telephony
}

Thursday, March 15, 2007

How to guide for pre-installed applications

Introduction
---------------

In preinstalled applications, application files such as binaries are already in place in their target folders on a memory card. When a memory card with preinstalled applications is inserted into a device, the preinstalled applications are automatically installed so that the user can use them without having to install them manually.


In addition to the application files, a .sis file created with a PA type must also exist in the \private\10202dce folder on the memory card. This .sis file is also known as a "stub" .sis file since it contains sis controller data but no files.

How to create PA package
-----------------------------


Creating PA sis package
---------------------------


* Make sure that the package type is PA in the .pkg file.
* In the .pkg file, change the target drive for each file to the MMC drive.
* Make sure that correct product dependency is specified in the package file.
* Get certification for the final .sis file, ie. submit the application to Symbian Signed. When submitting, include the PA type sis, .pkg file and corresponding binaries to a .zip file. Arrange the binaries in the .zip file according to the correct structure so that binaries are located in the correct directories under
o private
o resource
o sys

You need to be aware of the folowing for PA packages:
* Do not use FR (FILERUN) options since they are not invoked in PA packages.
* The FN option can be used if the stub file is not read-only.

Do not use the FT (FILETEXT) option. It is skipped/ignored for PA packages.
* The PA .sis file cannot have embedded .sis file(s).
Sample .pkg file content for PA application:
[CODE]
;Languages
&EN

;Header
#{"Test Application"},(0x11223344),1,0,0, TYPE=PA

;Localized Vendor name
%{"Test"}

;Unique Vendor name
:"Test"

;Dependency for S60 3rd Edition
[0x101F7961], 0, 0, 0, {"Series60ProductID"}

;Preinstalled files
"MyTestApp.exe" - "e:\sys\bin\MyTestApp.exe"
"MyTestApp_reg.rsc" - "e:\private\10003a3f\import\apps\MyTestApp_reg.rsc"
"input.dat" - "e:\private\11223344\input.dat"
[/CODE]

In the development phase, you can use developer certificate to sign the PA type sis. Create the .sis file and sign it with a trusted certificate and key:

makesis.exe mytestpa.pkg mytestpa.sis

signsis.exe mytestpa.sis mytestpa_signed.sis

Publishing files to target locations on memory card

Make sure that files referred in PA package exist on memory card.

Publish PA sis file to the \private\10202dce\ folder on the memory card. Publish package files to their location as specified in .pkg file.


IMPORTANT: You need to make sure that the .pkg file used to create the PA .sis file doesn’t list files that are updated/modified during run time. These files still need to be on the memory card but they will no longer be protected against tampering. If any of the installed files (e.g., the configuration file) is updated/modified, propagation won't work when the memory card is inserted to another device or when the C drive is formatted. One possible solution to this problem is that if a file (e.g., a configuration file) is updated, application(s) will not touch the original file (only reading). Instead they will make a copy of this file and update the copy.

Upgrading pre-installed applications
-----------------------------------------

Preinstalled applications can be upgraded by overwriting the PA files with an SA package. When an SA package is installed to a memory card, it is propagated. This means that it will behave like a PA package when the memory card is inserted into another device.

Preinstalled applications cannot be upgraded by using Partial Upgrade (PU) packages. SIS Patch (SP) packages can be used to upgrade preinstalled applications but the upgrade is not propagated to the memory card. Thus, it will not be in place when the memory card is inserted into another device.

Wednesday, March 14, 2007

Moving an application to foreground / to background

1. Being notified of the focus change
Override HandleForegroundEventL() function In AppUi Class Like

void CMyAppUi::HandleForegroundEventL(TBool aForeground)
{
// Call Base class method
CAknAppUi::HandleForegroundEventL(aForeground);

if(aForeground)
{
// We have gained the focus
...
}
else
{
// We have lost the focus
...
}
}

2. Bring Application To ForeGround

void CMyAppUi::BringToForeground()
{
// Construct en empty TApaTask object
// giving it a reference to the Window Server session
TApaTask task(iEikonEnv->WsSession( ));

// Initialise the object with the window group id of
// our application (so that it represent our app)
task.SetWgId(CEikonEnv::Static()->RootWin().Identifier());

// Request window server to bring our application
// to foreground
task.BringToForeground();
}

3. Send Application To BackGround
void CMyAppUi::BringToForeground()
{
// Construct en empty TApaTask object
// giving it a reference to the Window Server session
TApaTask task(iEikonEnv->WsSession( ));

// Initialise the object with the window group id of
// our application (so that it represent our app)
task.SetWgId(CEikonEnv::Static()->RootWin().Identifier());

// Request window server to Snedour application
// to BackGround
task.SendToBackground();
}

Other Method If you want to Send or Bring Focus to Other Application

TApaTaskList tasklist(iCoeEnv->WsSession());
TApaTask task(tasklist.FindApp(_L("TestApp")));
task.SendToBackground(); // or BringToForeground()


Library: apgrfx.lib

Thursday, March 01, 2007

How to lock your phone from Code.

RAknKeyLock keyLock; // first step

User::LeaveIfError(keyLock.Connect()); // second step
CleanupClosePushL(keyLock);

keyLock.EnableKeyLock(); // third step

keyLock.Close(); // fourth step
CleanupStack::PopAndDestroy(); // keyLock

Sunday, February 25, 2007

Creating Self-signed Symbian OS Certificates

Introduction

This short note describes the steps required to create a self-signed certificate for signing Symbian OS packages.

Shortly, the steps are the following:

1. Creating the certificate
2. Converting the certificate
3. Installing the certificate
4. Signing the installation package

The rest of this note describes each of the steps in more detail. The discussion assumes that the 9210 SDK has been installed, and paths set up properly.
Creating the Certificate

The certificate and its corresponding private key can be created with the following command:

makekeys -cert -dname "CN=Your Name EM=email@address CO=XX" filename.key filename.cer

The items with emphasis should be replaced with your own values. The dname (distinguished name) parameter string can also contain other values, see the makekeys help for more information. makekeys will prompt you to enter a passphrase for the key, using one is highly recommended.

Important note: QuickEdit mode must be disabled from the shell window, otherwise random data gathering won't work.
Converting the Certificate

For some reason, makekeys creates certificate files that the 9210 certificate manager software cannot read. To work around this, the certificate must be converted to a suitable file format. This is possible using the built-in certificate management tools in Windows 2000 or XP. The following steps are needed:

1. Open the newly generated certificate file by double-clicking it in Explorer
2. Click "Install Certificate" and follow the instructions, using default settings
3. Open "Internet Options" from Control Panel, select the "Content" tab, and click on "Certificates...".
4. Locate the new certificate in the "Trusted Root Certification Authorities" tab. If you used non-default options when installing the certificate, it may be visible in one of the other tabs.
5. Select the new certificate and click "Export...". Follow the Certificate Export Wizard's instructions, and select "DER encoded binary X.509 (CER)" as the export format. Enter a new file name.

The resulting certificate from these steps can be installed on a 9210 communicator. Note that you should retain the original file too, since it can be useful with other SDK tools.
Installing the Certificate

Because the certificate is self-signed, the device will not trust it by default. To install the certificate on the device and set it trusted for software installation, follow these steps:

1. Transfer the file to the device normally, and save it to a known location.
2. Open the Certificate manager from the communicator's Control panel.
3. Select "Add" and choose the file. This installs the certificate.
4. Select the newly installed certificate from the list, select "View details", select "Trust settings" and enable "Software installation".

After this process the Communicator will accept installation packages signed using the new certificate.
Signing the Installation Packages

Finally, to make use of the new certificate, installation packages must be signed using the corresponding private key. This process is documented in the SDK, but, briefly, the steps are the following:

1. Copy the original key and certificate files created by makekeys to a known location. In this example, the files are assumed to be at c:\home\user\keys\filename.key and c:\home\user\keys\filename.cer.
2. Add the following line to the installation package file (project.pkg):

*"c:\home\user\keys\filename.key","c:\home\user\keys\filename.cer"

3. Create the installation package normally. If you set a passphrase for the key, makesis will prompt you for it.

Friday, February 23, 2007

DLL capability model in a Secure Platform.

With platform security, every DLL must have at least the same set of capabilities as the loading process, or otherwise the process is not allowed to load the DLL. For this reason most general-purpose DLLs would need (or close to) ALL -TCB as they cannot know in beforehand all the processes that can/will load them at some point in the future. Even if your DLL is set to have ALL -TCB capabilities, it does not mean that it is using all of them. A DLL (that has a higher capability set than the loading process) cannot leak capabilities to the process.

A DLL capability does not grant the DLL access to any capability-restricted resources (not even if the DLL has ALL -TCB). For that access you will need a process with ALL -TCB capablities. DLL capabilities only reflect a level of trust, so that the loading process can be sure that the DLL it is capable of loading has been tested to be trusted with the set of capabilities that the process has.

To get your DLL signed with these heavy capabilities:

For example, all MTM, FEP, and browser plug-ins require ALL -TCB. If you are developing such a component and require ALL -TCB capabilities, you need to fill in the Capability request form on the Symbian Signed Web site https://www.symbiansigned.com/app/page/requirements and send the form to nokia.testing@nokia.com.
In the form you have to explain why each capability is requested and also give some company background information, for example, if you already have some co-operation with Nokia. This should be done before requesting the developer certificate.
When Nokia gets the capability request form, the case is evaluated with S60 platform. Manufacturer-approved capabilities are granted so that those DLLs that require sensitive capabilities are packaged to an embedded SIS file which is certified first, and the developer should use it in the delivery.

For more information about the process, see the "Testing and Signing with Symbian Platform Security" document at www.forum.nokia.com/testing.

Thursday, February 22, 2007

RSend Method to send SMS.
Include:
#include "rsendas.h"
#include "rsendasmessage.h"
Library:
LIBRARY sendas2.lib

Pros: No need to get Much more capability.
Cons: You can't manipulate msg entry in sms Msging entry. Only possible in MTM method.

void CSmsSendHandler::SendSmsInThirdEditionL(const TDesC& aAddr, const TDesC& aMsg)
{

RSendAs sendAs;
User::LeaveIfError(sendAs.Connect());
CleanupClosePushL(sendAs);

RSendAsMessage sendAsMessage;
sendAsMessage.CreateL(sendAs, KUidMsgTypeSMS);
CleanupClosePushL(sendAsMessage);

// prepare the message
sendAsMessage.AddRecipientL(aAddr, RSendAsMessage::ESendAsRecipientTo);
sendAsMessage.SetBodyTextL(aMsg);

// send the message
sendAsMessage.SendMessageAndCloseL();

// sendAsMessage (already closed)
CleanupStack::Pop();

// sendAs
CleanupStack::PopAndDestroy();

}

Wednesday, February 21, 2007

RSendAs : Send a file bluetooth

A number of people seem to have a problem using RSendAs to send a file via Bluetooth but its more or less the same as sending any other message.

To start, you need to get hold of the bluetooth MTM UID, its in "SendUiConsts.h"

Then its simply a case of:

1. Opening the SendAs session
2. Creating a message using the session
3. Adding the file as an attachment
4. Sending the message

void SendFileL(const TDesC& aFilename)
{
// 1. Open session
RSendAs session;
User::LeaveIfError(session.Connect());
CleanupClosePushL(session);

// 2. Create message
RSendAsMessage message;
message.CreateL(session, KSenduiMtmBtUid);
CleanupClosePushL(message);

// 3. Add attachment
TRequestStatus status;
message.AddAttachment(aFilename.FullName(), status);
User::WaitForRequest(status);

// 4. Send message
if (status.Int() == KErrNone)
{
CleanupStack::Pop(&message);
message.LaunchEditorAndCloseL();
}
else
CleanupStack::PopAndDestroy(&message);

CleanupStack::PopAndDestroy(&session);
}

Monday, February 19, 2007

Some Known Symbian Target Types.

The following target types are supported: [That are more or less know Known to me]

ani
A window server animation DLL.

app
A GUI application. This is deprecated at v9.0. Applications must be converted to EXEs.

ctl
A system control. This is deprecated at v9.0. They must be converted to applications.

dll
A DLL: either a shared library, or a polymorphic interface.

ecomiic
An ECOM implementation collection. This is deprecated at v9.0. The plugin target type should be used instead.

epocexe
An Symbian OS executable that can be launched from the shell. This is an executable program which exports no functions undera multi-process platform and a DLL which is linked with the TIntWinsMain() function exported as ordinal 1 under a single-process platform.

exe
An executable program.

exedll
An executable program for a multi-process platform, a DLL for a single-process platform.

exexp
An executable program with exports.

fsy
A plug-in file system.

implib
Results solely in the generation of a .lib file. It is an error for a component of the IMPLIB type to contain SOURCE statements and the build tools enforce this.

kdll
[If you know any thing about this target please let me know]

kext
[If you know any thing about this target please let me know]

klib
[If you know any thing about this target please let me know]

ldd
A logical device driver.

lib
A static library.

mda
A media-server plug-in DLL (deprecated).

mdl
A MIME recognizer. This is deprecated at v9.0, and should be converted to PLUGIN (ECOM).

notifier
An extended notifier DLL. This is deprecated at v9.0, and should be converted to PLUGIN (ECOM).

opx
An OPL extension.

pdd
A physical device driver.

pdl
A printer driver.

rdl
A recognizer. This is deprecated at v9.0, and should be converted to PLUGIN (ECOM).


[If you know any other target please let me know on my mail]

Thank you
stats counter