Saturday, August 14, 2010

Android Media Player

The exercise play, pause and stop a mp3 file in /res/raw folder, using android.media.MediaPlayer.



First of all, copy a mp3 file in /res/raw folder.



main.xml
 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
<Button
  android:id="@+id/playpause"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Play"
  />
<Button
  android:id="@+id/quit"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Quit!"
  />
<TextView
  android:id="@+id/state"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
</LinearLayout>



AndroidMediaPlayer.java
 

package com.exercise.AndroidMediaPlayer;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidMediaPlayer extends Activity {
 
 MediaPlayer mediaPlayer;
 Button buttonPlayPause, buttonQuit;
 TextView textState;
 
 private int stateMediaPlayer;
 private final int stateMP_NotStarter = 0;
 private final int stateMP_Playing = 1;
 private final int stateMP_Pausing = 2;
 
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
    
      buttonPlayPause = (Button)findViewById(R.id.playpause);
      buttonQuit = (Button)findViewById(R.id.quit);
      textState = (TextView)findViewById(R.id.state);
    
      buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);
      buttonQuit.setOnClickListener(buttonQuitOnClickListener);
    
      initMediaPlayer();
    
  }

  private void initMediaPlayer()
  {
   mediaPlayer = new  MediaPlayer();
      mediaPlayer = MediaPlayer.create(AndroidMediaPlayer.this, R.raw.music);
      stateMediaPlayer = stateMP_NotStarter;
      textState.setText("- IDLE -");
  }

  Button.OnClickListener buttonPlayPauseOnClickListener
   = new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    switch(stateMediaPlayer){
    case stateMP_NotStarter:
     mediaPlayer.start();
     buttonPlayPause.setText("Pause");
     textState.setText("- PLAYING -");
     stateMediaPlayer = stateMP_Playing;
     break;
    case stateMP_Playing:
     mediaPlayer.pause();
     buttonPlayPause.setText("Play");
     textState.setText("- PAUSING -");
     stateMediaPlayer = stateMP_Pausing;
     break;
    case stateMP_Pausing:
     mediaPlayer.start();
     buttonPlayPause.setText("Pause");
     textState.setText("- PLAYING -");
     stateMediaPlayer = stateMP_Playing;
     break;
    }
    
   }
  };

  Button.OnClickListener buttonQuitOnClickListener
 = new Button.OnClickListener(){

  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
   mediaPlayer.stop();
   mediaPlayer.release();
   finish();
  } 
  };
}

Simple Temperature Converter

4.1. Create Project

. Select File -> New -> Other -> Android -> Android Project and create the Android project "de.vogella.android.tempconvertor" Maintain the following.



Tip

I think this wizard should have the option to add the project to an existing working set. Please stare at Android New Project Wizard should have the option to add to Working set to get this functionality.

Press "Finish". This should create the following directory structure.


"R.java" is a generated class which contains the text and the UI elements. Please do not try to modify this class manually.

4.2. Two faces of things

The Android SDK allows to maintain certain artifacts, e.g. strings and UI's, in two ways, via a rich editor and directly via XML. The following description tries to use the rich UI but for validation lists also the XML. You can switch between the two things the the tab on the lower part of the screen. For example:

4.3. Create attributes

Android allows to create attributes for resources, e.g. for strings and / or colors. These attributes can be used in your UI definition via XML or in your Java source code.
Select the file "res/values/string.xml" and press "Add". Select "Color" and maintain "myColor" as the name and "#3399CC" as the value.




Add also the following "String" attributes. String attributes allow to translate the application at a later point.

Table 1. String Attributes
NameValue
buttonHandlermyClickHandler
celsiusto Celsius
fahrenheitto Fahrenheit




Switch to the XML representation and validate that you maintained the values correctly.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Convert!</string>
    <string name="app_name">Celsius to Fahrenheit Converter</string>
 <color name="myColor">#3399CC</color>
<string name="buttonHandler">myClickHandler</string>
<string name="celsius">to Celsius</string>
<string name="fahrenheit">to Fahrenheit</string>
<string name="calc">Calculate</string>
</resources>

   

4.4. Add UI Elements

