Messaging Service API example

This section presents the full source code of a working sample widget for the Messaging Service. You can download the wgz package for this widget from section Introduction to STEW.

For general information about creating widgets, see section Widget component files.

For widget development and debugging purposes, this example writes its output to c:\data\jslog_widget.log using console.info. For instructions on how to enable logging in the Web browser for S60, see section JavaScript console.

Info.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Nokia//DTD PLIST 1.0//EN" "http://www.nokia.com/NOKIA_COM_1/DTDs/plist-1.0.dtd">
<plist version="1.0">
<dict>
  <key>DisplayName</key>
  <string>MessagingSample</string>
  <key>Identifier</key>
  <string>com.nokia.widget.sapi.Messaging.sample</string>
  <key>Version</key>
  <string>1.0</string>
  <key>MainHTML</key>
  <string>messaging-sample.html</string>
</dict>
</plist>

messaging-sample.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <script type="text/javascript" src="js/messaging-sample.js" charset="utf-8"></script>
  <script type="text/javascript" src="js/common.js" charset="utf-8"></script>
  </head>
<body onload='setup()' bgcolor="#ddeeff">

  <form name="frm">
    <h3>Messaging Service API Sample Widget</h3>
    <input type="button" onclick="getList('img1')" value="GetList"><img id="img1" src="pic/blank.png" width="25" height="25" align="center"><br>
    <input type="button" onclick="SendMMS('img2')" value="SendMmsSync"><img id="img2" src="pic/blank.png" width="25" height="25" align="center"><br>
    <input type="button" onclick="SendASyncMMS('img3')" value="SendMmsAsync"><img id="img3" src="pic/blank.png" width="25" height="25" align="center"><br>
    <input type="button" onclick="cancelSendASyncMMS('img4')" value="cancelSendMmsAsync"><img id="img4" src="pic/blank.png" width="25" height="25" align="center"><br>
    <input type="button" onclick="Delete('img5')" value="RegisterNotification"><img id="img5" src="pic/blank.png" width="25" height="25" align="center"><br>
    <input type="button" onclick="ChangeStatus('img6')" value="DeleteMsg"><img id="img6" src="pic/blank.png" width="25" height="25" align="center"><br>
    <input type="button" onclick="RegisterNotification('img7')" value="RegisterNotification"><img id="img7" src="pic/blank.png" width="25" height="25" align="center"><br>
    <input type="button" onclick="CancelNotification('img8')" value="DeleteMsg"><img id="img8" src="pic/blank.png" width="25" height="25" align="center"><hr>
    <div class='messaging' id='messaging' bgcolor="#ddeeff" style=width:100%;height:100%;overflow:auto>
    </div>
  </form>

</body>
</html>

common.js

// common.js
//
// This file contains some utility functions

// Check the error code and show the information to users
function checkError(message, resultList, divId, imgId)
{
  var errCode = resultList.ErrorCode;
  var msg = "";

  if (errCode) {
    msg = message + "<BR>" + "Failed Error: " + errCode + "<BR>";
    if(resultList.ErrorMessage != undefined)
      msg += "Error Message: " + resultList.ErrorMessage;
    showIMG(imgId,"no");
  } else {
    showIMG(imgId,"yes");
  }

  //print error message
  if(divId != null && divId != undefined)
    document.getElementById(divId).innerHTML = msg;
  console.info(msg);

  return errCode;
}

// Build the message by reading a iteratorable list in a recursive manner
function showIterableList(iterator)
{
  var msg = "";
  try
  {
    iterator.reset();
    var item;
    while (( item = iterator.getNext()) != undefined ){
      msg += showObject( item );
    }
  }
  catch(e)
  {
    alert('<showIterableList> ' + e);
  }
  return msg;
}

// Build the message by reading a JS object in a recursive manner
function showObject( obj )
{
  var txt = "";
  try {
    if ( typeof obj != 'object' )
      return "" + obj + '<BR/>';
    else {
      for(var key in obj) {
        txt +=  key + ":";
        txt += showObject( obj[key] );
        txt += '<BR/>';
      }
      txt += '<BR/>';
    }
  }
  catch (e)
  {
    alert("showObject: " + e);
  }
  return txt;
}

