Ch09 Listings

satya - Saturday, February 27, 2010 8:18:32 PM

Listing 9-1


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

public class MainActivity extends Activity
{
    static final String AUDIO_PATH =
"http://www.androidbook.com/akc/filestorage/android/documentfiles/3389/play.mp3";

    private MediaPlayer mediaPlayer;
    private int playbackPosition=0;

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

        Button startPlayerBtn = (Button)findViewById(R.id.startPlayerBtn);
        Button pausePlayerBtn = (Button)findViewById(R.id.pausePlayerBtn);
        Button restartPlayerBtn = (Button)findViewById(R.id.restartPlayerBtn);

        startPlayerBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view)
            {
                try {
                    playAudio(AUDIO_PATH);
//                    playLocalAudio();
//                    playLocalAudio_UsingDescriptor();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }});

        pausePlayerBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view)
            {
                if(mediaPlayer!=null)
                {
                    playbackPosition = mediaPlayer.getCurrentPosition();
                    mediaPlayer.pause();
                }
            }});

        restartPlayerBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view)
            {
                if(mediaPlayer!=null && !mediaPlayer.isPlaying())
                {
                    mediaPlayer.seekTo(playbackPosition);
                    mediaPlayer.start();
                }
            }});
    }

    private void playAudio(String url)throws Exception
    {
        killMediaPlayer();

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource(url);
        mediaPlayer.prepare();
        mediaPlayer.start();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        killMediaPlayer();
    }
    private void killMediaPlayer()
    {
        if(mediaPlayer!=null)
        {
            try
            {
                mediaPlayer.release();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

satya - Saturday, February 27, 2010 8:18:59 PM

Listing 9-1 xml


<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button android:id="@+id/startPlayerBtn"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Playing Audio"
    />

<Button android:id="@+id/restartPlayerBtn"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Restart Player"
    />

<Button android:id="@+id/pausePlayerBtn"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Pause Player"
    />
</LinearLayout>

satya - Saturday, February 27, 2010 8:19:18 PM

Listing 9-2


private void playLocalAudio()throws Exception
    {
        mediaPlayer = MediaPlayer.create(this, R.raw.music_file);
        mediaPlayer.start();
    }

satya - Saturday, February 27, 2010 8:19:48 PM

Listing 9-3


private void playLocalAudio_UsingDescriptor() throws Exception {

    AssetFileDescriptor fileDesc = getResources().openRawResourceFd(
            R.raw.music_file);
    if (fileDesc != null) {

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource(fileDesc.getFileDescriptor(), fileDesc
                .getStartOffset(), fileDesc.getLength());

        fileDesc.close();

        mediaPlayer.prepare();
        mediaPlayer.start();
    }
}

satya - Saturday, February 27, 2010 8:20:07 PM

Listing 9-4


import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

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

        VideoView videoView = (VideoView)this.findViewById(R.id.videoView);
        MediaController mc = new MediaController(this);
        videoView.setMediaController(mc);
        videoView.setVideoURI(Uri.parse(
              "http://www.androidbook.com/akc/filestorage/android/documentfiles/3389/movie.mp4"));
        // videoView.setVideoPath("/sdcard/movie.mp4");
        videoView.requestFocus();
        videoView.start();
    }
}

satya - Saturday, February 27, 2010 8:20:35 PM

Listing 9-4 xml


<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 xmlns:android="http://schemas.android.com/apk/res/android">

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="200px"
        android:layout_height="200px" />

</LinearLayout>

satya - Saturday, February 27, 2010 8:20:57 PM

Listing 9-5


// RecorderActivity.java
import java.io.File;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class RecorderActivity extends Activity {
    private MediaPlayer mediaPlayer;
    private MediaRecorder recorder;
    private static final String OUTPUT_FILE= "/sdcard/recordoutput.3gpp";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.record);

        Button startBtn = (Button) findViewById(R.id.bgnBtn);

        Button endBtn = (Button) findViewById(R.id.stpBtn);

        Button playRecordingBtn = (Button) findViewById(R.id.playRecordingBtn);

        Button stpPlayingRecordingBtn = 
(Button) findViewById(R.id.stpPlayingRecordingBtn);

        startBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                try {
                    beginRecording();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        endBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                try {
                    stopRecording();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        playRecordingBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                try {
                    playRecording();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        stpPlayingRecordingBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                try {
                    stopPlayingRecording();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void beginRecording() throws Exception {
        killMediaRecorder();

        File outFile = new File(OUTPUT_FILE);

        if(outFile.exists())
        {
            outFile.delete();
        }
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(OUTPUT_FILE);
        recorder.prepare();
        recorder.start();

    }

    private void stopRecording() throws Exception {
        if (recorder != null) {
            recorder.stop();
        }
    }

    private void killMediaRecorder() {
        if (recorder != null) {
            recorder.release();
        }
    }

    private void killMediaPlayer() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void playRecording() throws Exception {
        killMediaPlayer();

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource(OUTPUT_FILE);

        mediaPlayer.prepare();
        mediaPlayer.start();
    }
    private void stopPlayingRecording() throws Exception {
        if(mediaPlayer!=null)
        {
            mediaPlayer.stop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        killMediaRecorder();
        killMediaPlayer();
    }

}

satya - Saturday, February 27, 2010 8:21:22 PM

Listing 9-5 xml


<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/record.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button android:id="@+id/bgnBtn" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Begin Recording"/>

        <Button android:id="@+id/stpBtn" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Stop Recording"/>

        <Button android:id=
"@+id/playRecordingBtn" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Play Recording"/>

        <Button android:id=
"@+id/stpPlayingRecordingBtn" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Stop Playing Recording"/>

    </LinearLayout>

satya - Saturday, February 27, 2010 8:21:44 PM

Listing 9-6


import java.io.File;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity implements SurfaceHolder.Callback {

	    private MediaRecorder recorder = null;
	    private static final String OUTPUT_FILE = "/sdcard/videooutput.mp4";
	    private static final String TAG = "RecordVideo";
	    private VideoView videoView = null;
	    private Button startBtn = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        startBtn = (Button) findViewById(R.id.bgnBtn);

        Button endBtn = (Button) findViewById(R.id.stpBtn);

        Button playRecordingBtn = (Button) findViewById(R.id.playRecordingBtn);

        Button stpPlayingRecordingBtn = 
(Button) findViewById(R.id.stpPlayingRecordingBtn);

        videoView = (VideoView)this.findViewById(R.id.videoView);

        final SurfaceHolder holder = videoView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        startBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                try {
                    beginRecording(holder);
                } catch (Exception e) {
                    Log.e(TAG, e.toString());
                    e.printStackTrace();
                }
            }
        });

        endBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                try {
                    stopRecording();
                } catch (Exception e) {
                    Log.e(TAG, e.toString());
                    e.printStackTrace();
                }
            }
        });

        playRecordingBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                try {
                    playRecording();
                } catch (Exception e) {
                    Log.e(TAG, e.toString());
                    e.printStackTrace();
                }
            }
        });

        stpPlayingRecordingBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                try {
                    stopPlayingRecording();
                } catch (Exception e) {
                    Log.e(TAG, e.toString());
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        startBtn.setEnabled(true);
    }
    
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
	    	    int height) {
        Log.v(TAG, "Width x Height = " + width + "x" + height);
    }

    private void playRecording() {
        MediaController mc = new MediaController(this);
        videoView.setMediaController(mc);
        videoView.setVideoPath(OUTPUT_FILE);
        videoView.start();
    }
    
    private void stopPlayingRecording() {
        videoView.stopPlayback();
    }
    
    private void stopRecording() throws Exception {
        if (recorder != null) {
            recorder.stop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (recorder != null) {
            recorder.release();
        }
    }

    private void beginRecording(SurfaceHolder holder) throws Exception {
        if(recorder!=null)
        {
            recorder.stop();
            recorder.release();
        }

        File outFile = new File(OUTPUT_FILE);
        if(outFile.exists())
        {
            outFile.delete();
        }

        try {
            recorder = new MediaRecorder();
            recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            recorder.setVideoSize(176, 144);
            recorder.setVideoFrameRate(15);
            recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setMaxDuration(30000); // limit to 30 seconds
            recorder.setPreviewDisplay(holder.getSurface());
            recorder.setOutputFile(OUTPUT_FILE);
            recorder.prepare();
            recorder.start();
        }
        catch(Exception e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
    }
}

satya - Saturday, February 27, 2010 8:22:44 PM

Listing 9-6 xml


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

	    <Button android:id="@+id/bgnBtn" android:layout_width="fill_parent"
	    	    android:layout_height="wrap_content" android:text="Begin Recording"
	    	    android:enabled="false" />

	    <Button android:id="@+id/stpBtn" android:layout_width="fill_parent"
	    	    android:layout_height="wrap_content" android:text="Stop Recording" />

	    <Button android:id="@+id/playRecordingBtn" android:layout_width="fill_parent"
	    	    android:layout_height="wrap_content" android:text="Play Recording" />

	    <Button android:id="@+id/stpPlayingRecordingBtn"
	    	    android:layout_width="fill_parent" android:layout_height="wrap_content"
	    	    android:text="Stop Playing Recording" />

    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center">
        
	        <VideoView android:id="@+id/videoView" android:layout_width="176px"
	    	        android:layout_height="144px" />
		    
    </RelativeLayout>
</LinearLayout>

satya - Saturday, February 27, 2010 8:23:07 PM

Listing 9-7


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class UsingMediaStoreActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        
        Button btn = (Button)findViewById(R.id.recordBtn);
        btn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                
                startRecording();
                
            }});
    }

    public void startRecording() {
        Intent intt = new Intent("android.provider.MediaStore.RECORD_SOUND");
        startActivityForResult(intt, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
        case 0:
            if (resultCode == RESULT_OK) {
                Uri recordedAudioPath = data.getData();
            }
        }
    }
}