Select "res/layout/main.xml" and open the Android editor via double-click. This editor allows to maintain the UI via drag and drop or directly via the XML source code. You can switch between both representations via the tabs at the bottom of the editor.
Switch to "main.xml" and verify that your XML looks like the following. Especially the grouping of RadioButtons into a group is difficult to get right with the editor.
Delete the "Hello World, Hello!" via a right mouse click. From the "Views" bar, drag in an "EditText". Add from the layout a "RadioGroup" and then two RadioButtons, add one "Button". The result should look like the following and the corresponding XML is listed below. Especially putting the RadionButtons into the RadioGroup is hard via the rich UI editor.



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">

<EditText android:text="@+id/EditText01" android:id="@+id/EditText01" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
 <RadioGroup android:id="@+id/RadioGroup01"
  android:layout_width="wrap_content" android:layout_height="wrap_content">
  <RadioButton android:text="@+id/RadioButton01" android:id="@+id/RadioButton01"
   android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
  <RadioButton android:text="@+id/RadioButton02" android:id="@+id/RadioButton02"
   android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
 </RadioGroup>
 <Button android:text="@+id/Button01" android:id="@+id/Button01"
  android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

   

4.5. Maintain UI properties

If you select a UI element you can change its properties via the properties view. Select EditText and change the property "Layout Width" to "fill_parent".


Assign the "celsius" string attribute to your "text" property of the first radio button and "fahrenheit" to the second. Set the property "Checked" to true for the first RadioButton. Assign "calc" to the text property of your button and assign "buttonHandler" to the "onClick" property. Delete the text property in the EditText (this means no text will be initially shown) and set the "Input type" property to "numberSigned" and "number decimal".
Select the complete widget and use the Properties view to set the property "background" to the color attribute "myColor".


Switch to the "main.xml" tab and verify that the XML is correctly maintained.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/myColor">

<EditText android:id="@+id/EditText01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:inputType="numberSigned|numberDecimal"></EditText>
 <RadioGroup android:id="@+id/RadioGroup01"
  android:layout_width="wrap_content" android:layout_height="wrap_content">
  <RadioButton android:id="@+id/RadioButton01"
   android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/celsius" android:checked="true"></RadioButton>
  <RadioButton android:id="@+id/RadioButton02"
   android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/fahrenheit"></RadioButton>
 </RadioGroup>
 <Button android:id="@+id/Button01"
  android:layout_height="wrap_content" android:onClick="@string/buttonHandler" android:layout_width="wrap_content" android:text="@string/calc"></Button>
</LinearLayout>

   

4.6. Code your applicatioin

Change your code in "Convert.java" to the following. Note that the "myClickHandler" will be called basedon the "On Click" property of your button.

package de.vogella.android.tempconvertor;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class Convert extends Activity {
 private EditText text;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  text = (EditText) findViewById(R.id.EditText01);

 }

 // This method is called at button click because we assigned the name to the
 // "On Click property" of the button
 public void myClickHandler(View view) {
  switch (view.getId()) {
  case R.id.Button01:
   RadioButton celsiusButton = (RadioButton) findViewById(R.id.RadioButton01);
   RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.RadioButton02);
   if (text.getText().length() == 0) {
    Toast.makeText(
      this,
      "Please enter a valid number", Toast.LENGTH_LONG).show();
    return;
   }
   
   float inputValue = Float.parseFloat(text.getText().toString());
   if (celsiusButton.isChecked()) {
    text.setText(String
      .valueOf(convertFahrenheitToCelcius(inputValue)));
   } else {
    text.setText(String
      .valueOf(convertCelciusToFahrenheit(inputValue)));
   }
   // Switch to the other button
   if (fahrenheitButton.isChecked()) {
    fahrenheitButton.setChecked(false);
    celsiusButton.setChecked(true);
   } else {
    fahrenheitButton.setChecked(true);
    celsiusButton.setChecked(false);
   }
   break;
  }
 }

 // Converts to celcius
 private float convertFahrenheitToCelcius(float fahrenheit) {
  return ((fahrenheit - 32) * 5 / 9);
 }

 // Converts to fahrenheit
 private float convertCelciusToFahrenheit(float celsius) {
  return ((celsius * 9) / 5) + 32;
 }
}
   

