Android: How to Stop Media Player play when Home button is pressed


Here is the solution, tested and verified

@Override
protected void onPause() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
                        }
}

Image Switcher with example and Source code

The ImageSwitcher methods give you a simple way to add animated transitions .ImageSwitcher are used to have an smooth transition animation in android view. Imagine you need to cycle through information  in an ImageView.  Some examples of this would be
  • Displaying ABCD letter images
  • Displaying fruits in sequence
  • Display House construction images
  • etc
Main Activity: ImageSwitcherExampleActivity.java
package com.successmobigroup.imageswitcherexample;


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.widget.Button;

import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
import com.successmobigroup.imageswitcherexample.R;

public class ImageSwitcherExampleActivity extends Activity implements ViewFactory{
  ImageSwitcher is;
  int [] imgid = {R.drawable.android1,R.drawable.android2,R.drawable.android3,R.drawable.android4};
  Button prev, next;
  int count =0;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_image_switcher_example);
  
  is = (ImageSwitcher)findViewById(R.id.imageSwitcher1);
  prev = (Button)findViewById(R.id.button1);
  next = (Button)findViewById(R.id.button2);
  is.setFactory(this);
  is.setInAnimation(this, android.R.anim . slide_in_left);
  is.setOutAnimation(this, android.R.anim.slide_out_right);
 
  prev.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
     if(count>0)
     {
      count--;
      try{
        is.setImageResource(imgid[count]);
       }
      catch(Exception e)
      {
       e.printStackTrace();
      }
     }
     else
     {
      Toast.makeText(ImageSwitcherExampleActivity.this, "First", Toast.LENGTH_LONG).show();
     }
   }
  });
  next.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    if(count<imgid.length)
    {
     
         
     try{
      is.setImageResource(imgid[count]);
     }
    catch(Exception e)
    {
     e.printStackTrace();
    }
     count++;
     
    }
    else
    {
     Toast.makeText(ImageSwitcherExampleActivity.this, "Last", Toast.LENGTH_LONG).show();
    }
   }
  });
  
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.image_switcher_example, menu);
  return true;
 }

 @Override
 public View makeView() {
  // TODO Auto-generated method stub
  ImageView iv = new ImageView(this);
  iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
  iv.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
  
  return iv;
 }

}
Layout xml: activity_image_switcher_example.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".ImageSwitcherExampleActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical" >

        <ImageSwitcher
            android:id="@+id/imageSwitcher1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </ImageSwitcher>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="&lt;&lt;" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text=">>" />

    </LinearLayout>

</LinearLayout>

Download source Complete source code here:

(right click save as)

Steps to Open Source in Eclipse:

1.Download Zip from above link
2.Locate the ZIP and extract
3.In Eclipse
  File-->Import-->Existing Android Code Into Workspace-->Browse
4.Locate file and say next
5.Done, You will find folder in your workspace

Screen Shots:





android missing contentdescription attribute on image

How to get rid of this error ????



Simple solution:
-------------------

Add this 
android:contentDescription="@null"

Text Switcher Example with Swipe

TextSwitcher is a UI control in android which can be used to show images using gestures and animations. In this tutorial, we shall see how to use the TextSwitcher control using example.
1. Adding the control
2. Adding animations
3. Adding gesture listener
4. Binding gesture detector
5. Download Code

Adding the control

If you are using the XML layout editor, then the TextSwitcher control is present in the “Transitions” category. You can simply drag and drop it to the layout and configure its attributes.
On the other hand, if you are writing the layout xml on your own, the following sample xml should help in setting up a basic TextSwitcher android UI element.

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

    <TextSwitcher
        android:id="@+id/textSwitcher1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </TextSwitcher>

</LinearLayout>   


The above code shall be present in the activity_main.xml file which is the layout file for our MainActivity in the sample application.

Adding animations

When users will switch images using gestures (horizontal swipe), you can add animation effect to show the user that the previous image has gone left and new image has come from the right hand side. You can also use fade out/fade in effects. The code for adding these animation effects to TextSwitcher control is:
tv = (TextSwitcher) findViewById(R.id.textSwitcher1);
tv.setInAnimation(AnimationUtils.loadAnimation(this,
 android.R.anim.fade_in));
