OneTok Android Titanium Module

I am happy to announce the Ti.OneTok module for Android.  This joins the iOS module created a few months ago.

The Module

The Ti.OneTok module provides a wrapper around the OneTok SDK allowing you to call it from your Titanium Project.  The Ti.OneTok module is available for download from the github project.

The Code

The complete code, documentation, and example app.js is available for download on github

AndroidModule, Documentation, and example

iOSModule, Documentation, and example

Ti.OneTok is available under the Apache 2 license so feel free to fork, extended, and contribute.

The Example

function startRecording(){
    var oneTokOutput = [];

    //This method is called on error
    function onError(e){
        Ti.API.info(e);
        alert('Errored while recording');
    };

    //This method is called as OneTok processes your
    //speak results. This will be called several times before finish
    function onResults(e){
        Ti.API.info("results=" + JSON.stringify(e));
        //We add the pending results to be used later.
        oneTokOutput.push(e);
        //You can check the result_type to determine if
        //a valid result has been returned
        if(e.result_type=='valid'){
            Ti.API.info("Valid Results=" + JSON.stringify(e));
        }
    };

    //This method is called when the recording session has finished
    function onFinish(e){
        alert('Recording Completed');
        Ti.API.info(JSON.stringify(oneTokOutput));
    };

    if(!Ti.Network.online){
        alert("I'm sorry a network connection is needed to use this module");
    }else{
        oneTokSession.startRecording({
                onResults:onResults, //Add callback to process results, called many times
                onError:onError, //Add callback to handle error messages
                onFinish:onFinish  //Add callback to handle when recording has finished
        });
    }
};

Android AlarmManager for Titanium

Looking for access to Android’s native AlarmManager in your Titanium project?

Using the new benCoding.AlarmManager you can now schedule alarms and services easily.

Want To Download The Module?

You can download the compile module here.  Before getting started please take a look at the “Before You Start” section in the documentation and download the full example project located here.

Interested In The Source?

The source is available in the benCoding.AlarmManager repo on GitHub.

Before You  Start

How Does It Work?

The AlarmManager module provides an API for create AlarmManager alerts.  The module also provides methods that allow you to schedule your Titanium Android Services to be launched. This is an easy method for scheduling code execution even when your app isn’t active.

addAlarmNotification

The addAlarmNotification allows you to schedule an Alarm that will then create an notification.

You can create an AlarmNotification using the below properties:

  • contentTitle– (Required) The title of the notification
  • contentText– (Required) The text of the notification
  • minute– (Required) The minute of the start time.
  • hour– (Optional) The hour you want to start the alarm
  • day– (Optional) The day you want to start the alarm
  • month– (Optional) The month you want to start the alarm
  • year– (Optional) The year you want to start the alarm
  • playSound(Optional) Play the default notification sound when alarm triggered.
  • vibrate(Optional) Vibrate the device on notification. Please note this requires the vibrate permission.
  • showLights(Optional) Activate notification lights on device when alarm triggered.
  • icon– (Optional)The icon of the notification
  • repeat – (Optional) Used to schedule a repeating alarm. You can provide a millisecond value or use the words hourly, daily, monthly, yearly.

Please note if you omit the day, month, and year parameters the module will assume you mean to make the alarm effective from today and add the number of minutes provided.

The valid repeat options are:

  • hourly
  • daily
  • monthly
  • yearly

You can also provide a millisecond value to schedule your own repeat frequency.

addAlarmService

The addAlarmService allows you to schedule an Alarm that will run a service within your Titanium App.

Before using this method you will need to define a service and re-compile your project. After recompiling your project open your /build/AndroidManifest.xml to file your full service name. This is important as Titanium generates this name. To learn more about Android Services please read the documentation here.

You can create an AlarmService using the below properties:

  • service– (Required) The full service name from your AndroidManifest.xml to be run.
  • minute– (Required) The minute of the start time.
  • hour– (Optional) The hour you want to start the alarm
  • day– (Optional) The day you want to start the alarm
  • month– (Optional) The month you want to start the alarm
  • year– (Optional) The year you want to start the alarm
  • interval– (Optional) The value used to create an interval service. This value must be in milliseconds.
  • forceRestart– (Optional) Force the service to restart if it is already running.
  • repeat – (Optional) Used to schedule a repeating alarm. You can provide a millisecond value or use the words hourly, daily, monthly, yearly.

