Android Environment Setup

You will be glad to know that you can start your Android application development on either of the following operating systems −

  • Microsoft Windows XP or later version.

  • Mac OS X 10.5.8 or later version with Intel chip.

  • Linux including GNU C Library 2.7 or later.

Second point is that all the required tools to develop Android applications are freely available and can be downloaded from the Web. Following is the list of software’s you will need before you start your Android application programming.

  • Java JDK5 or later version

  • Android Studio

Here last two components are optional and if you are working on Windows machine then these components make your life easy while doing Java based application development. So let us have a look how to proceed to set required environment.

Set-up Java Development Kit (JDK)

You can download the latest version of Java JDK from Oracle’s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

If you are running Windows and installed the JDK in C:\jdk1.8.0_102, you would have to put the following line in your C:\autoexec.bat file.

set PATH=C:\jdk1.8.0_102\bin;%PATH%
set JAVA_HOME=C:\jdk1.8.0_102

Alternatively, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.

On Linux, if the SDK is installed in /usr/local/jdk1.8.0_102 and you use the C shell, you would put the following code into your .cshrc file.

setenv PATH /usr/local/jdk1.8.0_102/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.8.0_102

Alternatively, if you use Android studio, then it will know automatically where you have installed your Java.

Android IDEs

There are so many sophisticated Technologies are available to develop android applications, the familiar technologies, which are predominantly using tools as follows

Android overview

What is Android?

Who I Am

Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies.

Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android.

The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008.

On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance.

The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2.

Why Android ?

Why Android

Features of Android

Android is a powerful operating system competing with Apple 4GS and supports great features. Few of them are listed below −

Sr.No. Feature & Description
1

Beautiful UI

Android OS basic screen provides a beautiful and intuitive user interface.

2

Connectivity

GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX.

3

Storage

SQLite, a lightweight relational database, is used for data storage purposes.

4

Media support

H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP.

5

Messaging

SMS and MMS

6

Web browser

Based on the open-source WebKit layout engine, coupled with Chrome’s V8 JavaScript engine supporting HTML5 and CSS3.

7

Multi-touch

Android has native support for multi-touch which was initially made available in handsets such as the HTC Hero.

8

Multi-tasking

User can jump from one task to another and same time various application can run simultaneously.

9

Resizable widgets

Widgets are resizable, so users can expand them to show more content or shrink them to save space.

10

Multi-Language

Supports single direction and bi-directional text.

11

GCM

Google Cloud Messaging (GCM) is a service that lets developers send short message data to their users on Android devices, without needing a proprietary sync solution.

12

Wi-Fi Direct

A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-peer connection.

13

Android Beam

A popular NFC-based technology that lets users instantly share, just by touching two NFC-enabled phones together.

Android Applications

Android applications are usually developed in the Java language using the Android Software Development Kit.

Once developed, Android applications can be packaged easily and sold out either through a store such as Google PlaySlideMEOpera Mobile StoreMobangoF-droid and the Amazon Appstore.

Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It’s the largest installed base of any mobile platform and growing fast. Every day more than 1 million new Android devices are activated worldwide.

This tutorial has been written with an aim to teach you how to develop and package Android application. We will start from environment setup for Android application programming and then drill down to look into various aspects of Android applications.

Categories of Android applications

There are many android applications in the market. The top categories are −

Categories

History of Android

The code names of android ranges from A to N currently, such as Aestro, Blender, Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat, Lollipop and Marshmallow. Let’s understand the android history in a sequence.

Jistory

What is API level?

API Level is an integer value that uniquely identifies the framework API revision offered by a version of the Android platform.

