Archive

Tag Archives: Android

The Ti.mely project provides Titanium access to iOS and Android native timers.  The native nature of these timers can be advantageous for background or long interval poling.

Using Ti.mely

The usage is straightforward, you simply create a new timer object

var timer = timerMod.createTimer();

Attach a listener to listen for the onIntervalChange event as shown below

    function showUpdate(d){
        var msg = "interval changed - interval set to " + d.interval;
            msg += " interval count = " + d.intervalCount;
        Ti.API.info(msg);
    }

    timer.addEventListener('onIntervalChange',showUpdate);

Initialize the timer by calling the start method.  This method takes the interval in milliseconds and an optional debug flag which will print timer information to your console window.

    timer.start({
        interval:2000,
        debug:true
    });

To stop the timer, simply call the stop method as shown below.

  timer.stop();

Native Consideration, ie Side Effects

Each time an interval elapses the onIntervalChange event will be fired.  The firing of this event will cause a trip over the Kroll JavaScript bridge.  For this reason using Ti.mely to implement high speed timers of 500 milliseconds or less could negatively impact app performance.

Get the module

The Ti.mely source code and compiled modules are available on Github(https://github.com/benbahrenburg/ti.mely) under the MIT license.

You can download the compiled modules using the following links

Example app.js

The below sample demonstrates how to use the Ti.mely module.  This app.js is include within the module’s example folder or available for iOS here and Android here.

var timer =  require('ti.mely').createTimer();

var win = Ti.UI.createWindow({
	backgroundColor:'#fff'
});

var how2Label = Ti.UI.createLabel({
	text:"Enter Duration in milliseconds",
	top:20, left:7, right:7, height:20,color:"#000"
});
win.add(how2Label);

var durationText = Ti.UI.createTextField({
	value:1000, top:50, left:7, right:7, height:40, color:"#000"
});
win.add(durationText);

var counterLabel = Ti.UI.createLabel({
	top:100, width:Ti.UI.FILL, height:40,left:7, right:7,color:"#000"
});
win.add(counterLabel);

function showUpdate(d){
	var msg = "interval changed - interval set to " + d.interval;
            msg += " interval count = " + d.intervalCount;
	Ti.API.info(msg);
	counterLabel.text = "Updated " + d.intervalCount  + " times.";
};

var startButton = Ti.UI.createButton({
	title:"Start", top:200, left:7, height:40, width:125
});
win.add(startButton);

startButton.addEventListener('click',function(e){
	counterLabel.text ="Starting Timer";
	timer.addEventListener('onIntervalChange',showUpdate);
	timer.start({
		interval:durationText.value,
		debug:true
	});
});

var stopButton = Ti.UI.createButton({
	title:"Stop", top:200,
	right:7, height:40, width:125
});
win.add(stopButton);

stopButton.addEventListener('click',function(e){
	timer.stop();
	timer.removeEventListener('onIntervalChange',showUpdate);
	counterLabel.text ="Press the Start button to test again";
});

win.open();

The first release of Securely the Titanium security module is now available on Github.  The goal of this project is to provide the tools and components needed to build secure Titanium apps.  Securely provides a comprehensive set of methods designed to easily handle your most common security requirements.

Features include

  • Secure Properties
  • Key Generators
  • String Encryption
  • File Encryption
  • PDF Protection

Get the module

The source and compiled module are both available on Github under the Apache 2 license.

Learn more

Learn more about this module by visiting the following links on Github:

  •  Documentation : Complete method level documentation with examples
  •  Samples : Example app.js files demonstrating how to use each proxy type

The Square TimeSquare project provides a rich and unique full featured Calendar Picker.  The cross-platform nature of this project makes it a perfect candidate for Titanium.

I’m happy to announce, the Ti.SQ modules for iOS and Android which allows you to use this excellent component in your Titanium projects.

The following provides all the details needed to get starting using this module in your projects today.

See it in action

iOS


Android


Get the module

All of the modules code, assets, documentation, and examples are available on github.

Before you start – Please make sure you read the project readme file before starting.  The readme file outlines all API differences and project dependences.

Documentation – Project documentation can be found here.

Examples – The iOS and Android APIs are almost.  A majority of the examples should work cross-platform with only minor updates.  Please make sure you read the documentation regarding the differences between iOS and Android.  The examples can be found for iOS here and Android here.

What to contribute– Pull Requests and other contributions are welcome.  Examples, and documentation are also encouraged.

Show me the Example

The following snippet outlines a basic usage scenario for the Ti.SQ module.

var sq = require('ti.sq');
Ti.API.info("module is => " + sq);

var win = Ti.UI.createWindow({
	backgroundColor:'#fff'
});

var calendarView = sq.createView({
	height:Ti.UI.FILL,
	top:0, bottom:'40dp',
	pagingEnabled:true,
	value:{
		month:6,day:10,year:2013
	},	
	min:{
		month:2,day:15,year:2013
	},
	max:{
		month:10,day:15,year:2013
	}
});
win.add(calendarView);

calendarView.addEventListener('dateChanged',function(d){
truei.API.info(JSON.stringify(d));
	Ti.API.info(JSON.stringify(d.dateValue));
	Ti.API.info(JSON.stringify(d.value));
	Ti.API.info(JSON.stringify(calendarView.value));	
})	

var button = Ti.UI.createButton({
	title:'Click to get selected value',
	height:'40dp', width:Ti.UI.FILL, bottom:0
});	
win.add(button);

button.addEventListener('click',function(d){
	Ti.API.info(JSON.stringify(calendarView.value));
	alert(String.formatDate(calendarView.value,"long"));
})	

win.open();

It is a common requirement to need to restart your app if the user restarts the device.  Although this requirement is common, it can get tricky quickly.  For example do you want to restart in the foreground or background?  What if you want to send a notification instead?

The Android.Tools project has been updated to handle a majority of these scenarios using the new BootReceiver.  This component allows you to do the following:

  • On BOOT_COMPLETED restart your app in either the foreground or background
  • On BOOT_COMPLETED create a notification with information defined in your project’s tiapp.xml
  • You can also use Titanium Properties to configure the above options from within your Titanium app. 

How does it work?

The BootReceiver is configured to work similar to how a native app would when it receives the BOOT_COMPLETED broadcast.  Since Titanium might not yet be loaded, the module will help bootstrap your app based on the configuration elements in your tiapp.xml.

Warning: This functionality requires you update your tiapp.xml file with a few specific elements. I’ve included samples for each scenario, but please plan on spending alittle time exploring in order to get the configurations for your app working properly.

Finding the tiapp.xml entries

The below steps cover how to create the tiapp.xml entries needed for this module to work.

  1. Before installing the module, you will want to build your project for the simulator.  It doesn’t matter if the app is empty or event runs. The goal is to simply have Titanium generate a AndroidManifest.xml file.  You can find this file in your Project/build/android folder as illustrated below in red.

    AndroidManifest.xml Path

  2. To avoid the 2373 restart bug, you will need to add the following properties into your tiapp.xml file.

    
        <property name="ti.android.bug2373.finishfalseroot" type="bool">true</property>
        <property name="ti.android.bug2373.disableDetection" type="bool">true</property>
        <property name="ti.android.bug2373.restartDelay" type="int">500</property>
        <property name="ti.android.bug2373.finishDelay" type="int">0</property>
        <property name="ti.android.bug2373.skipAlert" type="bool">true</property>
        <property name="ti.android.bug2373.message">Initializing</property>
        <property name="ti.android.bug2373.title">Restart Required</property>
        <property name="ti.android.bug2373.buttonText">Continue</property>
    
    

  3. Using the information from step #1’s AndroidManifest.xml add an android configuration node to your tiapp.xml. 

    tiapp.xml example

    (a) Add the two permission lines highlighted in Blue.

    (b) Add the application node from your AndroidManifest.xml collected in step #1. If you are copying and pasting the example, make sure you change the names to match your project information.

Scenario 1: Restart

The first scenario supported by the module is to restart your Titanium app upon receipt of the BOOT_COMPLETED broadcast.

The following diagram demonstrates how to create a receiver entry in your tiapp.xml to use the BootReceiver module.  The section shown in red illstrates the receiver and intent-filter entries needed to be made in order for your app to subscribe to the BOOT_COMPLETED broadcast.

Scenario 1 Diagram

  • bootType : This meta-data element is required and tells the module which action to take. By using the restart option, the module will restart your application upon receipt of the BOOT_COMPLETED broadcast.
  • sendToBack : This meta-data element is required if using the bootType of restart. If true, your app will be restarted in the background upon receipt of the BOOT_COMPLETED broadcast. If false, your app will be restarted in the foreground and the user will be presented with the first window of your app.

Please see the sample tiapp.xml and app.js for the full example files.

Scenario 2: Notification

The second scenario supported by the module is publish a notification upon receipt of the BOOT_COMPLETED broadcast.

The following diagram demonstrates how to create a receiver entry in your tiapp.xml to use the BootReceiver module.  The section shown in red illustrates the receiver and intent-filter entries needed to be made in order for your app to subscribe to the BOOT_COMPLETED broadcast.

 

Scenario 2 Diagram

Meta-Data Elements

  • bootType : This meta-data element is required and tells the module which action to take. By using the notify option, the module will publish a notification using the title and message properties defined in the tiapp.xml receipt of the BOOT_COMPLETED broadcast.
  • title : This meta-data element is required if using the bootType of notify. The title is used to create the title for the notification that will be published after receipt of the BOOT_COMPLETED broadcast.
  • message : This meta-data element is required if using the bootType of notify. The message is used to create the message body for the notification that will be published after receipt of the BOOT_COMPLETED broadcast.

Please see the sample tiapp.xml and app.js for the full example files.

Scenario 3: Using Properties

Allowing for the app at runtime to how to handle the BOOT_COMPLETED broadcast allows for handling more complex use cases but requires additional setup.  Titanium Properties are mapped to configuration elements in your tiapp.xml.  The value from these specific Titanium properties are then to determine the correct action to be taken upon receiving the BOOT_COMPLETED broadcast.

Scenario 3 Diagram

Meta-Data Elements

  • bootType : This meta-data element is required and tells the module which action to take. By using the propertyBased option, the module will look at the following properties to determine which action to take.
  • enabled_property_to_reference : This android:value element contains a reference to the Titanium Property the module will reference to see if this feature has been enabled. This property must contain a Boolean value and is false by default.
  • bootType_property_to_reference : This android:value element contains a reference to the Titanium Property the module will reference to see what action to perform. Just like the primary bootType element, you can use restart or notify to perform the desired actions. Please note all configuration elements such as title, message, sendToBack will be read from the Titanium Properties mapped in your tiapp.xml file.
  • sendToBack_property_to_reference : This android:value element contains a reference to the Titanium Property the module will reference to see if the app should be restarted in the foreground or background.. This property must contain a Boolean value and is true by default. Please note: This property is only used if the Titanium Property define in bootType_property_to_reference is set to restart.
  • icon_property_to_reference : This android:value element contains a reference to the Titanium Property the module will reference to determine which Android Resource Id to use when creating the icon for the notification created on receipt of the BOOT_COMPLETED broadcast. Please note: This property is only used if the Titanium Property define in bootType_property_to_reference is set to notify.
  • title_property_to_reference : This android:value element contains a reference to the Titanium Property the module will reference to determine which Android Resource Id to use when creating the title for the notification created on receipt of the BOOT_COMPLETED broadcast. Please note: This property is only used if the Titanium Property define in bootType_property_to_reference is set to notify.
  • message_property_to_reference : This android:value element contains a reference to the Titanium Property the module will reference to determine which Android Resource Id to use when creating the message for the notification created on receipt of the BOOT_COMPLETED broadcast. Please note: This property is only used if the Titanium Property define in bootType_property_to_reference is set to notify.

Please see the sample tiapp.xml and app.js for the full example files.

How do I get the module?

The module and source are available on Github at https://github.com/benbahrenburg/benCoding.Android.Tools

Any examples?

Usage examples are available on Github at https://github.com/benbahrenburg/benCoding.Android.Tools/tree/master/example

Was lucky enough to get a Nexus 4 the other day and noticed the Developer options were missing.  It seems Google has hidden these options

After a few short searches it seems Google has chosen to hide the developer options by default and use a gesture to unlock. 

To enable developer features:

  1. Go to Settings -> About phone
  2. Scroll to the Build number
  3. Tap 7 times

This adds another row to your ListView with developer options.

The idea of unlocking advantaged OS features is one idea I hope others choose to borrow from Android.

One of the challenges in working with Ti.Android.Intent‘s is knowing if the device has an app installed that will be able to handle the request.  The recommended approach until now was to wrap your startActivity statement within a try/catch statement.

With the new Android.Tools module you can now check if a Ti.Android.Intent has a receiver before submitting. This allows you to write more defensive code blocks like the one below:

//Add our tools module
var tools = require('bencoding.android.tools');
var platformTools = tools.createPlatform();

//Check we have external storage access
if(!Ti.Filesystem.isExternalStoragePresent()){
	alert("Access to external storage required");
	return;
}

//Create a Ti.File to our sample file
var pdfSource = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory + 'your_file.pdf');
//Create a temp file so the intent can read the file
var timeStampName = new Date().getTime();
var tempFile = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory,timeStampName +'.pdf');
if(tempFile.exists()){
	tempFile.deleteFile();
}
tempFile.write(pdfSource.read());
pdfSource = null;

