Friday, May 4, 2012

Set the title of Download on notification, setTitle()


Set the title of Download on notification, setTitle()

The method setTitle() of Request can be used to set the title of this download, to be displayed innotifications (if enabled).

Set the title of Download on notification, setTitle()

For API level 11 or higher, you can also control whether a system notification is posted by thedownload manager while this download is running or when it is completed, by calling setNotificationVisibility().

Continuous from last exercise "Restrict the types of networks over which DownloadManager may proceed".

package com.exercise.AndroidDownloadManager;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class AndroidDownloadManagerActivity extends Activity {
 
 final String DOWNLOAD_FILE = "http://goo.gl/w3XV3";

 final String strPref_Download_ID = "PREF_DOWNLOAD_ID";
 
 SharedPreferences preferenceManager;
 DownloadManager downloadManager;
 
 ImageView image;
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
      
       preferenceManager
        = PreferenceManager.getDefaultSharedPreferences(this);
       downloadManager
        = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
      
       Button btnStartDownload = (Button)findViewById(R.id.startdownload);
       btnStartDownload.setOnClickListener(btnStartDownloadOnClickListener);
      
       image = (ImageView)findViewById(R.id.image);
   }
  
   Button.OnClickListener btnStartDownloadOnClickListener
   = new Button.OnClickListener(){

  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
   
   Uri downloadUri = Uri.parse(DOWNLOAD_FILE);
   DownloadManager.Request request = new DownloadManager.Request(downloadUri);
   
   /*
    *  request.setAllowedNetworkTypes()-
    *  Restrict the types of networks over which this download may proceed.
    *  By default, all network types are allowed.
    *  - Request.NETWORK_WIFI
    *  - Request.NETWORK_MOBILE
    *  - Request.NETWORK_WIFI | Request.NETWORK_MOBILE
    * 
    *  request.setAllowedOverRoaming(false) -
    *  Set whether this download may proceed over a roaming connection.
    *  By default, roaming is allowed.
    */
   request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
   request.setAllowedOverRoaming(false);
   
   
   /*
    *  Set Title of Download
    */
   request.setTitle("Android-er Download!");
   
   /*
    *  (for API 11 or higher!)
    *  Display Download in Notification
    */
   //request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
     
   long id = downloadManager.enqueue(request);
   
   //Save the request id
   Editor PrefEdit = preferenceManager.edit();
   PrefEdit.putLong(strPref_Download_ID, id);
   PrefEdit.commit();

  }};

 @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  
  CheckDwnloadStatus();

  IntentFilter intentFilter
   = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
  registerReceiver(downloadReceiver, intentFilter);
 }

 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  unregisterReceiver(downloadReceiver);
 }
  
 private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

  @Override
  public void onReceive(Context arg0, Intent arg1) {
   // TODO Auto-generated method stub
   CheckDwnloadStatus();
  } 
 };
 
 private void CheckDwnloadStatus(){

  // TODO Auto-generated method stub
  DownloadManager.Query query = new DownloadManager.Query();
  long id = preferenceManager.getLong(strPref_Download_ID, 0);
  query.setFilterById(id);
  Cursor cursor = downloadManager.query(query);
  if(cursor.moveToFirst()){
   int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
   int status = cursor.getInt(columnIndex);
   int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
   int reason = cursor.getInt(columnReason);
   
   switch(status){
   case DownloadManager.STATUS_FAILED:
    String failedReason = "";
    switch(reason){
    case DownloadManager.ERROR_CANNOT_RESUME:
     failedReason = "ERROR_CANNOT_RESUME";
     break;
    case DownloadManager.ERROR_DEVICE_NOT_FOUND:
     failedReason = "ERROR_DEVICE_NOT_FOUND";
     break;
    case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
     failedReason = "ERROR_FILE_ALREADY_EXISTS";
     break;
    case DownloadManager.ERROR_FILE_ERROR:
     failedReason = "ERROR_FILE_ERROR";
     break;
    case DownloadManager.ERROR_HTTP_DATA_ERROR:
     failedReason = "ERROR_HTTP_DATA_ERROR";
     break;
    case DownloadManager.ERROR_INSUFFICIENT_SPACE:
     failedReason = "ERROR_INSUFFICIENT_SPACE";
     break;
    case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
     failedReason = "ERROR_TOO_MANY_REDIRECTS";
     break;
    case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
     failedReason = "ERROR_UNHANDLED_HTTP_CODE";
     break;
    case DownloadManager.ERROR_UNKNOWN:
     failedReason = "ERROR_UNKNOWN";
     break;
    }

    Toast.makeText(AndroidDownloadManagerActivity.this,
      "FAILED: " + failedReason,
      Toast.LENGTH_LONG).show();
    break;
   case DownloadManager.STATUS_PAUSED:
    String pausedReason = "";
    
    switch(reason){
    case DownloadManager.PAUSED_QUEUED_FOR_WIFI:
     pausedReason = "PAUSED_QUEUED_FOR_WIFI";
     break;
    case DownloadManager.PAUSED_UNKNOWN:
     pausedReason = "PAUSED_UNKNOWN";
     break;
    case DownloadManager.PAUSED_WAITING_FOR_NETWORK:
     pausedReason = "PAUSED_WAITING_FOR_NETWORK";
     break;
    case DownloadManager.PAUSED_WAITING_TO_RETRY:
     pausedReason = "PAUSED_WAITING_TO_RETRY";
     break;
    }
    
    Toast.makeText(AndroidDownloadManagerActivity.this,
      "PAUSED: " + pausedReason,
      Toast.LENGTH_LONG).show();
    break;
   case DownloadManager.STATUS_PENDING:
    Toast.makeText(AndroidDownloadManagerActivity.this,
      "PENDING",
      Toast.LENGTH_LONG).show();
    break;
   case DownloadManager.STATUS_RUNNING:
    Toast.makeText(AndroidDownloadManagerActivity.this,
      "RUNNING",
      Toast.LENGTH_LONG).show();
    break;
   case DownloadManager.STATUS_SUCCESSFUL:
    
    Toast.makeText(AndroidDownloadManagerActivity.this,
      "SUCCESSFUL",
      Toast.LENGTH_LONG).show();
    GetFile();
    break;
   } 
  } 
 }
 
 private void GetFile(){
  //Retrieve the saved request id
  long downloadID = preferenceManager.getLong(strPref_Download_ID, 0);
  
  ParcelFileDescriptor file;
  try {
   file = downloadManager.openDownloadedFile(downloadID);
   FileInputStream fileInputStream
    = new ParcelFileDescriptor.AutoCloseInputStream(file);
   Bitmap bm = BitmapFactory.decodeStream(fileInputStream);
   image.setImageBitmap(bm);
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
 }
}

