Robert Stevens Home

Android Programming Tips

By Robert John Stevens, CEO of WriteExpress Corporation


Creating an Android Activity

They make this as intuitive as mud so here are step-by-step instructions using Eclipse:

  1. Create a new Java class that inherits from Activity—Right click on your package name (e.g. com.Orabrush) > New > Class. Type in the name of your class (e.g. Foo). Click Browse to select a new Superclass. Start typing activity and select Activity - android.app. Click Finish.
    public class Foo extends Activity {
    	
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		// TODO Auto-generated method stub
    		super.onCreate(savedInstanceState);
    	}
    
    }
    
  2. Create an onCreate event handler— Put your cursor in your new Activity class. Press return twice to give yourself some space. Type onCreate and then Ctrl-Space. Select the first method (protected void onCreate(Bundle savedInstanceState) and press return.
  3. Create an XML file for the new Activity—Click the toolbar button Open a wizard to help create a new Android XML file. The name of the file must be lower case(e.g. foo.xml). Select a Resource Type (e.g. Layout). Select the root element (container) for the XML file (e.g. LinearLayout). Click Finish. Add whatever controls you wish to the new form
  4. Create a way to launch the new Activity—For example, drop a button onto the first form (Activity).
  5. Create a reference to your new buton
    	Button b = (Button)findViewById(R.id.button1);
    
  6. Create a new OnClickListener
            b.setOnClickListener(new OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				
    			}
    		});
    
  7. Call the startActivity method with an Intent object
    			@Override
    			public void onClick(View v) {
    				startActivity(new Intent(Main.this, Foo.class));
    				
    			}
    
  8. If you run it now it will crash—To find the problem, open the perspective DDMS. Scroll down to LogCat. You'll learn the Activity wasn't defined.
  9. Add the new Activity to the AndroidManifest.xml file
    	<activity android:name=".Foo" />
    
  10. In the new Activity Java file, set the ContentView to tell the second Activity which resource to use
    	setContentView(R.layout.foo);
    

Android Overview

Android runs on top of Linux. At the time of this writing it uses:

Each Android apps runs in a separate Linux process (in its own sandbox).

An app has components, a manifest file and resources.

Android components:

  1. Activities—An activity is a screen with a UI. Every screen has its own activity.
  2. Broadcast receivers—Components that respond to system-wide broadcast announcements (e.g. battery is low, photo is taken or screens turns off). Apps can become their own broadcast receivers. Broadcast receivers have no UI but can create status bar notifications that have UI.
  3. Content providers—Acessible to all apps, they provide read/write access to content via public URIs. Examples include Android media, contacts, etc.
  4. Services—Long-running processes that contain no UI.
  5. Android Manifest File—Every app as a AndroidManifest.xml file at its root. It includes configuration, components, permissions (access to hardware, etc.). It also defines the minimum API level to run the application.

Android Versions


Android Animation

Android animation is very slow on the emulator. Try it on your external devide.

Setting up an android animation is not obvious but doesn't require a lot of code.

There are several ways to create animations:

Tween animation—Use this to animate a single image. Give Android the start and end values and it calculates the animation frames inbetween.

See the code example in Android docs for tweened animation on Views.


Frame by frame images
1. Drag your images into the res/drawable-hdpi folder.
2. Double click the main.xml file.
3. You could change the XML layout to a RelativeLayout to make it easy to center controls.
4. Drag an ImageView onto your dialog.
5. You could set the gravity of the control to Center.
6. Create a new Android XML file. Check the Animation radio button.
7. Write the following code. Notice the references below to each animation image. The duration is in milliseconds.

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas/android.com/apk/res/android">
    <item android:drawable="@drawable/animation_001" android:duration="30" />
    <item android:drawable="@drawable/animation_002" android:duration="30" />
    <item android:drawable="@drawable/animation_003" android:duration="30" />
    <item android:drawable="@drawable/animation_004" android:duration="30" />
    <item android:drawable="@drawable/animation_005" android:duration="30" />
</animation-list>

8. Link the XML to your ImageView control. In your Java file, get a reference to the ImageView:

    ImageView iv = (ImageView)findViewById(R.id.imageView1);

9. Set the background resource to set the background for the image.

    ImageView iv = (ImageView)findViewById(R.id.imageView1);
    iv.setBackgroundResource(R.anim.animation);

10. Start the animation. If you want to do it when clicked, create an OnClick event.

    iv.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
        }

11. Import the class. Right click and select Import 'OnClickListener' (android.view.View)