// Show the image to indicate the test result
function showIMG(imgId, isOK)
{
  if(imgId == null || imgId == undefined)
    return;

  if(isOK == "yes")
    document.getElementById(imgId).src = "pic/yes.png";
  else if(isOK == "no")
    document.getElementById(imgId).src = "pic/no.png";
  else
    document.getElementById(imgId).src = "pic/blank.png";
}

// Show elements in object by using 'alert'
function testObject(obj)
{
  var msg = "";
  for(var key in obj) {
    msg = msg + ":" + key + "=" + obj[key];
  }
  alert(msg);
}

// Test whether the input is numeric
function IsNumeric(sText)
{
  var ValidChars = "0123456789.";
  var IsNumber=true;
  var Char;

  for (i = 0; i < sText.length && IsNumber == true; i++)
  {
    Char = sText.charAt(i);
    if (ValidChars.indexOf(Char) == -1)
    {
      IsNumber = false;
    }
  }
  return IsNumber;
}

messaging-sample.js

// messaging-sample.js
//
// In this sample Messaging will be send, deleted, and listed.
// Also, async operation will be canceled

//SAPI Error Codes
// 0    - Success
// 1000 - InvalidServiceArgument
// 1001 - UnknownArgumentName
// 1002 - BadArgumentType
// 1003 - MissingArgument
// 1004 - ServiceNotSupported
// 1005 - ServiceInUse
// 1006 - ServiceNotReady
// 1007 - NoMemory
// 1008 - HardwareNotAvailable
// 1009 - ServerBusy
// 1010 - EntryExists
// 1011 - AccessDenied
// 1012 - NotFound
// 1013 - UnknownFormat
// 1014 - GeneralError
// 1015 - CancelSuccess
// 1016 - ServiceTimedOut
// 1017 - PathNotFound

// Declare the service object
var so;

// id of the div used to display information
const DIV_ID = 'messaging';

// imgid for callback1 function
var imgid_callback1;

// imgid for callback2 function
var imgid_callback2;

// Test entry point
function setup()
{
  try
  {
    so = device.getServiceObject("Service.Messaging", "IMessaging");
      console.info("setup: so: %s", so);
  }
  catch(e)
  {
    alert('<setup> ' +e);
  }
}

//Get message list
function getList(imgId)
{
  // Setup input params using dot syntax
  var criteria = new Object();
  criteria.Type = 'Inbox';
  criteria.Filter = new Object();
  criteria.Filter.MessageTypeList = new Array();
  criteria.Filter.MessageTypeList[0] = 'MMS';
  criteria.Filter.MessageTypeList[1] = 'SMS';

  try
  {
    // Messaging supports synchronous call
    var result = so.IMessaging.GetList(criteria);
    if(!checkError("IMessaging::getList",result,DIV_ID,imgId)) {
      document.getElementById(DIV_ID).innerHTML = showIterableList(result.ReturnValue);
    }
  }
  catch(e)
  {
    showIMG(imgId,"no");
    alert('getList: '+e);
  }
}

//send MMS message
// Sync operation
function SendMMS(imgId)
{
    // Setup input params using dot syntax
    var criteria = new Object();
    criteria.MessageType = 'MMS';
    criteria.To = '4567809';
    criteria.BodyText ='Hello:TestSendSync: Sending message using SAPI';
    try
    {
      result = so.IMessaging.Send(criteria);
    checkError("IMessaging::SendMMS",result,DIV_ID,imgId);
    }
  catch(e)
  {
    showIMG(imgId,"no");
    alert('SendMMS: '+e);
  }
}

//send MMS message
// Async operation
function SendASyncMMS(imgId)
{
  // Setup input params using dot syntax
  var criteria = new Object();
  criteria.MessageType = 'MMS';
  criteria.To = '9876543210';
  criteria.BodyText = 'TestSendASync: Sending message using SAPI';

  try
  {
    imgid_callback1 = imgId;
    result = so.IMessaging.Send(criteria, callback1);
    if(!checkError("IMessaging::SendASyncMMS",result,DIV_ID,imgId)) {
      showIMG(imgId,"");
    }
  }
  catch(e)
  {
    showIMG(imgId,"no");
    alert('SendASyncMMS: '+e);
  }
}