Please note if you omit the day, month, and year parameters the module will assume you mean to make the alarm effective from today and add the number of minutes provided.

The valid repeat options are:

  • hourly
  • daily
  • monthly
  • yearly

You can also provide a millisecond value to schedule your own repeat frequency.

cancelAlarmNotification

This method cancels all alarms submitted using the addAlarmNotification method. Unfortunately if you want to cancel only one alarm you need to cancel them all and re-submit. This is due to how Android handles pendingIntents.

cancelAlarmService

This method cancels all alarms submitted using the addAlarmService method. Unfortunately if you want to cancel only one alarm you need to cancel them all and re-submit. This is due to how Android handles pendingIntents.

Receivers

Android Alarm’s work using BroadcastReceivers. In order to have your Titanium project subscribe to the Alarms it generates you need to add the receivers into your tiapp.xml file.

The benCoding.AlarmManager uses two receivers. One for each kind of Alarm you can schedule. See below for the example.

<receiver android:name="bencoding.alarmmanager.AlarmNotificationListener"></receiver>
<receiver android:name="bencoding.alarmmanager.AlarmServiceListener"></receiver>

Documentation & Examples

Full documentation is available here, additionally there is a fully functional sample project available for download here. Please note the same project is not included in your module zip file.

Show Me Some Code

Since the AlarmManager module requires the setup of BroadcastReceivers and specific service names I would recommend taking a look at the example app.js before starting.

Please find below a code snippet from the example project showing how to use a few of the methods.


//Import our module into our Titanium App
var alarmModule = require('bencoding.alarmmanager');
var alarmManager = alarmModule.createAlarmManager();

//Set an Alarm to publish a notification in about two minutes
alarmManager.addAlarmNotification({
    icon: Ti.Android.R.drawable.star_on, //Optional icon must be a resource id or url
    minute:2, //Set the number of minutes until the alarm should go off
    contentTitle:'Alarm #1', //Set the title of the Notification that will appear
    contentText:'Alarm & Notify Basic', //Set the body of the notification that will apear
    playSound:true, //On notification play the default sound ( by default off )
    vibrate:true, //On notification vibrate device ( by default off )
    showLights: true, //On notification show the device lights ( by default off )
});

//Below is an example on how you can provide a full date to schedule your alarm
//Set an Alarm to publish a notification in about two minutes and repeat each minute
alarmManager.addAlarmNotification({
    year: now.getFullYear(),
    month: now.getMonth(),
    day: now.getDate(),
    hour: now.getHours(),
    minute: now.getMinutes() + 2, //Set the number of minutes until the alarm should go off
    contentTitle:'Alarm #3', //Set the title of the Notification that will appear
    contentText:'Alarm & Notify Scheduled', //Set the body of the notification that will apear
    repeat:60000 //You can use the words hourly,daily,weekly,monthly,yearly or you can provide milliseconds.
    //Or as shown above you can provide the millesecond value
});

//Schedule a service to be run (once) in about two minutes
alarmManager.addAlarmService({
    //The full name for the service to be called. Find this in your AndroidManifest.xml Titanium creates
    service:'com.appworkbench.alarmtest.TestserviceService',
    minute:2 //Set the number of minutes until the alarm should go off
});

//Schedule a service to be run (once) in about two minutes, then to run at the same time each day
alarmManager.addAlarmService({
    //The full name for the service to be called. Find this in your AndroidManifest.xml Titanium creates
    service:'com.appworkbench.alarmtest.TestserviceService',
    year: now.getFullYear(),
    month: now.getMonth(),
    day: now.getDate(),
    hour: now.getHours(),
    minute: now.getMinutes() + 2, //Set the number of minutes until the alarm should go off
    repeat:'daily' //You can use the words hourly,daily,weekly,monthly,yearly or you can provide milliseconds.
});

Android Emulator Snapshots

Want to make any mobile developer flinch?  All you have to do is mention the Android Emulator.  Even with Google’s recent updates this is still a pain point for many developers.

It looks like some relief is here.  Last night on twitter Tony Lukasavage posted a tip on using snapshots.

The Android emulator snapshot enables the ability to save and restore its state to a ‘snapshot’ file in each AVD – so you can usually avoid booting when you start the emulator.  You can read more about this on the Android Tools site here.

In my testing, this is literally a “Go Faster” button and has reduced my load times from 5 minutes to about 1 minute.

Great how do I enable it?