12. When the OnClick event is fired, create a new instance of the animation drawable class.

    iv.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            AnimationDrawable anim = (AnimationDrawable) iv.getBackground();
        }

13. Right click on the iv above and select Change the modifier of 'iv' to final. Help—anyone know why?

14. Start the animation

    iv.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            AnimationDrawable anim = (AnimationDrawable) iv.getBackground();
            anim.start();
        }

15. To change the animation to only run once, set the oneshot property

<?xml version="1.0" encoding="utf-8"?>
<animation-list android:oneshot="true" xmlns:android="http://schemas/android.com/apk/res/android">

Android Gradient Buttons

This code example shows you how to create a scalable, vector-based Android button. The code is copied from the Android Documentation at Android Drawable Resources

1. Create a button.

2. Create a new XML file in the res/drawable-hdpi folder (right click on the folder and select New File)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFF0000"
        android:endColor="#80FF00FF"
        android:angle="45"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

3. Apply the XML file to the button.
Click the button. Right-click to bring up its Properties. Set the Button Background property to Drawable > rect.

This lets you draw the button using the XML drawing API.


Android Audio

With the Android MediaPlayer you can easily play audio.

1. Create a folder under the res folder to place your audio file(s). The folder name is usually named raw (eg. res/raw

2. Play the audio.

MediaPlayer mp = MediaPlayer.create(YourClass.this, R.raw.myAudioFile);
mp.start();

3. Release and nullify your Media Player:

mp.release();
mp = null;

4. If your activity receives a call to onStop(), you must release the MediaPlayer

From the official MediaPlayer documentation, "As you may know, when the user changes the screen orientation (or changes the device configuration in another way), the system handles that by restarting the activity (by default), so you might quickly consume all of the system resources as the user rotates the device back and forth between portrait and landscape, because at each orientation change, you create a new MediaPlayer that you never release."

5. Ensure you have permission to play audio. There is only one audio output and there may be several media services competing for its use, so you must first request audio focus.

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
    AudioManager.AUDIOFOCUS_GAIN);

if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    // could not get audio focus.
}

6. Handle focusChange events. See the MediaPlayer documentation

7. Release the MediaPlayer when being shut down and when not in use.

    if (mp != null)
    {
        mp.release();
        mp = null;
    }

Android Debugging

To debug, open the Manifest.xml file. Click the Application tab on the bottom of Eclipse. Set Debuggable to true. This will connect the debugger to your app in Eclipse.

Use the Log class in the android.util package


Android Definitions


FAQ

Q. How do you set the starting activity?

A. In the AndroidManifest.xml file, change this line to reference your activity:

Q. How do you create a new activity?

Q. How do I get the Eclipse/Java code completion to work?

A. Start typing a method name and click Ctrl-Space

Q. How do I make a new XML file for an Activity?

A. Click the toolbar button that "Opens a wizard to create a new Android XML File. The filename has to be lowercase.

Q. How do you clean up the XML?

A. Right click. Source > Cleanup Document

Q. When I have an error, how do I show the Quick Fix menu?

A. Ctrl-1 (Windows) or Command-1 (Mac).

Q. How do I respond to a crash?

A. Change to the Other > DDMS perspective. Scroll down to LogCat to see the error messages.

A. You want to duplicate your .java and .xml file. Right click on your package in Package Explorer (e.g. com.Orabrush) and select New > Class. Name our class. To extend or derive from the activity class, Click Browse. Enter activity in the text box.

Q. How do you get a reference to a widget?

A. Use findViewById and make sure you cast it.

Q. Why doesn't my app show my activity?

A. All activities have to be defined in the AndroidManifest.xml file

EditText et = (EditText) findViewById(R.id.editText1);

Q. How do I see the API Controls?

A. Using the Android Emulator, click the App Drawer (the 4x4 dotted icon on the middle bottom), and then click API Demos


Q. Where is the Android OS Source Code?

A. http://android.git.kernal.org/


Q. How do I view the Android framework classes?

A. Browse the source code and go to platform/frameworks/base.git. Click tree to see the packages.


Q. How do I view the code for the Android Styles?

A. Browse the source code and go to platform/frameworks/base.git > tree > res > values > styles.xml


Android Button Controls

There are two ways to create button listeners:

1. For one or two buttons:

Button b = (Button) findViewById(R.id.button1);
b.SetOnClickListener(new OnClickListener);

2. For many buttons, implement the OnClickListener

public class Main extends Activity implements OnClickListener {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button b = (Button) findViewById(R.id.button1);
    b.SetOnClickListener(this); // This will call the onClickView method below