tv.setOutAnimation(AnimationUtils.loadAnimation(this,
 android.R.anim.fade_out));

Adding gesture listener

A gesture listener is an interface which sends events when the user uses his fingers to swipe horizontal or vertical. Basically, you get the horizontal/vertical velocity, swipe distance and location of start/end of swipe. The following source code should be easy to understand where a new GestureListener has been created:
class MyGestureDetector extends SimpleOnGestureListener {

  final String TAG = MyGestureDetector.class.getSimpleName();

  // for touch left or touch right events
  private static final int SWIPE_MIN_DISTANCE = 80;   //default is 120
  private static final int SWIPE_MAX_OFF_PATH = 400;
  private static final int SWIPE_THRESHOLD_VELOCITY = 70;

  @Override
  public boolean onSingleTapConfirmed(MotionEvent e) {
 return super.onSingleTapConfirmed(e);
  }

  @Override
  public boolean onDown(MotionEvent e) {
 return true;
  }

  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
 Log.d(TAG, " on filing event, first velocityX :" + velocityX +
 " second velocityY" + velocityY);
 try {
   if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
     return false;
     if(e1.getX() - e2.getX() 
                      > SWIPE_MIN_DISTANCE && Math.abs(velocityX) 
                      > SWIPE_THRESHOLD_VELOCITY) {
       onHorizonTouch(true);  // left
   }  else if (e2.getX() - e1.getX() 
                      > SWIPE_MIN_DISTANCE && Math.abs(velocityX) 
                      > SWIPE_THRESHOLD_VELOCITY) {
       onHorizonTouch(false); // right
     }
 } catch (Exception e) {
  // nothing
 }
 return false;
  }

  void onHorizonTouch(Boolean toLeft) {
 if(!toLeft && imageIdx>0) {
                        tv.setInAnimation(AnimationUtils.loadAnimation(
   MainActivity.this, android.R.anim.fade_in));
   tv.setOutAnimation(AnimationUtils.loadAnimation(
   MainActivity.this, android.R.anim.fade_out));
   imageIdx--;
   MainActivity.this.tv.setText("Text1");
 }
 if(toLeft && imageIdx<1) {
   vs.setInAnimation(AnimationUtils.loadAnimation(
   MainActivity.this, android.R.anim.fade_in));
   vs.setOutAnimation(AnimationUtils.loadAnimation(
   MainActivity.this, android.R.anim.fade_out));
   imageIdx++;
   MainActivity.this.tv.setText("Text2");
 }
  }
}
In the above code, we are playing between two images only, but you can add more images and change the condition on imageIdx accordingly. Note that MyGestureDetector is a method local inner class.

Binding gesture detector

Binding the gesture detector to TextSwitcher is again a piece of cake as shown in the following lines of code:
  gestureDetector = new GestureDetector(new MyGestureDetector());
  View.OnTouchListener gestureListener = new View.OnTouchListener() {

   @Override
   public boolean onTouch(View v, MotionEvent event) {
    if (gestureDetector.onTouchEvent(event)) {
     return true;
    }
    return false;
   }
  };
  tv.setOnTouchListener(gestureListener);

Screen Shot:


Download Source Code

Download Source Here

Build your first android app

Building Your First App


DEPENDENCIES AND PREREQUISITES

Welcome to Android application development!
This class teaches you how to build your first Android app. You’ll learn how to create an Android project and run a debuggable version of the app. You'll also learn some fundamentals of Android app design, including how to build a simple user interface and handle user input.
Before you start this class, be sure you have your development environment set up. You need to:
  1. Download the Android SDK.
  2. Install the ADT plugin for Eclipse (if you’ll use the Eclipse IDE).
  3. Download the latest SDK tools and platforms using the SDK Manager.