Platform Version API Level VERSION_CODE
Android 6.0 23 MARSHMALLOW
Android 5.1 22 LOLLIPOP_MR1
Android 5.0 21 LOLLIPOP
Android 4.4W 20 KITKAT_WATCH KitKat for Wearables Only
Android 4.4 19 KITKAT
Android 4.3 18 JELLY_BEAN_MR2
Android 4.2, 4.2.2 17 JELLY_BEAN_MR1
Android 4.1, 4.1.1 16 JELLY_BEAN
Android 4.0.3, 4.0.4 15 ICE_CREAM_SANDWICH_MR1
Android 4.0, 4.0.1, 4.0.2 14 ICE_CREAM_SANDWICH
Android 3.2 13 HONEYCOMB_MR2
Android 3.1.x 12 HONEYCOMB_MR1
Android 3.0.x 11 HONEYCOMB

Android 2.3.4

Android 2.3.3

10 GINGERBREAD_MR1

Android 2.3.2

Android 2.3.1

Android 2.3

9 GINGERBREAD
Android 2.2.x 8 FROYO
Android 2.1.x 7 ECLAIR_MR1
Android 2.0.1 6 ECLAIR_0_1
Android 2.0 5 ECLAIR
Android 1.6 4 DONUT
Android 1.5 3 CUPCAKE
Android 1.1 2 BASE_1_1
Android 1.0 1 BASE

android overview

​Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance , led by Google, and other companies.

Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android.

The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008.

On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance.

The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2.

Android is a powerful operating system competing with Apple 4GS and supports great features. Few of them are listed below −

Sr.No. Feature & Description

1 Beautiful UI

Android OS basic screen provides a beautiful and intuitive user interface.

2 Connectivity

GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX.

3 Storage

SQLite, a lightweight relational database, is used for data storage purposes.

4 Media support

H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP.

5 Messaging

SMS and MMS

6 Web browser

Based on the open-source WebKit layout engine, coupled with Chrome’s V8 JavaScript engine supporting HTML5 and CSS3.

7 Multi-touch

Android has native support for multi-touch which was initially made available in handsets such as the HTC Hero.

8 Multi-tasking

User can jump from one task to another and same time various application can run simultaneously.

9 Resizable widgets

Widgets are resizable, so users can expand them to show more content or shrink them to save space.

10 Multi-Language

Supports single direction and bi-directional text.

11 GCM

Google Cloud Messaging (GCM) is a service that lets developers send short message data to their users on Android devices, without needing a proprietary sync solution.

12 Wi-Fi Direct

A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-peer connection.

13 Android Beam

A popular NFC-based technology that lets users instantly share, just by touching two NFC-enabled phones together.

Android applications are usually developed in the Java language using the Android Software Development Kit.

Once developed, Android applications can be packaged easily and sold out either through a store such as Google Play ,

SlideME , Opera Mobile Store , Mobango, F-droid and the

Amazon Appstore .

Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It’s the largest installed base of any mobile platform and growing fast. Every day more than 1 million new Android devices are activated worldwide.

This tutorial has been written with an aim to teach you how to develop and package Android application. We will start from environment setup for Android application programming and then drill down to look into various aspects of Android applications.

There are many android applications in the market. The top categories are −

The code names of android ranges from A to N currently, such as Aestro, Blender, Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat, Lollipop and Marshmallow. Let’s understand the android history in a sequence.

API Level is an integer value that uniquely identifies the framework API revision offered by a version of the Android platform.

Platform Version

API Level

VERSION_CODE

Android 6.0

23 MARSHMALLOW

Android 5.1

22 LOLLIPOP_MR1

Android 5.0

21 LOLLIPOP

Android 4.4W

20 KITKAT_WATCH KitKat for Wearables Only

Android 4.4

19 KITKAT

Android 4.3

18 JELLY_BEAN_MR2

Android 4.2, 4.2.2

17 JELLY_BEAN_MR1

Android 4.1, 4.1.1

16 JELLY_BEAN

Android 4.0.3, 4.0.4

15 ICE_CREAM_SANDWICH_MR1

Android 4.0, 4.0.1, 4.0.2

14 ICE_CREAM_SANDWICH

Android 3.2

13 HONEYCOMB_MR2

Android 3.1.x

12 HONEYCOMB_MR1

Android 3.0.x

11 HONEYCOMB

Android 2.3.4