4.7. Start Project

To start the Android Application, select your project, right click on it, Run-As-> Android Application Be patient, the emulator starts up very slow. You should get the following result.


Type in a number, select your conversion and press the button. The result should be displayed and the other option should get selected.

4.8. Using the home menue

If you press the Home button you can also select your application.



Friday, August 13, 2010

Welcome to Android!



Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.

Features

  • Application framework enabling reuse and replacement of components
  • Dalvik virtual machine optimized for mobile devices
  • Integrated browser based on the open source WebKit engine
  • Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
  • SQLite for structured data storage
  • Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
  • GSM Telephony (hardware dependent)
  • Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
  • Camera, GPS, compass, and accelerometer (hardware dependent)
  • Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE
<

Android Architecture

The following diagram shows the major components of the Android operating system. Each section is described in more detail below.
Android System Architecture

Applications

Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.

Application Framework

By providing an open development platform, Android offers developers the ability to build extremely rich and innovative applications. Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more.
Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user.
Underlying all applications is a set of services and systems, including:
  • A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser
  • Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data
  • Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files
  • Notification Manager that enables all applications to display custom alerts in the status bar
  • An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack
For more details and a walkthrough of an application, see the Notepad Tutorial.

Libraries

Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below:
  • System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices
  • Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
  • Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications
  • LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view
  • SGL - the underlying 2D graphics engine
  • 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer
  • FreeType - bitmap and vector font rendering
  • SQLite - a powerful and lightweight relational database engine available to all applications

Android Runtime

Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.
Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.
The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.

Linux Kernel

Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.

Supported Development Environments:
  • Eclipse IDE


  • Other development environments or IDEs


    • JDK 5 or JDK 6 (JRE alone is not sufficient)
    • Apache Ant 1.6.5 or later for Linux and Mac, 1.7 or later for Windows
    • Not compatible with Gnu Compiler for Java (gcj)
\

How To Write Your First Google Android Application

The Android Market is taking off. In March, over 9,000 applications hit the Android market, doubling the amount added the previous month, impressing Android users everywhere. Given the huge amount of new Android phones coming out this year, it doesn’t seem like things are going to level off anytime soon.
Recently, Google announced that they are sending free Nexus One or Droid devices to developers with 3.5+ stars and 5,000+ downloads on their applications – making it that much more attractive to become a (good) Android developer.

Want to know how to write Google Android apps? Android applications are written in Java – a relatively easy to learn, friendly language for new developers. Aside from the possibility of a free Nexus One and some money, you could actually contribute to the Android community. If you’ve got innovative ideas and the drive to see them spread, the Android market is for you! Let’s get you started on your very first Android application.
Before we get to how to write Google Android apps – first, a bit of overview. Android apps (much like almost any mobile app) are developed on a computer – PC or Mac (generally) – and then compiled and sent to the device for testing. If you don’t have an Android device yet, there are emulators that simulate an Android device on your computer, meaning that you can still develop an Android game or application without owning one.

Step 1: Get Eclipse

For this tutorial, I’m going to use Eclipse, because frankly it’s the easiest and most hassle-free development tool for Android right now. If you’re a NetBeans programmer, be my guest; but I’ll use Eclipse today.
Note: This is a .zip file; when you unzip it you will be able to run it wherever you unpacked it – there is no installer. I’d recommend that you put this in “C:\Program Files\” unless you plan on making it a portable application on a USB drive or something.

Step 2: Download The Java JDK

If you don’t have it already, you need to download the Java JDK 6. If you currently have the JDK 5, you should be okay, but there’s really no reason not to update. Just install it by downloading and then running through the setup to get things going. I’d recommend that you just hit next–>next–>finish, rather than doing anything fancy. Once you get things working, you can mess around a bit.

Step 3: Download The Android SDK Tools

Next, you’ll need to get the Android SDK Tools straight from Google. Unpack and install this to a directory you’ll remember – you need to reference this in the next few steps.

Step 4: Configure Eclipse For Your Android

Start Eclipse, and head to ‘Help>Install New Software‘. Hit  “Add…” and for the name, type “Android” and set the link to “https://dl-ssl.google.com/android/eclipse/” (if this doesn’t work, try it with http:// instead of https://).Click “OK” and the following should appear.

