Enabling Nexus 4 Developer Options

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.

Determine if Intent Receiver Exists on Android using Titanium

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

Titanium Android Module JDT Setup

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.

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