Cancel/remove download from DownloadManager.


Cancel/remove download from DownloadManager.

In the last exercise, "Set the title of Download on notification, setTitle()", The download query will be alway here after started, even close you app. Such that you always see the Toast of the status(such as "SUCCESSFUL") when you app start. So you have to call remove() method to clear thedownload, or if you want to stop it before finished.

package com.exercise.AndroidDownloadManager;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class AndroidDownloadManagerActivity extends Activity {
 
 final String DOWNLOAD_FILE = "http://goo.gl/w3XV3";

 final String strPref_Download_ID = "PREF_DOWNLOAD_ID";
 
 SharedPreferences preferenceManager;
 DownloadManager downloadManager;
 
 ImageView image;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        preferenceManager 
         = PreferenceManager.getDefaultSharedPreferences(this);
        downloadManager 
         = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        
        Button btnStartDownload = (Button)findViewById(R.id.startdownload);
        btnStartDownload.setOnClickListener(btnStartDownloadOnClickListener);
        
        image = (ImageView)findViewById(R.id.image);
    }
    
    Button.OnClickListener btnStartDownloadOnClickListener
    = new Button.OnClickListener(){

  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
   
   Uri downloadUri = Uri.parse(DOWNLOAD_FILE);
   DownloadManager.Request request = new DownloadManager.Request(downloadUri);
   
   /*
    *  request.setAllowedNetworkTypes()-
    *  Restrict the types of networks over which this download may proceed. 
    *  By default, all network types are allowed.
    *  - Request.NETWORK_WIFI
    *  - Request.NETWORK_MOBILE
    *  - Request.NETWORK_WIFI | Request.NETWORK_MOBILE
    *  
    *  request.setAllowedOverRoaming(false) -
    *  Set whether this download may proceed over a roaming connection. 
    *  By default, roaming is allowed.
    */
   request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
   request.setAllowedOverRoaming(false);
   
   
   /*
    *  Set Title of Download
    */
   request.setTitle("Android-er Download!");
   
   /*
    *  (for API 11 or higher!)
    *  Display Download in Notification
    */
   //request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
     
   long id = downloadManager.enqueue(request);
   
   //Save the request id
   Editor PrefEdit = preferenceManager.edit();
   PrefEdit.putLong(strPref_Download_ID, id);
   PrefEdit.commit();

  }};

 @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  
  CheckDwnloadStatus();

  IntentFilter intentFilter 
   = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
  registerReceiver(downloadReceiver, intentFilter);
 }

 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  unregisterReceiver(downloadReceiver);
 }
  
 private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

  @Override
  public void onReceive(Context arg0, Intent arg1) {
   // TODO Auto-generated method stub
   CheckDwnloadStatus();
  } 
 };
 
 private void CheckDwnloadStatus(){

  // TODO Auto-generated method stub
  DownloadManager.Query query = new DownloadManager.Query();
  long id = preferenceManager.getLong(strPref_Download_ID, 0);
  query.setFilterById(id);
  Cursor cursor = downloadManager.query(query);
  if(cursor.moveToFirst()){
   int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
   int status = cursor.getInt(columnIndex);
   int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
   int reason = cursor.getInt(columnReason);
   
   switch(status){
   case DownloadManager.STATUS_FAILED:
    String failedReason = "";
    switch(reason){
    case DownloadManager.ERROR_CANNOT_RESUME:
     failedReason = "ERROR_CANNOT_RESUME";
     break;
    case DownloadManager.ERROR_DEVICE_NOT_FOUND:
     failedReason = "ERROR_DEVICE_NOT_FOUND";
     break;
    case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
     failedReason = "ERROR_FILE_ALREADY_EXISTS";
     break;
    case DownloadManager.ERROR_FILE_ERROR:
     failedReason = "ERROR_FILE_ERROR";
     break;
    case DownloadManager.ERROR_HTTP_DATA_ERROR:
     failedReason = "ERROR_HTTP_DATA_ERROR";
     break;
    case DownloadManager.ERROR_INSUFFICIENT_SPACE:
     failedReason = "ERROR_INSUFFICIENT_SPACE";
     break;
    case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
     failedReason = "ERROR_TOO_MANY_REDIRECTS";
     break;
    case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
     failedReason = "ERROR_UNHANDLED_HTTP_CODE";
     break;
    case DownloadManager.ERROR_UNKNOWN:
     failedReason = "ERROR_UNKNOWN";
     break;
    }

    Toast.makeText(AndroidDownloadManagerActivity.this, 
      "FAILED: " + failedReason, 
      Toast.LENGTH_LONG).show();
    break;
   case DownloadManager.STATUS_PAUSED:
    String pausedReason = "";
    
    switch(reason){
    case DownloadManager.PAUSED_QUEUED_FOR_WIFI:
     pausedReason = "PAUSED_QUEUED_FOR_WIFI";
     break;
    case DownloadManager.PAUSED_UNKNOWN:
     pausedReason = "PAUSED_UNKNOWN";
     break;
    case DownloadManager.PAUSED_WAITING_FOR_NETWORK:
     pausedReason = "PAUSED_WAITING_FOR_NETWORK";
     break;
    case DownloadManager.PAUSED_WAITING_TO_RETRY:
     pausedReason = "PAUSED_WAITING_TO_RETRY";
     break;
    }
    
    Toast.makeText(AndroidDownloadManagerActivity.this, 
      "PAUSED: " + pausedReason, 
      Toast.LENGTH_LONG).show();
    break;
   case DownloadManager.STATUS_PENDING:
    Toast.makeText(AndroidDownloadManagerActivity.this, 
      "PENDING", 
      Toast.LENGTH_LONG).show();
    break;
   case DownloadManager.STATUS_RUNNING:
    Toast.makeText(AndroidDownloadManagerActivity.this, 
      "RUNNING", 
      Toast.LENGTH_LONG).show();
    break;
   case DownloadManager.STATUS_SUCCESSFUL:
    
    Toast.makeText(AndroidDownloadManagerActivity.this, 
      "SUCCESSFUL", 
      Toast.LENGTH_LONG).show();
    GetFile();
    downloadManager.remove(id);
    break;
   } 
  } 
 }
 
 private void GetFile(){
  //Retrieve the saved request id
  long downloadID = preferenceManager.getLong(strPref_Download_ID, 0);
  
  ParcelFileDescriptor file;
  try {
   file = downloadManager.openDownloadedFile(downloadID);
   FileInputStream fileInputStream 
    = new ParcelFileDescriptor.AutoCloseInputStream(file);
   Bitmap bm = BitmapFactory.decodeStream(fileInputStream);
   image.setImageBitmap(bm);
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
 }
}

