Posts tagged ‘Android’

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. ( dl-ssl.google.com )” 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.

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 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.app.Activity;
import android.media.MediaPlayer;
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)) ;
           }
        };
       
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // Hide the title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.fireworks);
   
        // timer
        mHandler.removeCallbacks(mUpdateTimeTask);
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }

    @Override
    public void onStop()
    {
        super.onStop();
       
        // timer
        mHandler.removeCallbacks(mUpdateTimeTask);
    }
   
}

Android code sample

I wanted to try some smart phone development. I started with Mac OsX in a VirtualBox got the Os installed on the virtual machine, but it wouldn’t boot for me after install. As I was fiddling with that on my Windows box to do iPhone development I thought this is way harder than it’s supposed to be.

Then I thought let’s see how this compares to doing Android development. Went to the Android SDK site and got the SDK which integrates with Eclipse very easily. The installs are just a few clicks of a button and your all set. Of course they have a Hello world sample that you will have running in Android emulator in matter of minutes. The install instructions show how to setup different devices under the emulator etc.

Now what about something more than just Hello world, the SDK comes bundled with all kind of samples, both controls and graphics along with more elaborate Google maps location based samples. It has plenty of stuff to get you going. The great thing is that the code is plain old Java so if you have done any Java or C# development you will feel right at home.

I wanted to do something basic before going into any real development. My idea is to create a simple calculator to calculate handicap score. I used to play pool and we would have a simple handicap system that needed to be referenced to calculate the race between two people that have been matched up.

When Android project is created in Eclipse it will create a bunch of files, resources, manifest, etc. and the main Activity class. The Hello world sample creates control dynamically in code but that can be hard to maintain when your project increases in size. The way to do it is to declare the controls in a XML resource file and then reference it in code. I didn’t see a editor to handle the controls visually but I’m sure there are some out there.

For a simple app the XML is found under res/layout/main.xml in my case it will look like this.

<?xml version=“1.0” encoding=“utf-8”?>
<RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
    android:layout_width=“fill_parent”
    android:layout_height=“fill_parent”>

    <TextView
        android:id=“@+id/lbPlayer1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:text=“Handicap Player1:”/>

    <EditText
        android:id=“@+id/txPlayer1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbPlayer1”/>

    <TextView
        android:id=“@+id/lbPlayer2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/txPlayer1”
        android:text=“Handicap Player2:”/>

    <EditText
        android:id=“@+id/txPlayer2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbPlayer2”/>

    <Button
        android:id=“@+id/btOk”
        android:layout_width=“wrap_content”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/txPlayer2”
        android:layout_alignParentRight=“false”
        android:layout_marginLeft=“10dip”
        android:text=“Calculate” />

    <TextView
        android:id=“@+id/lbMustWin1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/btOk”
        android:text=“Number of games Player1 must win:”/>

    <EditText
        android:id=“@+id/txMustWin1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbMustWin1”/>

    <TextView
        android:id=“@+id/lbMustWin2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/txMustWin1”
        android:text=“Number of games Player2 must win:”/>

    <EditText
        android:id=“@+id/txMustWin2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbMustWin2”/>

       
</RelativeLayout>

Things to notice are the id’s of the controls they need to be unique and how the layout is done for each control you specify where it should show up relative to other controls. That way the manager rendering your view can order them and it will look pretty good.

As I mentioned before the code is in java.

//
package hello.world;
//
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;

public class helloActivity extends Activity implements OnClickListener
{

        /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        // The usual
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);
       
        // Wire up click event
        Button button = (Button)findViewById(R.id.btOk);
        button.setOnClickListener(this);
    }
   
   
    // Implement the OnClickListener callback
    public void onClick(View v)
    {
        // Input from user
        String sPlayer1 = ((EditText)this.findViewById( R.id.txPlayer1)).getText().toString().trim();
        String sPlayer2 = ((EditText)this.findViewById( R.id.txPlayer2)).getText().toString().trim();
       
        // Turn into doubles
        double[] players = {0,0};
        players[0] = Double.parseDouble( sPlayer1 );
        players[1] = Double.parseDouble( sPlayer2 );
       
        // Calculate
        calculate( players );
       
        // Set the results
        ((EditText)this.findViewById( R.id.txMustWin1 )).setText( “” + (int)players[0] );
        ((EditText)this.findViewById( R.id.txMustWin2 )).setText( “” + (int)players[1] );
    }
     
    // Calculates handicap
    private static void calculate( double[] pdaPlayers )
    {
        // STRONGER is lower handicap
        // See who is better rated coming in,
        boolean bStrongerFirst =  pdaPlayers[0] < pdaPlayers[1];
        // Holds results
        double strong_race, weak_race;

        if( bStrongerFirst )
        {
            // What’s the race
            weak_race = Math.max(2, 6Math.floor( pdaPlayers[1] ));
            strong_race = weak_race + Math.round( pdaPlayers[1] – pdaPlayers[0] );
            // set the slots before returning
            pdaPlayers[0] = strong_race;
            pdaPlayers[1] = weak_race;
        }
        else
        {
            // What’s the race
            weak_race = Math.max(2, 6Math.floor( pdaPlayers[0] ));
            strong_race = weak_race + Math.round( pdaPlayers[0] – pdaPlayers[1] );
            //  Set the slots before returning
            pdaPlayers[0] = weak_race;
            pdaPlayers[1] = strong_race;
        }
    }

}  // EOC
 

The onCreate function is the main function of the activity, to get button click event it will be setup there. The rest is straight forward and activated when the user clicks the button. The controls are addressed by R.id.xxxx which is the resource id’s given to each control in the layout XML. The R mapping is created when the project is compiled. For this simple sample, the user input is retrieved and used to calculate handicap which is then presented back to the user in controls below.

The app running in Android emulator
androidhandicap1

Update
—–
I just didn’t find the visual editor, it’s there in Eclipse it shows as tab when you open up the xml file. It’s very primitive one might be better off to use DroidDraw