Android 2.3.3

10 GINGERBREAD_MR1

Android 2.3.2

Android 2.3.1

Android 2.3

9 GINGERBREAD

Android 2.2.x

8 FROYO

Android 2.1.x

7 ECLAIR_MR1

Android 2.0.1

6 ECLAIR_0_1

Android 2.0

5 ECLAIR

Android 1.6

4 DONUT

Android 1.5

3 CUPCAKE

Android 1.1

2 BASE_1_1

Android 1.0

1 BASE

What is Android ?

Why Android ?

Features of Android

Android Applications

Categories of Android applications

History of Android

android core building blocks

​Android Core Building Blocks

An android component is simply a piece of code that has a well defined life cycle e.g. Activity, Receiver, Service etc.

The core building blocks or fundamental components of android are activities, views, intents, services, content providers, fragments and AndroidManifest.xml.

Activity

An activity is a class that represents a single screen. It is like a Frame in AWT.

View

A view is the UI element such as button, label, text field etc. Anything that you see is a view.

Intent

Intent is used to invoke components. It is mainly used to:

Start the service

Launch an activity

Display a web page

Display a list of contacts

Broadcast a message

Dial a phone call etc.
Service

Service is a background process that can run for a long time.

There are two types of services local and remote. Local service is accessed from within the application whereas remote service is accessed remotely from other applications running on the same device.

Content Provider

Content Providers are used to share data between the applications.

Fragment

Fragments are like parts of activity. An activity can display one or more fragments on the screen at the same time.

AndroidManifest.xml

It contains informations about activities, content providers, permissions etc. It is like the web.xml file in Java EE.

Android Virtual Device (AVD)

It is used to test the android application without the need for mobile or tablet etc. It can be created in different configurations to emulate different types of real devices.

android architecture

​Android Architecture

android architecture or Android software stack is categorized into five parts:

1. linux kernel

2. native libraries (middleware),

3. Android Runtime

4. Application Framework

5. Applications

Let’s see the android architecture first.

1) Linux kernel

It is the heart of android architecture that exists at the root of android architecture. Linux kernel is responsible for device drivers, power management, memory management, device management and resource access.

2) Native Libraries

On the top of linux kernel, their are Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media, C runtime library (libc) etc.

The WebKit library is responsible for browser support, SQLite is for database, FreeType for font support, Media for playing and recording audio and video formats.

3) Android Runtime

In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is responsible to run android application. DVM is like JVM but it is optimized for mobile devices. It consumes less memory and provides fast performance.

4) Android Framework

On the top of Native libraries and android runtime, there is android framework. Android framework includes Android API’s such as UI (User Interface), telephony, resources, locations, Content Providers (data) and package managers. It provides a lot of classes and interfaces for android application development.

5) Applications

On the top of android framework, there are applications. All applications such as home, contact, settings, games, browsers are using android framework that uses android runtime and libraries. Android runtime and native libraries are using linux kernal.

History of android

​History of Android

The history and versions of android are interesting to know. The code names of android ranges from A to J currently, such as Aestro, Blender , Cupcake, Donut ,

Eclair, Froyo , Gingerbread , Honeycomb , Ice Cream Sandwitch, Jelly Bean, KitKat and Lollipop . Let’s understand the android history in a sequence.

1) Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United States in October, 2003.

2) In 17th August 2005, Google acquired android Incorporation. Since then, it is in the subsidiary of Google Incorporation.

3) The key employees of Android Incorporation are

Andy Rubin, Rich Miner , Chris White and Nick Sears.

4) Originally intended for camera but shifted to smart phones later because of low market for camera only.

5) Android is the nick name of Andy Rubin given by coworkers because of his love to robots.

6) In 2007, Google announces the development of android OS.

7) In 2008, HTC launched the first android mobile.

Android Versions, Codename and API

Let’s see the android versions, codenames and API Level provided by Google.

Version Code name API Level

1.5 Cupcake 3

1.6 Donut 4

2.1 Eclair 7

2.2 Froyo 8

