Archive for the ‘Android’ Category.

GoogleTv getting started

There were some GoogleTv guys ( Les Vogel and Paul Carff ) coming to town to hold a session on GoogleTv development. This event was facilitated by the local Android meetup group. Naturally I wanted to attend, I haven’t looked at GoogleTv before so why not jump on the oppertunity to get to know GoogleTv development a little. To my surprise I was handed a nice GoogleTv T-shirt and a Vizio GoogleTv device as I walked in the door, w00t !

Lets look at developing for the device, it’s recommended that you develop on Linux, as the Google Tv emulator uses KVM virtual machine to run in, most people use Eclipse as the IDE. Other than that setting up for coding for Google Tv is pretty much the same as coding for Android. First download and install the Android SDK, then download and install the Google Tv extension. Here is a little snag I ran into, when running the Android SDK Manager you will have to toggle the radio button to sort by repository rather than API level to find, “Google Inc. ( )” in the list. Once you see that you can find “Google Tv Addon” below, that’s the one you want, check the box and install the package. With that out of the way, next you need to setup a Android Virtual machine using the Android Virtual Device Manager. When you create your new GoogleTv AVD see if you can set the data partition to 1024 instead of 128, this will help with errors about the emulator not having enough space for installing your application. Otherwise you can also run it from command prompt, after you add the /tools and /platform-tools directories from the sdk to your path. Like this

$ emulator -avd googleTv -partition-size 1024

For some your keyboard might not work either in the Emulator, in order to activate that add Keyboard support in the harware properties of the AVD configuration and set it to “yes”. Now you should be good to go, you might have to start the Emulator from command prompt depending on your setup. Now in your Package Manger, you can look for KVM and install. You will also need computer that supports BIOS virtualization extensions, in order to check on that run

$ kvm-ok

you should see some message like “KVM acceleration can be used” if your good, otherwise you will get some kind of error.

That’s the Emulator at work

I wrote a sample app that plays different media over the internet, it turns out the emulator is not as capable of playing different formats as the regular Android emulator. Most of my streams played on the Android emulator but not on the GoogleTv emulator. It’s a good thing that they gave us GoogleTv devices when we attended the labs event at Google, now I can start coding and try it on the actual device which will work better than on the emulator. The Vizio GoogleTv is only $99 at the moment, if your going to develop for GoogleTv I would recommend getting the device to test on rather than using the emulator.

A lot of Android applications will work just fine on GoogleTv without any modifycation. The most important thing to keep in mind is that the GoogleTv display is Landscape only and the resolution is usually in the Tv format 1280 x 720 or 1920 x 1080. For example my Android BeerWidget runs fine on the GoogleTv without any modifycation.

Android Beer timer Widget

A friend of mine said he wanted a beer app for the Android, really what’s that ? It goes something like this, a beer glass on your Android desktop. The beer glass fills up from 9am to 5pm, once it’s full, well then it’s time to stop working and go out for a beer. On the weekends the glass is always full of course. This would have to be a widget on the desktop so the image / icon can be changed on a timer through the day. Since I hadn’t written an Android widget before, I told my friend, no problem I will write it for you.

Lets declare the widget in the manifest, the service and the alarm receiver as well.

<receiver android:name=“.FxBeerWidget” android:label=“Beer time widget”>
    <action android:name=“android.appwidget.action.APPWIDGET_UPDATE” />
  <meta-data android:name=“android.appwidget.provider” android:resource=“@xml/beerwidgetlayout” />
<service android:name=“.CxUpdateWidgetService” />
<receiver android:name=“.CxBeerAlarmReceiver” />

Then in the AppWidgetProvider we use AlarmManager to update our receiver

// Setup receiver that will call the widgetService     
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent2 =  PendingIntent.getBroadcast(context, 0,
      new Intent(context, CxBeerAlarmReceiver.class),  PendingIntent.FLAG_CANCEL_CURRENT);
// Use inexact repeating which is easier on battery (system can phase events and not wake at exact times)
alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 500, (60*1000), pendingIntent2);

Note that you have to be mindful of the resources you are using and use a long interval. If the person using the phone is playing a game for example when the timer goes off. You do not want to take much resources in order for his game to keep playing smoothly. In our case it’s a simple check and a quick update of a icon if needed.

The CxBeerAlarmReceiver is a BroadcastReceiver which when woken up will start the CxUpdateWidgetService which is a IntentService. The CxUpdateWidgetService will take care of updating the widgets.

public static void updateAllWidgets(Context context)
  final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
  final int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, FxBeerWidget.class));

  // Remote view for the widget
  RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.beerwidget );
  // Setup the beer main Activity as Intent
  Intent beerIntent = new Intent();
  beerIntent.setClass( context, FxMain.class);
  // Setup pending intent, when widget clicked show main screen
  PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, beerIntent, 0);
  views.setOnClickPendingIntent(, pendingIntent);
  // Time status
  int iCurrentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
  // Format it in clock like format, leading zero
  views.setTextViewText(, CxUtil.getTimeString() );
  // Update image only if needed
  int plusNum = whichIcon( iCurrentHour);
  CxLog.d( CxLog.TOKEN, “updating beer image, currhour=” + iCurrentHour + “, plusNum=” + plusNum   );
  // Set the current image
  views.setImageViewResource(, R.drawable.beer72_0  + plusNum );
  // Associate the update views – Loop all id’s
  for(int i=0; i<appWidgetIds.length; ++i)
     AppWidgetManager.getInstance(context).updateAppWidget( appWidgetIds[i], views );

