Linux.com

Home Learn Linux Linux Documentation Android Programming for Beginners: Part 1

Android Programming for Beginners: Part 1

 Don't miss part 2!

With Android phones and tablets making their way into more and more pockets and bags, dipping a toe into Android coding is becoming more popular too. And it's a great platform to code for -- the API is largely well-documented and easy to use, and it's just fun to write something that you can run on your own phone. You don't even need a phone at first, because you can write and test code in an emulator on your Linux PC.  In the first of this two-part intro to Android coding, get a basic timer app up and running and start learning about the Android API. This tutorial assumes some basic familiarity with Java, XML, and programming concepts, but even if you're shaky on those, feel free to follow along!

Dev environment and getting started

A note on versions: the most recent version of Android is 4.2 (Jelly Bean), but as you can see from this Wikipedia chart, there aren't many people using it yet. You're better off coding for one or both of 4.0 (Ice Cream Sandwich) or 2.3 (Gingerbread), especially as Android is entirely forwards-compatible (so your 2.3 code will run on 4.2) but not always backwards-compatible. The code here should work on either 4.0 or 2.3.

android countdown timer

The quickest way to get your dev environment set up is to download the Android Bundle. You'll also need JDK 6 (not just JRE); note that Android is not compatible with gcj. If you already have Eclipse, or wish to use another IDE, you can set it up for Android as described here.

Now, create a project called Countdown either using Eclipse, or from the command line. I set the BuildSDK to 4.0.3, and minimum SDK to 2.2, and (in Eclipse) used the BlankActivity template.

 

My First Android Project: Layout

For our very first program, we're going to do is to show a timer that counts down from 10 seconds when you click a button. Before writing the code, let's create the interface -- what the user will see when they start the app. Open up res/layout/activity_countdown.xmlto create an XML layout, using either the Eclipse graphical editor, or a text/XML editor, to enter this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
      <TextView 
          android:id="@+id/time_display_box" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          android:layout_alignParentTop="true" 
          android:layout_centerHorizontal="true" 
          android:layout_marginTop="60dp" 
          android:text="@string/_00_30" 
          android:textAppearance="?android:attr/textAppearanceLarge"/>
      <Button
          android:id="@+id/startbutton"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/time_display_box"
          android:layout_centerHorizontal="true"
          android:layout_marginTop="41dp"
          android:text="@string/start" />
    
</RelativeLayout>

Note the references to @string/start and @string/__00_30. These values are stored in res/values/strings.xml:

<string name="start">Start</string>
<string name="_00_30">00:30</string>

This illustrates the standard way of referring to Android resources. It's best practice to use string references rather than hard-coding strings.

My First Android Project: Code

Next, open up the CountdownActivity.java file in your editor, ready to write some code. You should already have an onCreate() method stub generated. onCreate() is always called when the Activity is first created, so you'll often do setup and app logic startup here. (Eclipse may also have created an onCreateOptionsMenu()method stub, which we'll ignore for now.) Enter this code:

public class CountdownActivity extends Activity {
	
  private static final int MILLIS_PER_SECOND = 1000;
  private static final int SECONDS_TO_COUNTDOWN = 30;
  private TextView     countdownDisplay;
  private CountDownTimer timer;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_countdown);
        
    countdownDisplay = (TextView) findViewById(R.id.time_display_box);
    Button startButton = (Button) findViewById(R.id.startbutton);
    startButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        try {
          showTimer(SECONDS_TO_COUNTDOWN * MILLIS_PER_SECOND);
        } catch (NumberFormatException e) {
          // method ignores invalid (non-integer) input and waits
          // for something it can use
        }
      }
    });
  }
}

You'll notice the thing that makes this a surprisingly easy first project: the Android API includes a CountDownTimer that you can use. We set up this, and the countdown display, as private member variables. In onCreate() we use the built-in setContentView method to grab our XML layout The R.foo.barsyntax is a standard way to refer to Android XML resources in your code, so you'll see it a lot.

findViewById is another method you'll use a lot; here, it grabs the display and the Start button from the XML layout. For the Button to work when clicked, it needs an OnClickListener. This is an interface, so must be subclassed. We could create a whole new MyButton class to do this, but this is overkill for a single button. Instead, we do it inline, creating a new OnClickListener and its onClick() method. Ours simply calls showTimer() on the number of milliseconds we want to use (currently hard-coded).

So what does showTimer()do?

private void showTimer(int countdownMillis) {
  if(timer != null) { timer.cancel(); }
  timer = new CountDownTimer(countdownMillis, MILLIS_PER_SECOND) {
  @Override
  public void onTick(long millisUntilFinished) {
    countdownDisplay.setText("counting down: " +
    millisUntilFinished / MILLIS_PER_SECOND);
  }
  @Override
    public void onFinish() {
      countdownDisplay.setText("KABOOM!");
    }
  }.start();
}

The CountDownTimer class does most of the work for us, which is nice. Just in case there's already a running timer, we start off by cancelling it if it exists. Then we create a new timer, setting the number of milliseconds to count down (from the showTimer() parameter) and the milliseconds per count interval. This interval is how often the onTick()callback is fired.