2.3 Gingerbread 9 and 10

3.1 and 3.3 Honeycomb 12 and 13

4.0 Ice Cream Sandwitch

15

4.1, 4.2 and 4.3

Jelly Bean 16, 17 and 18

4.4 KitKat 19

5.0 Lollipop 21

what is android

​What is Android

Before learning all topics of android, it is required to know what is android.

Android is a software package and linux based operating system for mobile devices such as tablet computers and smartphones.

It is developed by Google and later the OHA (Open Handset Alliance). Java language is mainly used to write the android code even though other languages can be used.

The goal of android project is to create a successful real-world product that improves the mobile experience for end users.

There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream Sandwich, Froyo, Ecliar, Donut etc which is covered in next page.

What is Open Handset Alliance (OHA)

It’s a consortium of 84 companies such as google, samsung, AKM, synaptics, KDDI, Garmin, Teleca, Ebay, Intel etc.

It was established on 5th November, 2007, led by Google. It is committed to advance open standards, provide services and deploy handsets using the Android Plateform.

Features of Android

After learning what is android, let’s see the features of android. The important features of android are given below:

1) It is open-source.

2) Anyone can customize the Android Platform.

3) There are a lot of mobile applications that can be chosen by the consumer.

4) It provides many interesting features like weather details, opening screen, live RSS (Really Simple Syndication) feeds etc.