// cancel send MMS message
// Async operation
function cancelSendASyncMMS(imgId)
{
  // Setup input params using dot syntax
  var criteria = new Object();
  criteria.MessageType = 'MMS';
  criteria.To = '9876543210';
  criteria.BodyText = 'TestSendASync: Sending message using SAPI';

  try
  {
    imgid_callback1 = imgId;
    result = so.IMessaging.Send(criteria, callback1);
    if(!checkError("IMessaging::cancelSendASyncMMS",result,DIV_ID,imgId)) {
      showIMG(imgId,"");
      var criteria2 = new Object();
      criteria2.TransactionID = result.TransactionID;
      var result2 = so.IMessaging.Cancel(criteria2);
      checkError("IMessaging::cancelSendASyncMMS",result2,DIV_ID,imgId); 
    }
  }
  catch(e)
  {
    showIMG(imgId,"no");
    alert('cancelSendASyncMMS: '+e);
  }
}

// function deletes message with specified MessageId
// sync operation
function Delete(imgId)
{
  var msgIdStr = prompt("Please type the message id", "0");
  if(msgIdStr == "" || msgIdStr == null)
    return;

  // Setup input params using dot syntax
  var msgId = parseInt(msgIdStr);
  var criteria = new Object();
  criteria.MessageId = msgId;

  // function sends message
  try
  {
    var result = so.IMessaging.Delete(criteria);
    checkError("IMessaging::Delete",result,DIV_ID,imgId);
  }
  catch(e)
  {
    showIMG(imgId,"no");
    alert('Delete: '+e);
  }
}

// function changes status of message
// Sync operation
function ChangeStatus(imgId)
{
  var msgIdStr = prompt("Please type the message id", "0");
  if(msgIdStr == "" || msgIdStr == null)
    return;

  var criteria = new Object();
  var msgId = parseInt(msgIdStr);
  criteria.MessageId = msgId;
  criteria.Status = 'Unread';

  try
  {
    var result = so.IMessaging.ChangeStatus(criteria);
    checkError("IMessaging::ChangeStatus",result,DIV_ID,imgId);
  }
  catch(e)
  {
    showIMG(imgId,"no");
    alert('ChangeStatus: '+e);
  }
}

// function cancels notification of new messages.
// sync operation
function CancelNotification(imgId)
{
  var criteria = new Object();
  criteria.Type = 'NewMessage';
  try
  {
    var result = so.IMessaging.CancelNotification(criteria);
    checkError("IMessaging::CancelNotification",result,DIV_ID,imgId);
  }
  catch(e)
  {
    showIMG(imgId,"no");
    alert('CancelNotification: '+e);
  }
}

// function registers for notification of new messages
// Sync operation
// to test RegisterNotification(): 1) click on RegisterNotification 2) click on sendMMS button to get callback
function RegisterNotification(imgId)
{
  var criteria = new Object();
  criteria.Type = 'NewMessage';
  try
  {
    imgid_callback2 = imgId;
    // Register for notification
    result = so.IMessaging.RegisterNotification(criteria, callback2);
    if(!checkError("IMessaging::RegisterNotification",result,DIV_ID,imgId)) {
      showIMG(imgId,"");
    }
  }
  catch(e)
  {
    showIMG(imgId,"no");
    alert('RegisterNotification: '+e);
  }
}

function callback1(transId, eventCode, result)
{
  console.info("callback1: transId: %d  eventCode: %d result.ErrorCode: %d", transId, eventCode, result.ErrorCode);
  if(!checkError("IMessaging::SendASyncMMS",result,DIV_ID,imgid_callback1)) {
    document.getElementById(DIV_ID).innerHTML = showIterableList(result.ReturnValue);
  }
}

function callback2(transId, eventCode, result)
{
  console.info("callback2: transId: %d  eventCode: %d result.ErrorCode: %d", transId, eventCode, result.ErrorCode);
  if(!checkError("IMessaging::SendASyncMMS",result,DIV_ID,imgid_callback2)) {
    document.getElementById(DIV_ID).innerHTML = "Messaging status was changed";
  }
}