CountDownTimer is another abstract class, and the __onTick()__ and __onFinish()__ methods must be implemented when it is subclassed. We override onTick() to decrease the countdown display by a second on every tick; and override onFinish() to set a display message once the countdown finishes. Finally, start() sets the timer going.

If you select 'Run' in Eclipse, you can choose to run this as an Android app, and an emulator will automatically be generated and run for you. Check out the Android docs if you need more information on setting up an emulator, or on running an app from the command line.

Congratulations, you've written your first Android app! In the second part of this series, we'll have a closer look at the structure of an Android app, and make some improvements to the timer to input a countdown time, a Stop button, and menu options. We'll also look at running it on a physical phone rather than the software emulator.

For more information in the mean time, you can check out the Android Development Training section of The Linux Foundation's Linux training website.

 

Comments

Subscribe to Comments Feed
  • kinjal Said:

    Nice gaiudline for me, thank. You!!!!!!!!!!!

  • Abdoulaye Siby Said:

    Nice guideline indeed. But I must add one thing though ... Android is NOT forward compatible. They are starting to tighten the rules to get rid of badly designed applications. For example, an application will be terminated if it tries to open a network request or a socket connection from the main UI thread. All these will finally force developers to write responsive applications. Some of my own apps are still working well on Honeycomb, Gingerbread, and Ice Cream Sandwich, but not on Jelly Bean. Cheers

  • Roger Said:

    Then Googles own RSS -Reader is danger of being closed too i guess.

  • Abdoulaye Siby Said:

    I haven't used that app yet. But I am sure that they will update it before it becomes unusable.

  • kaueeeee Said:

    bevkuff hi rhega yr tu toh....teri kasam

  • chadgamas Said:

    question.how & where can i search of my appli of my googleplay of this unit ts1duo myphone unit

  • db Said:

    When, oh when will we have an alternative to the vile langage java?

  • DavidChipman Said:

    What's wrong with Java? I'll admit it's not my first choice for programming either, but "vile"?

  • Craig Hubley Said:

    I'd go with "vile", too. Just very bad object model, never really was write-once-run-everywhere. Some good languages have been written IN Java though like Clojure.

  • Abdoulaye Siby Said:

    Do you mind using JavaScript? You can try Titatium Studio from AppCelerator at http://www.appcelerator.com/

  • CrizZ Said:

    With the Adnroid NDK you could use C++ for Android development.

  • whitehawk66 Said:

    Oh my: I'll get back to this once I come up with a truly inspired notion. Staring into a computer screen churning out this kind of language would be a soul killer to me. Thankfully, I know how to create other things. Peace

  • sadik Said:

    for me Nice gaiudline for Android programming

  • Maria Said:

    Know something, I had no desire programirovat Android. Be kind in the future, please contact me in Russian.

  • benny Said:

    For me it's just another new world of discovery!

  • Berka Said:

    Hello i can`t find CountdownActivity.java Where is it? Hope someone can help me!

  • Dhiren Dash Said:

    On the left side pane, drop down "src", you will see, "com..". Drop down again and you will have a file with .java extension. And that s it.

  • Dhiren Dash Said:

    This is not a tutorial for beginners. And there are no imports too.

  • Berka Said:

    Thanks but When i drop down The com.. I have a java filé called mainactivity is this The filé iam looking för?

  • Vijay Said:

    The example didn't work for me without adding the following includes to CountdownActivity.java: import android.app.Activity; import android.widget.TextView; import android.os.CountDownTimer; import android.widget.Button; import android.view.View; otherwise, thanks for the tutorial!

  • cab jones Said:

    I am confused about "need JDK 6 not just JRE." I downloaded the latest Android package (Windows). Java -version reports 1.7.0_10 and I have the folder C:\Program Files\Java\jdk1.7.0_10, ...\jre7. Perhaps that means I have JDK 7, but I can't precisely verify that since the caution was "not JRE). By the way, I have Cygwin installed, so I can use which or whatever. How do I verify that I have JDK 6 (at least)? I've done a tiny bit of one tutorial encountered no problems--perhaps I am being too much a worry-wart.

  • ksanger Said:

    I was expecting a tutorial for a beginner. I've been at it all day trying to configure Eclipse and the Android SDK before finding a bundle. Actually had Eclipse setup ok until I upgraded the SDK which was no longer compatible and required an update to Eclipse which broke everything. So here I am trying to write a first program. Not a total noob, I've written in java using netbeans. Have not written for Android nor used eclipse. I am confused by the next step. "Now, create a project called Countdown either using Eclipse, or from the command line. I set the BuildSDK to 4.0.3, and minimum SDK to 2.2, and (in Eclipse) used the BlankActivity template." I had alreay run the tool Android and installed Android 2.3. Don't know what is meant by set the BuildSDK to 4.0.3 and the minimum SDK to 2.2? Does that mean install Android 2.2 using the tool "Android"? Or is there a setting in eclipse? Then take the next line. "used in the BlankActivity template". If in eclipse I sellect File, New Project, and then open up Android I get choices of "Android Application Project", "Android Project from Existing Code", "Android Sample Project", or "Android Test Project". Which of these is a BlankActivity template? Then again, if I close eclipse and open it up again, then select the file icon New, then open Android, I get different choices of "Android Activity", "Android Application Project", "Android Icon Set", "Android Object", "Android Project from Existing Code", "Android Sample Project", "Android Test Project", "Android XML File", "Android XML Layout File", "Android XML Values File", or "Template Develoment Wizard". Selecting Activity, Next, brings up "Blank Activity" as a choice. By creating a project called CountdownTimer will calling my new activity CountdownTimer do the same thing? Or do I need to create an Android project and add a blank activity to it? The blank activity form asks me to select a project. So you must mean create an Android project, but haven't specified which one. Then we must have to add an activity? In one paragraph I am lost again. I would not rate this as a beginner's first tutorial.

  • Dark Penguin Said:

    I'm having a lot of trouble as well. I've tried one of the WROX books and two or three of the online tutorials, but there are always unresolved references or menu options missing due presumably to version conflicts. In this I have the import of CountDownTimer in place but I can't seem to use its constructor. For that matter, in the code presented I see where timer is declared but I don't see any initialization for it. Wish I knew Java better; I've hardly looked at it since the siren call of C#.

  • Work order management Said:

    the Service Proz mission is "to provide practical, efficient, dependable and logical software that improves the operational efficiencies of home service businesses." Since the introduction of Cloud-based, on-demand service management software, the entire organization is connected all-day, every day, and anywhere in the world with the information they need. There are no more disagreements or misunderstandings because all information is always available. The Office Manager sees the full picture of the entire business including daily work orders, the schedule, customer appointments, and billing. The Dispatch team sees the planned schedule, its current progress, and swiftly reacts to changes. The Field Technician sees their scheduled work and all necessary details on their smartphone or tablet such as when, where, the type of work, skills needed, and customer details. work order management

  • Mani Said:

    Nice tutorial for me. How to I download the api level 10 manualy. Please tell the link.

  • Abdoulaye Siby Said:

    I think it is safer and easier to use the tools provided by the Android SDK manager either in the Android Developer Tools (ADT) or in Eclipse or on the command line. The detail explanation is on the Android Developer site. Unfortunately I don't have the direct URL to the page where it shows the command line instructions, but I can tell you that it is part of the very first steps explaining how to setup an Android development environment. Good luck.

  • chris Said:

    "This tutorial assumes some basic familiarity with Java, XML, and programming concepts, but even if you're shaky on those, feel free to follow along!" Sorry, it only assumes a working knowledge of Eclipse [about 30 hours] and how xml and java interact in Android [20 hrs]. In this respect, it is no different than most non audio-visual tutorials. Massive knowledge is assumed.

  • DavidChipman Said:

    Some "tutorial", then.... It's not for "Beginners" as the title suggests.

  • Alex Said:

    This is actually for the very beginners , this was my first application , and i manage it !

  • Paul A. Nardi Said:

    I agree that a little more infrastructure i.e., how to set up and RUN this app would be appropriate for this tutorial. This is usually the part that beginners struggle with the most and bloggers seem to have the most trouble explaining.

  • Dark Penguin Said:

    If you're using Eclipse the typical procedure is that you set up an Android Virtual Device which you can configure to resemble the device your app should run on. Look for the AVD Manager icon in the Eclipse menu bar (the IDE's menu, not the Windows menu bar). Of course, you can also connect a real Android-powered device into the USB port and run your app on it. This page explains how to do it either way. http://developer.android.com/training/basics/firstapp/running-app.html This seemed a great tutorial, but it all went pear shaped for me when I tried to do the next part on creating GUIs. The xml files it tells me to modify either aren't there or they're not where they are supposed to be per the examples, and by taking my best educated guess as to which file I'm supposed to edit works out about as well as you'd expect.

  • Arindam at venturehire Said:

    nice post,thanks http://venturehire.co/courses/android-app-development-online-workshop/

  • rakesh Said:

    really nice tutorial for Android beginner ! Very informative and fruitful keep writing like this. http://www.tanzaniteinfotech.com/mobile-app/android-application-development/ Thanks Tanzanite Infotech

  • hicham Said:

    very useful tut,but quite complicated for beginners. ps our developer "juliet kemp" is really pretty!

  • Ravi Said:

    Worth trying this: http://www.wingnity.com/android. These guys are providing free online classes for android.

  • Cristian Said:

    Very nice guide Juliet. Its appreciated

Upcoming Linux Foundation Courses

  1. LFD331 Developing Linux Device Drivers
    25 Aug » 29 Aug - Virtual
    Details
  2. LFS422 High Availability Linux Architecture
    08 Sep » 11 Sep - Raleigh, NC
    Details
  3. LFS426 Linux Performance Tuning
    08 Sep » 11 Sep - New York
    Details

View All Upcoming Courses

Become an Individual Member
Check out the Friday Funnies

Sign Up For the Linux.com Newsletter


Who we are ?

The Linux Foundation is a non-profit consortium dedicated to the growth of Linux.

More About the foundation...

Frequent Questions

Join / Linux Training / Board