It provides support for messaging services(SMS and MMS), web browser, storage (SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout etc.

Categories of Android applications

There are many android applications in the market. The top categories are:

Entertainment

Tools

Communication

Productivity

Personalization

Music and Audio

Social

Media and Video

Travel and Local etc.

Publishing android application

Publishing Android Application

Android application publishing is a process that makes your Android applications available to users. Infact, publishing is the last phase of the Android application development process.

Once you developed and fully tested your Android Application, you can statselling or distributing free using Google Play (A famous Android marketplace). You can also release your applications by sending them directly to users or by letting users download them from your own website.

You can check a detailed publishing process at Android official website, but this tutorial will take you through simple steps to launch your application on Google Play. Here is a simplified check list which will help you in launching your Android application:

Step

Activity

1

Regression Testing Before you publish your application, you need to make sure that itsmeeting the basic quality expectations for all Android apps, on all of the devices that you are targeting. So perform all the required testing on different devices including phone and tablets.

2

Application Rating When you will publish your application at Google Play, you will have to specify a content rating for your app, which informs Google Play users of its maturity level. Currently available ratings are (a) Everyone (b) Low maturity (c) Medium maturity (d) High maturity.

3

Targeted Regions Google Play lets you control what countries and territories where your application will be sold. Accordingly you must take care of setting up time zone, localization or any other specific requirement as per the targeted region.

4

Application Size Currently, the maximum size for an APK published on Google Play is 50 MB. If your app exceeds that size, or if you want to offer a secondary download, you can use APK Expansion Files, which Google Play will host for free on its server infrastructure and automatically handle the download to devices.

5

SDK and Screen CompatibilityIt is important to make sure that your app is designed to run properly on the Android platform versions and device screen sizes that you want to target.

6

Application Pricing Deciding whether you app will be free or paid is important because, on Google Play, free apps must remain free. If you want to sell your application then you will have to specify its price in different currencies.

7

Promotional Content It is a good marketing practice to supply a variety of high-quality graphic assets to showcase your app or brand. After you publish, these appear on your product details page, in store listings and search results, and elsewhere.

8

Build and Upload release-ready APK The release-ready APK is what you you will upload to the Developer Console and distribute to users. You can check complete detail on how to create a release-ready version of your app:Preparing for Release.

9

Finalize Application DetailGoogle Play gives you a variety of ways to promote your app and engage with users on your product details page, from colorful graphics, screenshots, and videos to localized descriptions, release details, and links to your other apps. So you can decorate your application page and provide as much as clear crisp detail you can provide.

Export Android Application

You will need to export your application as an APK (Android Package) file before you upload it Google Play marketplace.

To export an application, just open that application project in Eclipse and selectFile->Export from your Eclipse and follow the simple steps to export your application:

Next select, Export Android Application option as shown in the above screen shot and then click Nextand again Next so that you get following screen where you will chooseCreate new keystore to store your application.

Enter your password to protect your application and click on Next button once again. It will display followigscreen to let you create a key for your application:

Once you filled up all the information, click Next button and finally it will ask you a location where Application will be exported:

Finally, you click on Finish button to generate your Android Application Package File which will be uploaded at Google Play marketplace.

Google Play Registration

The most important step is to register with Google Play using Google Play Marketplace. You can use your existinggoogle ID if you have any otherwise you can create a new Google ID and then register with the marketplace. You will have following screen to accept terms and condition.

You can use Continue to paymentbutton to proceed to make a payment of $25 as a registration fee and finally to complete your account detail.

Once you are a registered user at Google Play, you can upload release-ready APK for your application and finally you will complete application detail using application detail page as mentioned in step 9 of the above mentioned checklist.

Android phone calls

Android Phone Calls

As such every Android Device especially Mobile phone is meant to provide a functionality to make a phone call but still you may need to write an application where you want to give an option to your user to make a call using a hard coded phone number.

This chapter lists down all the simple steps to create an application which can be used to make a Phone Call. You can use Android Intent to make phone call by calling built-in Phone Call functionality of the Android. Following section explains different parts of our Intent object required to make a call.

Intent Object – Action to make Phone Call

You will use ACTION_CALL action to trigger built-in phone call functionality available in Android device. Following is simple syntax to create an intent with ACTION_CALL action

Intent phoneIntent = new Intent(Intent.ACTION_CALL);

You can use ACTION_DIAL action instead of ACTION_CALL, in that case you will have option to modify hardcoded phone number before making a call instead of making a direct call.

Intent Object – Data/Type to make Phone Call

To make a phone call at a given number 91-800-001-0101, you need to specify tel: as URI using setData() method as follows:

phoneIntent.setData(Uri.parse("tel:91-800-001-0101"));

The interesting point is that, to make a phone call, you do not need to specify any extra data or data type.

Example

Following example shows you in practical how to use Android Intent to make phone call to the given mobile number.

To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work.

 

Step

Description

1

You will use Eclipse IDE to create an Android application and name it as PhoneCallDemo under a packagecom.example.phonecalldemo. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.

2

Modify src/MainActivity.java file and add required code to take care of making a call.

3

Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I’m adding a simple button to Call 91-800-001-0101 number

4

Modify res/values/strings.xml to define required constant values

5

Modify AndroidManifest.xml as shown below

6

Run the application to launch Android emulator and verify the result of the changes done in theaplication.

Following is the content of the modified main activity file src/com.example.phonecalldemo/MainActivity.java.

package com.example.phonecalldemo;
 
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
 
      Button startBtn = (Button) findViewById(R.id.makeCall);
      startBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
         makeCall();
      }
   });
 
   }
   protected void makeCall() {
      Log.i("Make call", "");
 
      Intent phoneIntent = new Intent(Intent.ACTION_CALL);
      phoneIntent.setData(Uri.parse("tel:91-800-001-0101"));
 
      try {
         startActivity(phoneIntent);
         finish();
         Log.i("Finished making a call...", "");
      } catch (android.content.ActivityNotFoundException ex) {
         Toast.makeText(MainActivity.this,
         "Call faild, please try again later.", Toast.LENGTH_SHORT).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.main, menu);
      return true;
   }
}

Following will be the content of res/layout/activity_main.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >
 
   <Button android:id="@+id/makeCall"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/make_call"/>
   
</LinearLayout>

Following will be the content of res/values/strings.xml to define two new constants:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">PhoneCallDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="make_call">Call 91-800-001-0101</string>
 
</resources>

