Message Scheduler: Using Tizen Contact and Messaging Device API's
PUBLISHED
Message Scheduler - Using Tizen Contact and Messaging Device API's
This tutorial with the sample application demonstrates, how to use the Tizen provided Contact
and Messaging
device API's in your web applications.Using the sample application "Message Scheduler", you can schedule a SMS message (to a contact from the device) to be sent at some particular date and time. You can also edit and delete the scheduled message. The sample application is designed to support just single recipient (though that can be extended to support multiple recipients).The application also uses Web SQL database and localStorage for it's persistent data. Now, let's see how this API's have been used in the implimentation of the sample application.
The application mainly uses below API's and methods,
1 Using Contact Device API
Using Contact API you can manage the address books in the device to access, modify, add, and remove contacts within a specified address book.In the sample application the addressbook is initialized and the contacts are retrieved when the user taps on the search button to select a recipient of the message. Also web SQL database is created during the init itself. Below is the initialization code from the sample application.
function InitAddressBook() { /* Initialize */ console.log("initialize called"); try{ gAddressbook = tizen.contact.getDefaultAddressBook(); } catch(e){ console.log('getDefaultAddressBook() error: ' + e.message); } if(gAddressbook){ var sortingMode = new tizen.SortMode('name.firstName', 'ASC'); var phoneFilter = new tizen.AttributeFilter('phoneNumbers.number','CONTAINS', ''); gAddressbook.find(onAllContactsFindSuccess, onError, phoneFilter,sortingMode); // create DB if (localStorage.getItem('dbcreated') !='yes') { console.log("creating database"); createDatabase(); localStorage.setItem('dbcreated','yes'); } } else{ console.log('getDefaultAddressBook() not initialized '); } } function onError(){ console.log('gAddressbook.find() failed'); }
And below function retrieves the contacts and prepares for the list display.
function onAllContactsFindSuccess(contacts) { console.log("onAllContactsFindSuccess called"); var name, str = ''; $("#cont-list").empty(); for ( var i = 0; i < contacts.length ; i++) { str = '<li class="ui-li-has-multiline ui-li-text-ellipsis">' + contacts[i].name.firstName + '</li>'; $("#cont-list").append(str).listview("refresh"); } // for loop ends }
2 Using Messaging Device API
Using Messaging API you can create, send, read messages and also manage messages in the message storage.In the sample application, the function sendScheduledMsgs() is invoked by the alarm trigger on the user specified date/time and queries the SQL database for the scheduled messages for that date/time and sends the SMS message. The function also updates the status of the delivery into the database, which can be seen in message details.
// After retrieving the messages from database if(noOfMsgs) { // Now send all scheduled msgs for(var i=0; i < noOfMsgs; i++) { if( results.rows.item(i).Status != "Failed" ) { var name=results.rows.item(i).Name; var phone=results.rows.item(i).PhoneNumber; var msg=results.rows.item(i).Msg; tizen.messaging.getMessageServices("messaging.sms", serviceListCB, serviceErrorCB); function messageSent(recipients) { alert("Scheduled message sent to " + name); db.transaction(function (tx) { var sqlquery = 'UPDATE MsgTable SET Status='+'"' + status + '"' + 'WHERE Name="' + name + '" and SYEAR="' + tyear + '" and SMONTH="' + tmonth + '" and SDAY="' + tday + '" and SHOUR="' + thour + '" and SMIN="' + tmin + '";' //'"' + ');' ; console.log(sqlquery); tx.executeSql(sqlquery); }); } function messageFailed(error) { status = "Failed"; db.transaction(function (tx) { var sqlquery = 'UPDATE MsgTable SET Status='+'"' + status + '"' + 'WHERE Name="' + name + '" and SYEAR="' + tyear + '" and SMONTH="' + tmonth + '" and SDAY="' + tday + '" and SHOUR="' + thour + '" and SMIN="' + tmin + '";' //'"' + ');' ; console.log(sqlquery); tx.executeSql(sqlquery); }); alert("Failed sending msg-" + error.message); console.log("Failed sending msg- Error: " + error.message); } function serviceErrorCB(error) { console.log("error getting messaging service: " + error.message); } function serviceListCB(services) { if (services.length > 0) { var msgobj = new tizen.Message("messaging.sms", {plainBody:msg, to:[phone]}); services[0].sendMessage(msgobj, messageSent, messageFailed); } } } } } else{ console.log("No scheduled msgs to send"); }
3 Using Alarm Device API
The application also uses the Alarm API to launch an application (in our case, the sample application itself) on the alarm event trigger. As part of scheduling the SMS message of the user,an absolute alarm event is created for the user selected data and time. Along with other user data, the alarm ID is also stored onto the SQL database. The alarm ID would be needed, when the user edits the scheduled message or deletes the scheduled message. Please look for the updateMsg()
and deleteSchMsg()
functions in the sample application for more details. Below code snippet, from the function scheduleMsg()
, shows how an absolute alarm event is created for the defined date/time and stored in the SQL database.
var db = openDatabase('Msgdb', '1.0', 'Messages Database', 2 * 1024 * 1024); db.transaction(function (tx) { console.log("creating abs alarm event"); // Create alarm event for the new msg var date = new Date(year, month, day, hour, min); var absalarm = new tizen.AlarmAbsolute(date); tizen.alarm.add(absalarm, "HeohmeJ13H.MsgScheduler"); console.log("abs alarm event created with ID: " + absalarm.id); console.log("adding data to database"); var sqlquery = 'INSERT INTO MsgTable (Name,Status,PhotoUri,PhoneNumber,Msg,AlarmId,SMONTH,SDAY,SYEAR,SHOUR,SMIN) VALUES ('+ '"' + contactName + '"' + ',' + '"'+ status + '"'+ ','+ '"'+ contactPhoto + '"'+ ',' + '"' + phoneNumber + '"'+ ','+ '"'+ userMsg + '"' + ',' + '"'+ absalarm.id + '"' + ','+ '"'+ month+ '"' + ',' + '"' +day+ '"'+ ',' + '"' + year+ '"'+ ',' + '"' + hour+ '"'+ ',' + '"' + min + '"'+ ');' ; tx.executeSql(sqlquery); console.log("Insert to database successfull"); alert("Scheduled Message for " + contactName ); });
4 Web SQL Database and LocalStorage for Persistent Data
The sample application stores all the contact attributes to web SQL database
table. Based on the need, the required contacts can be queried from the database table to send, edit or delete the entries. Below is the function createDatabase(), which is invoked during the initialization of address book.
function createDatabase() { var db = openDatabase('Msgdb', '1.0', 'Messages Database', 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS MsgTable (P_Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,Name varchar(255) NOT NULL, PhotoUri varchar(255),Status varchar(255),PhoneNumber varchar(255), Msg varchar(255), AlarmId varchar(255),SMONTH varchar(255), SDAY varchar(255), SYEAR varchar(255), SHOUR varchar(255), SMIN varchar(255))'); localStorage.setItem('msgTableCreated','yes'); console.log("createDatabase successfull"); }); }
To avoid accessing the database very often, the sample application uses LocalStorage
for storing the user selected scheduled contact details for editing or deleting operations. The function getScheduledMsgs() stores the user selected details to localstorage as below,
$(document).on("click","ul#msglist > li", function(e){ // when clicked on any contact var ItemIndex=$(this).index(); console.log("Item Index of scheduled msgs: "+ ItemIndex ); // Store the item details to localstorage var rname = results.rows.item(ItemIndex).Name; var rstatus = results.rows.item(ItemIndex).Status; var rphotoUri = results.rows.item(ItemIndex).PhotoUri; var rmsg = results.rows.item(ItemIndex).Msg; var ralarmId = results.rows.item(ItemIndex).AlarmId; var ryear = results.rows.item(ItemIndex).SYEAR; var rmonth = results.rows.item(ItemIndex).SMONTH; var rday = results.rows.item(ItemIndex).SDAY; var rhour = results.rows.item(ItemIndex).SHOUR; var rmin = results.rows.item(ItemIndex).SMIN; localStorage.setItem('recptname', rname ); localStorage.setItem('recptstatus',rstatus); localStorage.setItem('recptphoto',rphotoUri); localStorage.setItem('recptMsg',rmsg); localStorage.setItem('recptAlarmId',ralarmId); localStorage.setItem('recptyear', ryear ); localStorage.setItem('recptmonth',rmonth); localStorage.setItem('recptday', rday ); localStorage.setItem('recptrhour', rhour ); localStorage.setItem('recptrmin',rmin); console.log("The selected items details, "+ "Name: " + rname + " Msg: " + rmsg + " AlarmId: "+ ralarmId); schdMsgDetails(); });
Sample application available for download for reference. See file attachments.
Screenshot:
Picture 1: Sample apps home screen (allows to schedule a message from device contacts)
Picture 2: List of the scheduled messages
Picture 3: Details of the scheduled message, can edit or delete the scheduled message
Development Environment:
Tizen SDK Version : 2.2.0 Build id : 20130708-1957