satya - Saturday, February 27, 2010 8:23:28 PM

Listing 9-7 xml


<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
 <Button android:id="@+id/recordBtn"
            android:text="Record Audio"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
</LinearLayout>

satya - Saturday, February 27, 2010 8:23:47 PM

Listing 9-8


import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    
    Uri myPicture = null;

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

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    public void captureImage(View view)
    {
        ContentValues values = new ContentValues();
        values.put(Media.TITLE, "My demo image");
        values.put(Media.DESCRIPTION, "Image Captured by Camera via an Intent");

        myPicture = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);

        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        i.putExtra(MediaStore.EXTRA_OUTPUT, myPicture);

        startActivityForResult(i, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==0 && resultCode==Activity.RESULT_OK)
        {
            // Now we know that our myPicture URI refers to the image just taken 
        }
    }
}

satya - Saturday, February 27, 2010 8:24:23 PM

Listing 9-8 xml


<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
 <Button android:id="@+id/btn"
            android:text="Take Picture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:onClick="captureImage" />
        
</LinearLayout>

satya - Saturday, February 27, 2010 8:24:41 PM

Listing 9-9


import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MediaScannerActivity extends Activity implements MediaScannerConnectionClient 
{
    private EditText editText = null;
    private String filename = null;
    private MediaScannerConnection conn;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        editText = (EditText)findViewById(R.id.fileName);
    }

    public void startScan(View view)
    {
        if(conn!=null)
        {
            conn.disconnect();
        }
        
        filename = editText.getText().toString();

        File fileCheck = new File(filename);
        if(fileCheck.isFile()) {
            conn = new MediaScannerConnection(this, this);
            conn.connect();
        }
        else {
            Toast.makeText(this,
                "That file does not exist",
                Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onMediaScannerConnected() {
        conn.scanFile(filename, null);
    }

    @Override
    public void onScanCompleted(String path, Uri uri) {
        try {
            if (uri != null) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(uri);
                startActivity(intent);
            }
            else {
                Log.e("MediaScannerDemo", "That file is no good");
            }
        } finally {
            conn.disconnect();
            conn = null;
        } 
    }
}

satya - Saturday, February 27, 2010 8:25:02 PM

Listing 9-9 xml


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

  <EditText android:id="@+id/fileName"
    android:hint="Enter new filename"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
	  
  <Button android:id="@+id/scanBtn"
    android:text="Add file"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick=�?�startScan�?� />
    
</LinearLayout>

satya - Saturday, February 27, 2010 8:25:23 PM

Listing 9-10


import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class TelephonyDemo extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        Button sendBtn = (Button)findViewById(R.id.sendSmsBtn);

        sendBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                EditText addrTxt = 
                      (EditText)TelephonyDemo.this.findViewById(R.id.addrEditText);

                EditText msgTxt = 
                      (EditText)TelephonyDemo.this.findViewById(R.id.msgEditText);

                try {
                    sendSmsMessage(
                        addrTxt.getText().toString(),msgTxt.getText().toString());
                    Toast.makeText(TelephonyDemo.this, "SMS Sent", 
                	        Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(TelephonyDemo.this, "Failed to send SMS", 
                	        Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }});
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void sendSmsMessage(String address,String message)throws Exception
    {
        SmsManager smsMgr = SmsManager.getDefault();
        smsMgr.sendTextMessage(address, null, message, null, null);
    }
}

satya - Saturday, February 27, 2010 8:25:45 PM

Listing 9-10 xml


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

	    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	    	    android:orientation="horizontal" android:layout_width="fill_parent"
	    	    android:layout_height="wrap_content">

	    	    <TextView android:layout_width="wrap_content"
	    	    	    android:layout_height="wrap_content" android:text="Destination Address:" />

	    	    <EditText android:id="@+id/addrEditText"
	    	    	    android:layout_width="fill_parent" android:layout_height="wrap_content"
	    	    	    android:phoneNumber=�?�true�?� android:text="9045551212" />

	    </LinearLayout>

	    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	    	    android:orientation="vertical" android:layout_width="fill_parent"
	    	    android:layout_height="wrap_content">

	    	    <TextView android:layout_width="wrap_content"
	    	    	    android:layout_height="wrap_content" android:text="Text Message:" />

	    	    <EditText android:id="@+id/msgEditText" android:layout_width="fill_parent"
	    	    	    android:layout_height="wrap_content" android:text="hello sms" />

	    </LinearLayout>

	    <Button android:id="@+id/sendSmsBtn" android:layout_width="wrap_content"
	    	    android:layout_height="wrap_content" android:text="Send Text Message" />

</LinearLayout>

satya - Saturday, February 27, 2010 8:26:08 PM

Listing 9-11


public class MySMSMonitor extends BroadcastReceiver
{
    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if(intent!=null && intent.getAction()!=null && 
ACTION.compareToIgnoreCase(intent.getAction())==0)
        {
            Object[]pduArray= (Object[]) intent.getExtras().get("pdus");
            SmsMessage[] messages = new SmsMessage[pduArray.length];
            for (int i = 0; i<pduArray.length; i++) {
                    messages[i] = SmsMessage.createFromPdu ((byte[])pduArray [i]);
            }
            Log.d("MySMSMonitor","SMS Message Received.");
        }
    }
}

satya - Saturday, February 27, 2010 8:26:23 PM

Listing 9-11


<receiver android:name="MySMSMonitor">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    </intent-filter>
</receiver>

satya - Saturday, February 27, 2010 8:26:41 PM

Listing 9-12


import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

public class SMSInboxDemo extends ListActivity {

    private ListAdapter adapter;
    private static final Uri SMS_INBOX = Uri.parse("content://sms/inbox");

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        Cursor c = getContentResolver()
                .query(SMS_INBOX, null, null, null, null);
        startManagingCursor(c);
        String[] columns = new String[] { "body" };
        int[] names = new int[] { R.id.row };
        adapter = new SimpleCursorAdapter(this, R.layout.sms_inbox, c, columns,
                names);

        setListAdapter(adapter);
    }
}

satya - Saturday, February 27, 2010 8:27:04 PM

Listing 9-12 xml


<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/sms_inbox.xml -->
<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:id="@+id/row"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

</LinearLayout>

satya - Saturday, February 27, 2010 8:28:08 PM

Listing 9-13


public class TelephonyServiceDemo extends Activity
{
    private static final String TAG="TelephonyServiceDemo";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        TelephonyManager teleMgr = 
              (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        teleMgr.listen(new MyPhoneStateListener(), 
        PhoneStateListener.LISTEN_CALL_STATE);
    }

    class MyPhoneStateListener extends PhoneStateListener
    {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            switch(state)
            {

                case TelephonyManager.CALL_STATE_IDLE:
                    Log.d(TAG, "call state idle...incoming number is["+
                                  incomingNumber+"]");break;
                case TelephonyManager.CALL_STATE_RINGING:
                    Log.d(TAG, "call state ringing...incoming number is["+
                                  incomingNumber+"]");break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    Log.d(TAG, "call state Offhook...incoming number is["+
                                  incomingNumber+"]");break;
                default:
                     Log.d(TAG, "call state ["+state+"]incoming number is["+
                                  incomingNumber+"]");break;
            }
        }
    }
}