Note: Make sure you install the most recent versions of the ADT plugin and the Android SDK before you start this class. The procedures described in this class may not apply to earlier versions.
If you haven't already done these tasks, start by downloading the Android SDK and following the install steps. Once you've finished the setup, you're ready to begin this class.
This class uses a tutorial format that incrementally builds a small Android app that teaches you some fundamental concepts about Android development, so it's important that you follow each step.

Creating an Android Project

An Android project contains all the files that comprise the source code for your Android app. The Android SDK tools make it easy to start a new Android project with a set of default project directories and files.
This lesson shows how to create a new project either using Eclipse (with the ADT plugin) or using the SDK tools from a command line.
Note: You should already have the Android SDK installed, and if you're using Eclipse, you should also have the ADT plugininstalled (version 22.6.2 or higher). If you don't have these, follow the guide to Installing the Android SDK before you start this lesson.

Create a Project with Eclipse


  1. Click New  in the toolbar.
  2. In the window that appears, open the Android folder, select Android Application Project, and click Next.
  3. Figure 1. The New Android App Project wizard in Eclipse.
  4. Fill in the form that appears:
    • Application Name is the app name that appears to users. For this project, use "My First App."
    • Project Name is the name of your project directory and the name visible in Eclipse.
    • Package Name is the package namespace for your app (following the same rules as packages in the Java programming language). Your package name must be unique across all packages installed on the Android system. For this reason, it's generally best if you use a name that begins with the reverse domain name of your organization or publisher entity. For this project, you can use something like "com.example.myfirstapp." However, you cannot publish your app on Google Play using the "com.example" namespace.
    • Minimum Required SDK is the lowest version of Android that your app supports, indicated using the API level. To support as many devices as possible, you should set this to the lowest version available that allows your app to provide its core feature set. If any feature of your app is possible only on newer versions of Android and it's not critical to the app's core feature set, you can enable the feature only when running on the versions that support it (as discussed in Supporting Different Platform Versions). Leave this set to the default value for this project.
    • Target SDK indicates the highest version of Android (also using the API level) with which you have tested with your application.
      As new versions of Android become available, you should test your app on the new version and update this value to match the latest API level in order to take advantage of new platform features.
    • Compile With is the platform version against which you will compile your app. By default, this is set to the latest version of Android available in your SDK. (It should be Android 4.1 or greater; if you don't have such a version available, you must install one using the SDK Manager). You can still build your app to support older versions, but setting the build target to the latest version allows you to enable new features and optimize your app for a great user experience on the latest devices.
    • Theme specifies the Android UI style to apply for your app. You can leave this alone.
    Click Next.
  5. On the next screen to configure the project, leave the default selections and click Next.
  6. The next screen can help you create a launcher icon for your app.
    You can customize an icon in several ways and the tool generates an icon for all screen densities. Before you publish your app, you should be sure your icon meets the specifications defined in the Iconographydesign guide.
    Click Next.
  7. Now you can select an activity template from which to begin building your app.
    For this project, select BlankActivity and click Next.
  8. Leave all the details for the activity in their default state and click Finish.
Your Android project is now a basic "Hello World" app that contains some default files. To run the app, continue to the next lesson.

Create a Project with Command Line Tools


If you're not using the Eclipse IDE with the ADT plugin, you can instead create your project using the SDK tools from a command line:
  1. Change directories into the Android SDK’s tools/ path.
  2. Execute:
    android list targets
    This prints a list of the available Android platforms that you’ve downloaded for your SDK. Find the platform against which you want to compile your app. Make a note of the target id. We recommend that you select the highest version possible. You can still build your app to support older versions, but setting the build target to the latest version allows you to optimize your app for the latest devices.
    If you don't see any targets listed, you need to install some using the Android SDK Manager tool. See Adding Platforms and Packages.
  3. Execute:
    android create project --target <target-id> --name MyFirstApp \
    --path <path-to-workspace>/MyFirstApp --activity MainActivity \
    --package com.example.myfirstapp
    
    Replace <target-id> with an id from the list of targets (from the previous step) and replace <path-to-workspace> with the location in which you want to save your Android projects.
Your Android project is now a basic "Hello World" app that contains some default files. To run the app, continue to the next lesson.
Tip: Add the platform-tools/ as well as the tools/ directory to your PATH environment variable.

Running Your App

If you followed the previous lesson to create an Android project, it includes a default set of "Hello World" source files that allow you to immediately run the app.
How you run your app depends on two things: whether you have a real Android-powered device and whether you're using Eclipse. This lesson shows you how to install and run your app on a real device and on the Android emulator, and in both cases with either Eclipse or the command line tools.
Before you run your app, you should be aware of a few directories and files in the Android project:
AndroidManifest.xml
The manifest file describes the fundamental characteristics of the app and defines each of its components. You'll learn about various declarations in this file as you read more training classes.
One of the most important elements your manifest should include is the <uses-sdk> element. This declares your app's compatibility with different Android versions using the android:minSdkVersion andandroid:targetSdkVersion attributes. For your first app, it should look like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ... >
    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" />
    ...</manifest>
You should always set the android:targetSdkVersion as high as possible and test your app on the corresponding platform version. For more information, read Supporting Different Platform Versions.
src/
Directory for your app's main source files. By default, it includes an Activity class that runs when your app is launched using the app icon.
res/
Contains several sub-directories for app resources. Here are just a few:
drawable-hdpi/
Directory for drawable objects (such as bitmaps) that are designed for high-density (hdpi) screens. Other drawable directories contain assets designed for other screen densities.
layout/
Directory for files that define your app's user interface.
values/
Directory for other various XML files that contain a collection of resources, such as string and color definitions.
When you build and run the default Android app, the default Activity class starts and loads a layout file that says "Hello World." The result is nothing exciting, but it's important that you understand how to run your app before you start developing.

Run on a Real Device


If you have a real Android-powered device, here's how you can install and run your app:
  1. Plug in your device to your development machine with a USB cable. If you're developing on Windows, you might need to install the appropriate USB driver for your device. For help installing drivers, see the OEM USB Drivers document.
  2. Enable USB debugging on your device.
    • On most devices running Android 3.2 or older, you can find the option under Settings > Applications > Development.
    • On Android 4.0 and newer, it's in Settings > Developer options.
      Note: On Android 4.2 and newer, Developer options is hidden by default. To make it available, go toSettings > About phone and tap Build number seven times. Return to the previous screen to findDeveloper options.
To run the app from Eclipse:
  1. Open one of your project's files and click Run  from the toolbar.
  2. In the Run as window that appears, select Android Application and click OK.
Eclipse installs the app on your connected device and starts it.
Or to run your app from a command line:
  1. Change directories to the root of your Android project and execute:
    ant debug
  2. Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute:
    adb install bin/MyFirstApp-debug.apk
  3. On your device, locate MyFirstActivity and open it.
That's how you build and run your Android app on a device! To start developing, continue to the next lesson.

Run on the Emulator


Whether you're using Eclipse or the command line, to run your app on the emulator you need to first create anAndroid Virtual Device (AVD). An AVD is a device configuration for the Android emulator that allows you to model different devices.
Figure 1. The AVD Manager showing a few virtual devices.
To create an AVD:
  1. Launch the Android Virtual Device Manager:
    1. In Eclipse, click Android Virtual Device Manager from the toolbar.
    2. From the command line, change directories to<sdk>/tools/ and execute:
      android avd
  2. In the Android Virtual Device Manager panel, click New.
  3. Fill in the details for the AVD. Give it a name, a platform target, an SD card size, and a skin (HVGA is default).
  4. Click Create AVD.
  5. Select the new AVD from the Android Virtual Device Manager and click Start.
  6. After the emulator boots up, unlock the emulator screen.
To run the app from Eclipse:
  1. Open one of your project's files and click Run  from the toolbar.
  2. In the Run as window that appears, select Android Application and click OK.
Eclipse installs the app on your AVD and starts it.
Or to run your app from the command line:
  1. Change directories to the root of your Android project and execute:
    ant debug
  2. Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute:
    adb install bin/MyFirstApp-debug.apk
  3. On the emulator, locate MyFirstActivity and open it.