//Create our PDF intent
var intent = Ti.Android.createIntent({
	action: Ti.Android.ACTION_VIEW,
	type: "application/pdf",
	data: session.tempFile.nativePath
});

//Check that the device can open the intent
if(platformTools.intentAvailable(intent)){
	//Since the device can open the intent run startActivity
	try {
		Ti.Android.currentActivity.startActivity(intent);
	} catch(e) {
		Ti.API.debug(e);
		alert('Something went wrong');
	}
}else{
	//No PDF reader to we need to alert the user to go get one.
	alert("Please go to the Google Play Store and download a PDF reader");			
}

Android.Tools project

Github Repo:

 https://github.com/benbahrenburg/benCoding.Android.Tools

Documentation:

https://github.com/benbahrenburg/benCoding.Android.Tools/tree/master/documentation

Example:

https://github.com/benbahrenburg/benCoding.Android.Tools/tree/master/example

I’ve just started a project that requires the development of a few Titanium Android modules.  After configuring all of my SDK and NDK paths I was surprised to be greeted with the message that I had to install JDT…

JDT

Since Titanium Studio is Eclipse based the question is what version of the JDT is compatible?  After alittle hunting I found the “Installing the Java Development Tools” guide that provided all of the steps needed to add this dependency.

 

Hopefully this helps someone that is Googling on how to resolve this warning.

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
        });
    }
};

Looking for an Android version of Ti.App.iOS.LocalNotification? Or just 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 project 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.
});

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.

Follow

Get every new post delivered to your Inbox.

Join 963 other followers