Confirm to Quit? Over-write the BACK key.


Confirm to Quit? Over-write the BACK key.

To over-write the BACK key, to prompt user for confirmation to quit instead of exiting directly, simply override the onBackPressed() method.

Confirm to Quit? Over-write the BACK key.

package com.exercise.AndroidConfirmQuit;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;

public class AndroidConfirmQuitActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
 @Override
 public void onBackPressed() {
  // TODO Auto-generated method stub
  //super.onBackPressed();
  openQuitDialog();
 }
 
 private void openQuitDialog(){
  AlertDialog.Builder quitDialog 
   = new AlertDialog.Builder(AndroidConfirmQuitActivity.this);
  quitDialog.setTitle("Confirm to Quit?");
  
  quitDialog.setPositiveButton("OK, Quit!", new OnClickListener(){

   @Override
   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    finish();
   }});
  
  quitDialog.setNegativeButton("NO", new OnClickListener(){

   @Override
   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    
   }});
  
  quitDialog.show();
 }
}

Set styling text on TextView


Set styling text on TextView

styling text



Define your string resource (stylingtext) in /res/values/strings.xml, with styling markup.

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <string name="hello">Hello World, AndroidStylingTextActivity!</string>

    <string name="app_name">AndroidStylingText</string>

    <string name="stylingtext">

    Styling Text:\n

    <i>Italic</i> <b>Bold</b> <monospace>Monospace</monospace>\n 

    <strike>Strike</strike> <sup>Superscript</sup> <sub>Subscript</sub> <u>Underline</u>\n

    <big><big><big>Big x 3 </big>Big x 2 </big>Big</big> <small>Small <small>Small x 2</small></small>

    </string>