Select both of the resulting packages, and hit next – this will download the Android ADT(Android Development Tools). Go ahead and start the download to obtain these two packages. Restart Eclipse (it should prompt you to on completion of the downloads). We’re almost ready to start coding.

Step 5: Configure The Android SDK

Navigate to the folder you downloaded/unpacked the Android SDK to. In there, you’ll find a file named “SDK Setup.exe.” Start that file – the following dialogue should appear.

Don’t feel obligated to download every single thing. Could it hurt? Not really. For me, however, I only really want to program for Android 2.1 and 2.01, so those are the only API packages I bothered to get (someday I may pay for my folly, but not today). Either way, get what you want (and you do need to pick one) and hit install. The SDK manager will install it for a little while – go grab a snack.

Step 6: Set Up Your Android Virtual Device (AVD)

Now that you’ve finished yet another painful download, click over to “virtual devices” (still in the SDK Manager). We’re going to create an Android device that will test run your programs for you! Hit “New” to create a new Android device, and put in the specifications that you want it to have. In the screenshot below, you’ll see the options I wanted (that closely mimic that of my Motorola Droid).

Click “Create AVD” to–well–create your AVD. Select your AVD from the list, and hit “Start” to make sure that you do indeed have a working emulation of an Android phone. After a pretty lengthy start-up wait, it should look something like this.

Fool around with it and explore for a bit if you want, then close it up so we can get back to work.

Step 7: Configure Eclipse Again

Remember that Android SDK we got earlier? We didn’t do anything with it. Now, it’s time to tell Eclipse where it is so Eclipse can use it as a resource. To do this, open Eclipse and navigate toWindow>Preferences (or on Mac, Eclipse>Preferences) and select the Android tab. As shown below, browse to the location of your Android SDK and hit “Apply“.

Everything check out so far? Hit “OK” to save everything and let’s go program.

Step 8: Create A New Project

It’s finally time to code some. Navigate to ‘File>New>Other…>Android>Android Project‘, and input a project name, as well as some other details. If you want, copy from my screenshot below. Some of the fields need explaining that simply doesn’t belong here, so if you want to know more specifically, please let me know and maybe I’ll write an article about it.

Hit “Finish” and the project will be created.

Step 9: Input Your Code

In the tree on the left, navigate to the “src” folder and expand everything. Go to the file with the name of your “Activity” (created in step 8, mine was HelloWorld) and double click it to see the contents. Presently, your code has all of the content in black (with some minor modifications depending on your settings). To make a working “Hello world” program, you need to add the text that is in bold red. Note that there are two bold red “blocks” of code, and you need to add both to make things work.
//==========Start Code============


package com.android.helloandroid;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       TextView tv = new TextView(this);
       tv.setText("Hello, Android");
       setContentView(tv);
   }
}

//==========End Code============
I would love to explain all of the code, but that’s not exactly the point of this tutorial; the point is to get your feet off the ground. I know some/most of this is confusing; but it’s just how things are wired.

Step 10: Run Your Program

Above your code, you’ll see a little green “Play” button (or navigate to ‘Run>Run‘). Click it.When a popup box asks you how to run the application, you’re going to tell it to run as an “Android Application”. It will prompt you to save changes; hit yes.
Now you get to wait an eternity while your virtual device boots up. I’d recommend that you leave it open for the duration of your programming sprees, otherwise you’re going to spend more time watching the Android logo spin than you will watching your program freeze up. Just saying. Efficiency.
After everything’s done loading, your application should upload and start automatically. Which means that right after you “unlock” the device, you’ll be greeted with your first Android program.I only captured the top half of the screen because the rest of it is black.

That’s it, congratulations! The task can be a bit daunting at first; and definitely confusing, but if you stick with it you won’t be disappointed. If you step back and think about it, we only did a few really major things, the rest was just the process of connecting the pieces to make everything work.
Do you want to become an Android developer? Have you ever written an Android app, and if so, what did it do? As always I love getting feedback in the comments section. As someone who answered yes to the first question, I’m in the process of learning to adequately code for my Android device, so do you have any websites or pointers that would help me or a fellow Android newbie out?