Note that the user can have more than more widget running, there could be one on each desktop, etc. The for loop will take care of that and update all of the widgets. Another cotcha is that you will have to set the click intent for the widget each time the update function is called. Otherwise it will get disconnected from the widget and clicking the widget will not open the FxMain screen.

Here is the Widget if you like to download and install on your Android – BeerTimeWidget

Here is how it looks in action.

Sign align and release Android application

In order to release your app in the Android market place you need to digitally sign it. The instructions are here. But in short I will show you what you need from the command line, you won’t have to read all the instructions. First off make your app .apk name something different then what your going to use in the end. As the process requires the input and output to have different file names.

Lets take a look, this example is from DOS command line

Create the signature key
C:\Temp> keytool -genkey -v -keystore c:\temp\release-key.keystore -alias MyAlias -keyalg RSA -keysize 2048 -validity 10000

Sign using the key
C:\Temp> jarsigner -verbose -keystore release-key.keystore release.MyApp.apk MyAlias

Verify that it took
C:\Temp> jarsigner -verify -verbose release.MyApp.apk

Run the align tool as recommended
C:\Temp> zipalign -v 4 release.MyApp.apk MyApp.apk

And your all done, now publish it and start watching the downloads.

Android screen layout Hirerarchy Viewer

Playing around with a layout for Android screen finally got me in trouble. The visual presentation in the IDE isn’t exactly the same as when you run in the Android emulator. I went looking around for an alternative, it turns out that a Hierarchy Viewer ships with the SDK. Just load your app and the screen you want to examine in the emulator. Then fire up the Hierarchy Viewer and view your layout from there. This nice little app makes it easy to debug your screen layout. If your on windows goto your SDK lib dir on the command line, something like …\android-sdk-windows\tools\lib\ and execute hierarchyviewer.jar

Android play instant sound from resource

I wanted to play short sound bites in a Android application, when playing sounds on the Media player there is a lag as the Media player needs to allocate memory, load the resource etc. If you need to play short sounds in response to button click or when shooting a gun in your game you need it to play instantly in response to what the user just did. In that respect SoundPool is the way to go, it allows preloading the soundbites and gives instant access to the sounds as needed. I created a simple convenience class for it as seen below.

import java.util.HashMap;

public class CxMediaPlayer
private SoundPool mShortPlayer= null;
private HashMap mSounds = new HashMap();

// Constructor
public CxMediaPlayer( Activity pContext )
// setup Soundpool
this.mShortPlayer = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);

// 0-9 Buttons
mSounds.put( R.raw.button_1, this.mShortPlayer.load(pContext, R.raw.button_1, 1) );
mSounds.put( R.raw.button_2, this.mShortPlayer.load(pContext, R.raw.button_2, 1) );
mSounds.put( R.raw.button_3, this.mShortPlayer.load(pContext, R.raw.button_3, 1) );
mSounds.put( R.raw.button_4, this.mShortPlayer.load(pContext, R.raw.button_4, 1) );
mSounds.put( R.raw.button_5, this.mShortPlayer.load(pContext, R.raw.button_5, 1) );
mSounds.put( R.raw.button_6, this.mShortPlayer.load(pContext, R.raw.button_6, 1) );
mSounds.put( R.raw.button_7, this.mShortPlayer.load(pContext, R.raw.button_7, 1) );

// Others
mSounds.put( R.raw.delete_5, this.mShortPlayer.load(pContext, R.raw.correct_answer, 1) );
mSounds.put( R.raw.delete_5, this.mShortPlayer.load(pContext, R.raw.wrong_answer, 1) );

// Plays the passed preloaded resource
public void playShortResource( int piResource )
int iSoundId = mSounds.get( piResource ); iSoundId, 0.99f, 0.99f, 0, 0, 1 );

// Cleanup
public void Release()
// Cleanup
this.mShortPlayer = null;

Then all you need in your Activity is to initiate the player class and call playShortResource when you need a sound played. Your resources should be available in the res/raw directory.

// The media player – OnCreate
  mxMediaPlayer = new CxMediaPlayer( this );
// Play the desired sound – OnClick
  mxMediaPlayer.playShortResource(  R.raw.button_1 );
// Make sure to release resources when done – OnDestroy

Android GUI thread timer sample

I was looking for a simple Android timer to do updates on ticks in one of the views I’m playing with. The problem with spinning off another thread brings up two issues, one is that it takes more resources and the second one is that you will have to switch back over to the UI thread to update the screen. Then I came across a much better solution in the SDK documentation click here. I had to read it a couple of times and when I imported it into my app had to figure out some things a long the way. So for your benefit here is a cut down simple version.

In case you didn’t know see how easy it’s to use the built in Log class, the output will be visible in LogCat output. Also note the call Handler.removeCallbacks(mUpdateTimeTask); to free resources.

package us.kristjansson.test;
import us.kristjansson.test.R;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Window;

public class FxFireWorks extends Activity
        // Timer
        private Handler mHandler = new Handler();
        private Runnable mUpdateTimeTask = new Runnable()
           public void run()
               // Do something
               Log.d( this.toString(), “Do something !!”);
               // timer
               mHandler.postDelayed(mUpdateTimeTask, ( 2 * 1000)) ;
    public void onCreate(Bundle savedInstanceState)

        // Hide the title bar
        // timer
        mHandler.postDelayed(mUpdateTimeTask, 100);

    public void onStop()
        // timer