    ImageButton ib = (Button) findViewById(R.id.imageButton1);
    b.SetOnClickListener(this);

}

@Override
public void onClick(View v) { //This creates a listener for all buttons
    if (R.id.button1 == v.getId()) {
        Log.d("Me", "Clicked the button");
    }
}

Android Documentation


Icons

You will need icons for your Android App. For the Android Market you'll need a 512x512 icon. Read the Android Launcher Icons Guidelines. Go to the Android Icons page and download their official Android Icon Photoshop Templates.

Make sure you save out different sizes using Photoshop's Save for the Web feature as a PNG-24 with transparency on, and save them in project folders drawable-hdpi (size 512x512), drawable-mdpi (size 48x48), and drawable-ldpi (size 36x36).

If you want to rename your icon, change its name in the AndroidManifest.xml file.

You could just have one 512x512 large icon and Android will scale it down for the smaller icons but that requires more processing and may result in not-so-pretty icons.

See also: Android Icon Design Guidelines


Android Layouts


List Controls

1. Create a list in an xml file

<resources>
    <string-array name="colors">
        <item name="red">Red</item>
        <item name="white">White</item>
        <item name="blue">Blue</item>
    </string-array>
</resources>

2. extend your class

public class Main extends ListActivity {

3. To add a ListView control, expand Composite on the left side and drag the control onto your palette.

4. Give the ListView a specific id like "@android:id/list"

5. To get the data into the ListView, set the ListAdapter (a component that takes data and adapts it for display).

setListAdapter(new ArrayAdapter(new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1,
    getResoures().getStringArray(R.array.colors)));
)

You could also have read the list into a string array:

String[] items = getResoures().getStringArray(R.array.colors);
 

Multiple Screen Support

From the Android SDK:

For example, the following is a list of resource directories in an application that provides different layout designs for different screen sizes and different bitmap drawables for medium, high, and extra high density screens.

res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

res/drawable-mdpi/my_icon.png        // bitmap for medium density
res/drawable-hdpi/my_icon.png        // bitmap for high density
res/drawable-xhdpi/my_icon.png       // bitmap for extra high density

See the section Best Practices at: Supporting Multiple Screens

Android Resources

The resource system takes a little getting used to but is very powerful when targeting different devices and languages.


Android Security

If you want your app to access certain things, you'll need permission.

ConnectivityManager conman = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

Selling Android Apps

Introducing Google Play.


Android Styles

Q. How do I create a style file?

A.

1. In Eclipse, click the button to create a New Android XML File > name your file (e.g. styles.xml), click the Values radio button > click Finish. The file will be put under the values folder.

2. Open the file in the editor. You'll want to extend each style from an existing control by setting the parent property.

<style name="MyStyle" parent="@android:style/TextAppearance">
    <item name="android:textSize">30sp</item>
    <item name="android:textColor">#FF0000</item>
    <item name="android:typeface">monospace</item>
</style>

4. Click a control. Click the Properties tab, then click Style and select your style.


Q. How do I subclass a style file?

A. Using the code above, create a new style and modify the name like this:

    <style name="MyStyle.MySubclassStyle">
            <item name="android:textSize">20sp</item>
    </style>

See also the official Android Styles and Themes documentation.


Android Text Controls


Android Themes

Android ships with many built-in themes.
1. Choose a theme from the Theme pull-down menu in Eclipse.
2. Modify the AndroidManifest.xml file to set or apply the theme. You can set the theme at the application or activity level. Use the names for the built in themes as shown on the theme pull-down menu. For example to use the built-in dialog theme:

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.Dialog">

Q. How do I override or extend a theme?

A. Create a style that overrides the theme:
1. Create a new Android XML File (e.g. styles.xml) and click the Values checkbox, and then click the Finish button.
2. Create a style block with the parent attribute set to your theme and a name for your custom theme, then override the properties you wish. For example:

<resources>
    <style parent="@android:style/Theme.Dialog" name="myCustomTheme">
        <item name="@android:textColor">#00FF00</item>
    </style>
</resources>

3. Set your custom theme in the AndroidManifest.xml file:

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/myCustomTheme">

See also the official Android Styles and Themes documentation.


Android Toast Notifications

A toast notification is an Android popup window that appears, stays for a specified duration and then disappears.

See also the official


Android Tools


Android Units


Samples and Notes of Interest to me



Copyright © 2012 Robert Stevens. All rights reserved.

This article was commenced on March 20, 2012. Last update: May 21, 2012.


Top Related Searches