Here is a quick walk through on how I enabled this feature. Before you start make sure you close the Android emulator.

Open the AVD Manager

The first thing you want to do is open the AVD manager.  The easiest way to do this is by going to your <Android SDK Folder>/tools  directory and issuing the terminal command  ./Android AVD as shown below.

AVD Terminal Command

This will open the AVD Manager and show you all of the AVD images you’ve created. The below shows what the AVD Manager looks like on my machine.

AVD Manager

You can see that all of my AVD images have been generated by the Titanium build process.

Enable Snapshot in your AVD image

After you’ve opened the AVD Manager you want to select an AVD Image to enable snapshots. Select your AVD Name and select the Edit button on the right side of the AVD Manager menu.

This will open the AVD Editor screen.  If you have Android Tools r9 or higher you should see a section called Snapshot ( circled below ).  Update the checkbox to enable this feature.

Enable Snapshot

After enabling the snapshot feature press the Edit AVD button.  You will receive a confirmation message similar to the below.

AVD Edit Confirmation

Repeat

You will want to repeat this process with all of your AVD files.

Launch

The next time you launch the emulator for your updated AVD images you’ll see a dramatic improvement in launch speed.

Using DDMS To Set Your Android Emulator’s Location

In an earlier post I covered how to use terminal to set the location for the Android Emulator.  A few people mentioned that it might be worth covering how to do the same using the Dalvik Debug Monitor Server (DDMS).  When building Android Apps I tend to have this app open in the background since it provides helpful memory and process monitoring.

DDMS is a utility that provides a ton of useful information.  I highly recommend reading its documentation here.

If your IDE supports the ADT plugin you can even use DDMS within your IDE.  To make things easier, I’ve covered how to use DDMS as a stand alone application below. Please reference your IDE’s documentation for ADT support and installation instructions.

Finding DDMS

DDMS is located in <Your Android SDK Folder> / tools.  The below example shows this installation path where the root SDK folder is called AndroidSDK. Depending on your installation your path might be different.

image

Opening DDMS

To launch DDMS in stand alone mode, simply double click on DDMS. You will see a DOS or terminal window for a second when the application is loading.

Setting Your Location

Now that you have DDMS open, you want to select your emulator from the list of devices on the left hand side navigator as pictured below.

image

After selecting your device, click on the “Emulator Control” tab on the right tabbar as pictured below.

image

This tab lists all of the emulator settings you can update using DDMS. The location options are at the bottom of the tab. 

DDMS allows you to set the location in the below ways.

  • Manual – set the location by manually specifying decimal or sexagesimal longitude and latitude values.
  • GPX – GPS eXchange file
  • KML – Keyhole Markup Language file

The below shows using the manual option to set the coordinates to New York’s Time Square. After updating your location information press the “Send” button. This will update the emulator with your new location information. Please note you might need to restart your App or perform a location lookup in the emulator’s native Map App in order to jump start the process.

image

Quick Walk Through Video

Setting Your Location in the Android Emulator

It seems almost all of the Apps I write these days are location aware in some regard.  I’ve written here about the new iOS Simulator’s location setting and wanted to show the same for the Android Emulator.

There are several different ways to sent the emulator’s location information. Since I use a few different development environments I like to use Terminal since it let’s me keep the same workflow no matter the development platform.

Step 1: Platform Tools

Open Terminal and go to your AndroidSDK / platform-tools directory.  Android let’s you call the directory you install the Android SDK into anything. For this example, I’m using the name AndroidSDK.

 Platform Tools Directory

Step 2: Finding Attached Devices

The adb utility allows us to query all of the devices (and emulators) that are currently attached to the system.  To do this we use the adb devices command as shown below.

adb command

After pressing enter you will see a list of all the devices linked to the system.  In this case there is only the emulator shown below. 

ado device output

 

Step 3: Connect To Emulator

Using the information above we can telnet into the emulator using the below command.

Telnet connection command

This will connect you to the emulator as shown below.

Telnet connection Message

This allows us to connect to the emulator directly and issue commands.

Step 4: Geo Fix A Location

Now we’ve connected to the emulator, we can use the geo fix command to set our location coordinates.  The below example shows setting the coordinates for Time Square in New York City.

Geo Fix Your Location

The format is:

geo fix command format

You can read more about the different geo commands at the bottom of this page.

 

Video Walk Through

Here is a short video walk through of the above steps: