Thursday, March 1, 2012

Beginning Android (Part 2)

Revision History
Latest:
Revision 0.5 - Apr. 21, 2012
Revision 0.0 02.29.2012
  • Created
  • First draft
Revision 0.1 03.01.2012
  • Added "Getting Feedback After Sending SMS"
Revision 0.2 03.14.2012
  • Added "Obtaining The Required Tools" screencast to show how to setup your development environment for the first time
Revision 0.3 - 0.5 03.29.2012
04.10.2012
04.21.2012
  • Enhancements

Creating Your First Android Application
The first Android application I am developing is the BlueMine Starter Package in Google Play Store.

Part 1 of this Beginning Android tutorial series covered the overview of the Android platform. If you haven't seen it yet, please take some time to read it before reading this article.

In this article, you will develop your first Android application. You will learn how to send SMS programmatically within an Android application.
NOTE: This tutorial assumes that you are familiar with Java programming and IDE's like Eclipse and NetBeans.


Brief Contents
  1. The Four Components of Android
  2. Creating The SMS Application
    • Obtaining The Required Tools
    • Developing SendingSMS project



Why Develop for Android?

The Android (known as the iOS killer) has some huge advantages over other mobile operating system like the iOS, Symbian, Windows Phone, etc. If you take a look at the Android Ice Cream Sandwich you can say to yourself that its very revolutionary and innovative, isn't it? Android has Home-screen Widgets and other features you can't find in iOS or any other mobile operating system. You can develop powerful and innovative apps that integrates with its core applications such as Google Maps with Location-Based Services and more.

Android is free and open-source and it uses the #1 Java programming language.

The Four Components of Android

Your Android projects should contain at least one class that is derived from one of these components:
  • Activity - If your Android application has a UI, you must create one class that extends this component. You will learn how to create an Activity in this article.
  • Service - If your Android application has a long running task, you should do it in the background and not in the UI thread. This class provides the facility to make a task run in the background.
  • BroadcastReceiver - If your Android application will receive and respond to global events such as the sending and delivery of SMS, your class must be registered as a subclass of this component. You will learn how to use this component to get feedback after sending SMS.
  • ContentProvider - If your Android application has data that you wants to share with other Android applications, you should create and implement this component.
For the detailed look at the Android Build process please refer to Android documentation.

Creating The SMS Application

Android development has four phases. Below is a diagram of Android development process:
http://developer.android.com/images/developing/developing_overview.png

Obtaining The Required Tools

Before you can start creating Android application, you must setup your development environment first. You will need the following to develop our SMS application:
  • Android SDK
  • Eclipse (Helios or greater)
Note: You need to install at least the Android 1.6 platform for this tutorial.
See Android Installation Instructions and System Requirements for more information and watch this video to learn how to setup your development environment for the first time on Windows.


I use Windows 7, Java 7, Eclipse Indigo for Java Developers, ADT and Android SDK revision 17 in this screencast.

Developing The SMS Project

SMS messaging is one of the killer applications on Android or any mobile phones today. Let's create your first simple and practical Android project. I assume that you are already familiar with Java programming here. I will not explain the detail of each line of code here. I'll give some instructions here that you should follow:
SMS messaging is one of the killer applications on Android or any mobile phones today. Let's create your first simple and practical Android project. I assume that you are already familiar with Java programming; I will not explain each line of code in detail.

Follow these steps:

1. Start your Eclipse IDE

2. Go to File -> New -> Project


3. Select Android Project in the New Project dialog


4. Complete the New Android Project wizard.




5. Open main.xml (located in <your project's name>/res/layout) and replace its contents with the code below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <EditText
        android:id="@+id/editRecipient"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="14dp"
        android:hint="@string/recipientHint"
        android:inputType="phone" />
    <EditText
        android:id="@+id/editMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="17dp"
        android:layout_toLeftOf="@+id/sendButton"
        android:hint="@string/messageBodyHint" >
    </EditText>
    <Button
        android:id="@+id/sendButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/editMessage"
        android:onClick="send"
        android:text="@string/sendButtonText" />
</RelativeLayout>
Note: I used RelativeLayout here because I need to align each common form component relative to the other components.
6. Open SMSActivity.java (located in <your project's name>/src/<your package name>) and add the following code:
public void send(android.view.View view) {
final android.widget.EditText recipient = (android.widget.EditText) findViewById(R.id.editRecipient);
final android.widget.EditText message = (android.widget.EditText) findViewById(R.id.editMessage);
final android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
final String addr = recipient.getText().toString();
final String text = message.getText().toString();
smsManager.sendTextMessage(addr, null, text, null, null);
recipient.setText("");
message.setText("");
}
7. To allow our application to send SMS, add the following permission to AndroidManifest.xml (located in your project's root directory):
<uses-permission android:name="android.permission.SEND_SMS" />
8. That's it. Deploy and run the project.



How It Works

Steps 1 to 4 show you how to create a new Android application in Eclipse. Steps 5 to 7 cover the code that will enable your new application to send SMS: step 5 changes the layout of your application's UI; step 6 includes the actual code that sends an SMS, and; step 7 includes a code snippet that informs our users about the permissions the application needs to send SMS. Step 8 shows you how to run the application.
We add the code in step 7 above to inform our users about the permissions our application needs to send SMS. Then at step 6, we add the actual code that sends the SMS message. We use the built-in Android telephony API class called android.telephony.SmsManager. Easy isn't it?

The application uses the built-in Android telephony API class `android.telephony.SmsManager` to send SMS; for more information, see: documentation of SmsManager API.
The complete source code for this application is hosted at Kenai.com. You must have a Subversion client installed on your machine to checkout the project repository. 
If you have the command line Subversion client, you can checkout the repository by running: 
`svn co https://svn.kenai.com/svn/ron-os-sample-code~project-code-repository/BeginningAndroidProjects/SendingSMS` 
This will checkout a copy of the SendingSMS project.

Getting Feedback After Sending The SMS
Note: The code snippets in this section are from a modified version of the source code in the SendingSMS project; the full source code is in a separate project called SendingSMS2.
You now know how to send SMS message using SmsManager class; however, how will you know if the message was sent successfully? To do so, you need to create an instance of PendingIntent and pass it as the 3rd parameter to sendTextMessage() method of SmsManager. You also need to register a BroadcastReceiver to listen to global event named "SMS_SENT".
You can checkout the project's repository via the command line Subversion client by running:
`svn co https://svn.kenai.com/svn/ron-os-sample-code~project-code-repository/BeginningAndroidProjects/SendingSMS2`
Once you've checked out the SendingSMS2 project, open it with Eclipse and take a look at the new implementation of the send() method of SMSActivity.java. See the code in bold:
public void send( android.view.View view) {
android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
android.app.PendingIntent sendingIntent = android.app.PendingIntent.getBroadcast(this, 0,
new android.content.Intent(SMS_SENT), 0);

String addr = recipient.getText().toString();
String text = message.getText().toString();
sendButton.setEnabled(false);
status.setText(R.string.messageSending);
smsManager.sendTextMessage(addr, null, text, sendingIntent, null);
}
I've implement a BroadcastReceiver to listen for "SMS_SENT" update:
private final android.content.BroadcastReceiver smsSentReceiver = new android.content.BroadcastReceiver() {
@Override
public void onReceive(android.content.Context context, android.content.Intent data) {
switch (getResultCode()) {
case RESULT_OK:
status.setText(R.string.messageSentSuccess);
break;
default:
status.setText(R.string.messageSentFailed);
}
recipient.setText("");
message.setText("");
sendButton.setEnabled(true);
}
};
Then I register the BroadcastReceiver in the onStart() method, which is called when the SMSActivity starts:
@Override
protected void onStart() {
super.onStart();
registerReceiver(smsSentReceiver, new android.content.IntentFilter(SMS_SENT));
}
Then I unregistered it in the onStop() method, which is called when the SMSActivity stops, to avoid leaks:
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(smsSentReceiver);
}
All done! You have now created your first simple and practical Android application =)

What's Next?

Checkout the complete project @ http://kenai.com/projects/ron-os-sample-code/sources/project-code-repository/history/BeginningAndroidProjects. You must have any Subversion client installed on your machine to checkout my example project.

Thank You!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.