Following is the default content ofAndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.phonecalldemo"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   <uses-permission android:name="android.permission.CALL_PHONE" />
   <uses-permission android:name="android.permission.READ_PHONE_STATE" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.phonecalldemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Let’s try to run your PhoneCallDemoapplication. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.

Selct your mobile device as an option and then check your mobile device which will display following screen:

Now use Call 91942-347-6192 button to make phone call.

Android sending sms

Android Sending SMS

There are following two ways to send SMS using Android device:

  • Using SmsManager to send SMS
  • Using Built-in Intent to send SMS

Using SmsManager to send SMS

The SmsManager manages SMS operations such as sending data to the given mobile device. You can create this object by calling the static methodSmsManager.getDefault() as follows:

SmsManager smsManager = SmsManager.getDefault();

Once you have SmsManager object, you can use sendDataMessage() method to send SMS at the specified mobile number as below:

smsManager.sendTextMessage("phoneNo", null, "SMS text", null, null);

Apart from the above method, there are few other important functions available in SmsManager class. These methods are listed below:

S.N.

Method & Description

1

ArrayList<String>divideMessage(String text) 
This method divides a message text into several fragments, none bigger than the maximum SMS message size.

2

static SmsManager getDefault() 
This method is used to get the default instance of the SmsManager

3

void sendDataMessage(StringdestinationAddress, StringscAddress, short destinationPort, byte[] data, PendingIntentsentIntentPendingIntentdeliveryIntent) 
This method is used to send a data based SMS to a specific application port.

4

voidsendMultipartTextMessage(StringdestinationAddress, StringscAddressArrayList<String> parts, ArrayList<PendingIntent>sentIntents,ArrayList<PendingIntent>deliveryIntents) 
Send a multi-part text based SMS.

5

void sendTextMessage(StringdestinationAddress, StringscAddress, String text,PendingIntent sentIntent,PendingIntent deliveryIntent) 
Send a text based SMS.

Example

Following example shows you in practical how to use SmsManagerobject to send an SMS to the given mobile number.

To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work.

Step

Description

1

You will use Eclipse IDE to create an Android application and name it as SendSMSDemo under a packagecom.example.sendsmsdemo. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.

2

Modify src/MainActivity.java file and add required code to take care of sending email.

3

Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I’m adding a simple GUI to take mobile number and SMS text to be sent and a simple button to send SMS.

4

Modify res/values/strings.xml to define required constant values

5

Modify AndroidManifest.xml as shown below

6

Run the application to launch Android emulator and verify the result of the changes done in theaplication.

Following is the content of the modified main activity file src/com.example.sendsmsdemo/MainActivity.java.

package com.example.sendsmsdemo;
 
import android.os.Bundle;
import android.app.Activity;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
   Button sendBtn;
   EditText txtphoneNo;
   EditText txtMessage;
 
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
 
      sendBtn = (Button) findViewById(R.id.btnSendSMS);
      txtphoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
      txtMessage = (EditText) findViewById(R.id.editTextSMS);
 
      sendBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            sendSMSMessage();
         }
      });
 
   }
   protected void sendSMSMessage() {
      Log.i("Send SMS", "");
 
      String phoneNo = txtphoneNo.getText().toString();
      String message = txtMessage.getText().toString();
 
      try {
         SmsManager smsManager = SmsManager.getDefault();
         smsManager.sendTextMessage(phoneNo, null, message, null, null);
         Toast.makeText(getApplicationContext(), "SMS sent.",
         Toast.LENGTH_LONG).show();
      } catch (Exception e) {
         Toast.makeText(getApplicationContext(),
         "SMS faild, please try again.",
         Toast.LENGTH_LONG).show();
         e.printStackTrace();
      }
   }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
}

Following will be the content of res/layout/activity_main.xml file:

<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:id="@+id/textViewPhoneNo"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/phone_label" />
 
   <EditText
   android:id="@+id/editTextPhoneNo"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:inputType="phone"/>
 
   <TextView
   android:id="@+id/textViewMessage"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/sms_label" />
 
   <EditText
   android:id="@+id/editTextSMS"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:inputType="textMultiLine"/>
 
   <Button android:id="@+id/btnSendSMS"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/send_sms_label"/>
 