</resources>






Then you can refer the string resource in your layout file, 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"

    />

<TextView  

    android:layout_width="fill_parent" 

    android:layout_height="wrap_content" 

    android:text="@string/stylingtext"

    />

</LinearLayout>

Using GestureDetector with SimpleOnGestureListener


Using GestureDetector with SimpleOnGestureListener

GestureDetector.SimpleOnGestureListener is a convenience class to extend when you only want to listen for a subset of all the gestures.

Using GestureDetector with SimpleOnGestureListener

package com.exercise.AndroidSimpleGesture;

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.widget.TextView;

public class AndroidSimpleGestureActivity extends Activity {

TextView gestureEvent;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       gestureEvent = (TextView)findViewById(R.id.GestureEvent);
   }
  
   @Override
public boolean onTouchEvent(MotionEvent event) {
 // TODO Auto-generated method stub
    return gestureDetector.onTouchEvent(event);
}

SimpleOnGestureListener simpleOnGestureListener
   = new SimpleOnGestureListener(){

 @Override
 public boolean onDoubleTap(MotionEvent e) {
  // TODO Auto-generated method stub
  gestureEvent.setText("onDoubleTap: \n" + e.toString());
  return super.onDoubleTap(e);
 }

 @Override
 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
   float velocityY) {
  // TODO Auto-generated method stub
  gestureEvent.setText("onFling: \n" + e1.toString() + "\n" + e2.toString() +"\n"
    + "velocityX= " + String.valueOf(velocityX) + "\n"
    + "velocityY= " + String.valueOf(velocityY) + "\n");
  return super.onFling(e1, e2, velocityX, velocityY);
 }

 @Override
 public void onLongPress(MotionEvent e) {
  // TODO Auto-generated method stub
  gestureEvent.setText("onLongPress: \n" + e.toString());
  super.onLongPress(e);
 }

 @Override
 public boolean onSingleTapConfirmed(MotionEvent e) {
  // TODO Auto-generated method stub
  gestureEvent.setText("onSingleTapConfirmed: \n" + e.toString());
  return super.onSingleTapConfirmed(e);
 }

   };
  
   GestureDetector gestureDetector
   = new GestureDetector(simpleOnGestureListener);
}


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

   <TextView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="@string/hello" />
  
   <TextView
       android:id="@+id/GestureEvent"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content" />

</LinearLayout>

Detect swipe using SimpleOnGestureListener