</LinearLayout>

Following will be the content of res/values/strings.xml to define two new constants:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">SendSMSDemo</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="phone_label">Enter Phone Number:</string>
    <string name="sms_label">Enter SMS Message:</string>
    <string name="send_sms_label">Send SMS</string>
   
</resources>

Let’s try to run your SendSMSDemoapplication. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which will display following screen:

Now you can enter a desired mobile number and a text message to be sent on that number. Finally click on SedSMS button to send your SMS. Make sure your GSM connection is working fine to deliver your SMS to its recipient.

You can take a number of SMS separated by comma and then inside your program you will have to parse them into an array string and finally you can use a loop to send message to all the given numbers. That’s how you can write your own SMS client. Next section will show you how to use existing SMS client to send SMS.

Using Built-in Intent to send SMS

You can use Android Intent to send SMS by calling built-in SMS functionality of the Android. Following section explains different parts of our Intent object required to send an SMS.

Intent Object – Action to send SMS

You will use ACTION_VIEW action to launch an SMS client installed on your Android device. Following is simple syntax to create an intent with ACTION_VIEW action

Intent smsIntent = new Intent(Intent.ACTION_VIEW);

Intent Object – Data/Type to send SMS

To send an SMS you need to specifysmsto: as URI using setData() method and data type will be to vnd.android-dir/mms-sms using setType() method as follows:

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");

Intent Object – Extra to send SMS

Android has built-in support to add phone number and text message to send an SMS as follows:

smsIntent.putExtra("address"  , new String("0123456789;3393993300"));
smsIntent.putExtra("sms_body"  , "Test SMS to Angilla");

Example

Following example shows you in practical how to use Intent object to launch SMS client to send an SMS to the given recipients.

To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work.

Step

Description

1

You will use Eclipse IDE to create an Android application and name it as SendSMSDemo under a packagecom.example.sendsmsdemo. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.

2

Modify src/MainActivity.java file and add required code to take care of sending SMS.

3

Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I’m adding a simple button to launch SMS Client.

4

Modify res/values/strings.xml to define required constant values

5

Modify AndroidManifest.xml as shown below

6

Run the application to launch Android emulator and verify the result of the changes done in theaplication.

Following is the content of the modified main activity file src/com.example.sendsmsdemo/MainActivity.java.

package com.example.sendsmsdemo;
 
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
 
      Button startBtn = (Button) findViewById(R.id.sendSMS);
      startBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
         sendSMS();
      }
   });
 
   }
   protected void sendSMS() {
      Log.i("Send SMS", "");
 
      Intent smsIntent = new Intent(Intent.ACTION_VIEW);
      smsIntent.setData(Uri.parse("smsto:"));
      smsIntent.setType("vnd.android-dir/mms-sms");
 
      smsIntent.putExtra("address"  , new String ("0123456789"));
      smsIntent.putExtra("sms_body"  , "Test SMS to Angilla");
      try {
         startActivity(smsIntent);
         finish();
         Log.i("Finished sending SMS...", "");
      } catch (android.content.ActivityNotFoundException ex) {
         Toast.makeText(MainActivity.this,
         "SMS faild, please try again later.", Toast.LENGTH_SHORT).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.main, menu);
      return true;
   }
}

Following will be the content of res/layout/activity_main.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >
 
   <Button android:id="@+id/sendSMS"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/compose_sms"/>
   
</LinearLayout>

Following will be the content of res/values/strings.xml to define two new constants:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">SendSMSDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="compose_sms">Compose SMS</string>
 
</resources>

Following is the default content ofAndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sendsmsdemo"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.sendsmsdemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Let’s try to run your SendSMSDemoapplication. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which will display following screen:

Now use Compose SMS button to launch Android built-in SMS clients which is shown below

You can modify either of the given default fields and finally use send SMS button (marked with red rectangle) to send your SMS to the mentioned recipient.