Detect swipe using SimpleOnGestureListener

 In thisexercise, we modify the SimpleOnGestureListener to detect swipe by overriding onFling() method.

Detect swipe using SimpleOnGestureListener

package com.exercise.AndroidSimpleGesture;

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.widget.TextView;

public class AndroidSimpleGestureActivity extends Activity {
 
 TextView gestureEvent;
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       gestureEvent = (TextView)findViewById(R.id.GestureEvent);
   }
  
   @Override
 public boolean onTouchEvent(MotionEvent event) {
  // TODO Auto-generated method stub
    return gestureDetector.onTouchEvent(event);
 }

 SimpleOnGestureListener simpleOnGestureListener
   = new SimpleOnGestureListener(){


  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    float velocityY) {
   String swipe = "";
   float sensitvity = 50;
   
   // TODO Auto-generated method stub
   if((e1.getX() - e2.getX()) > sensitvity){
    swipe += "Swipe Left\n";
   }else if((e2.getX() - e1.getX()) > sensitvity){
    swipe += "Swipe Right\n";
   }else{
    swipe += "\n";
   }
   
   if((e1.getY() - e2.getY()) > sensitvity){
    swipe += "Swipe Up\n";
   }else if((e2.getY() - e1.getY()) > sensitvity){
    swipe += "Swipe Down\n";
   }else{
    swipe += "\n";
   }
   
   gestureEvent.setText(swipe);
   
   return super.onFling(e1, e2, velocityX, velocityY);
  }
   };
  
   GestureDetector gestureDetector
   = new GestureDetector(simpleOnGestureListener);
}

Play Ring Tone in Ring Tone Text Transfer Language (RTTTL) format using MediaPlayer


Play Ring Tone in Ring Tone Text Transfer Language (RTTTL) format using MediaPlayer

Ring Tone Text Transfer Language (RTTTL) was developed by Nokia to be used to transfer ringtonesto cellphone by Nokia, to know more please refer to Wikipedia - Ring Tone Transfer Language.

It's a example to play a single note in RTTTL format using MediaPlayer.

Play Ring Tone in Ring Tone Text Transfer Language (RTTTL) format using MediaPlayer

First, create a xml(/res/raw/a4.rtttl) to define a single note in RTTTL format.
<a4:d=4,o=5,b=250:a4;


Main Code:
package com.exercise.AndroidRTTTL;

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

public class AndroidRTTTLActivity extends Activity {
 
 Button buttonPlay;
 MediaPlayer mediaPlayer;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        buttonPlay = (Button)findViewById(R.id.play);
        buttonPlay.setOnClickListener(buttonPlayOnClickListener);
    }
    
    Button.OnClickListener buttonPlayOnClickListener
    = new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   if(mediaPlayer != null) 
   {
    mediaPlayer.release();
   }
   
   mediaPlayer = MediaPlayer.create(AndroidRTTTLActivity.this, R.raw.a4);
   mediaPlayer.start();
   
  }};
}


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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <Button
        android:id="@+id/play" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Play" />

</LinearLayout>

Create frame animation with AnimationDrawable


Create frame animation with AnimationDrawable






Before we start coding for our frame animation, we have to prepare some .png graph for our frames,named android_1.png ~ android_7.png. Copy all graphs to /res/drawable folder.























Create a file /res/anim/anim_android.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false"
>
<item
android:drawable="@drawable/android_1"
android:duration="100"/>
<item
android:drawable="@drawable/android_2"
android:duration="100"/>
<item
android:drawable="@drawable/android_3"
android:duration="100"/>
<item
android:drawable="@drawable/android_4"
android:duration="100"/>
<item
android:drawable="@drawable/android_5"
android:duration="100"/>
<item
android:drawable="@drawable/android_6"
android:duration="100"/>
<item
android:drawable="@drawable/android_7"
android:duration="100"/>
</animation-list>


Modify main.xml, add a ImageView with android:src="@anim/anim_android".
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<ImageView
android:id="@+id/myanimation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@anim/anim_android"
/>

</LinearLayout>


Modify our activity:
package com.exercise.AndroidAnimation;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class AndroidAnimationActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ImageView myAnimation = (ImageView)findViewById(R.id.myanimation);
final AnimationDrawable myAnimationDrawable
= (AnimationDrawable)myAnimation.getDrawable();

myAnimation.post(
new Runnable(){

  @Override
  public void run() {
   myAnimationDrawable.start();
  }
});
}
}