Android Send SMS and Make a phone call in Android Application

By: Ashley Emailed: 1674 times Printed: 2156 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

This sample android program shows you how to use Telephony in Android. This program demonstrates how to send SMS from your Android application. This program also shows you how to make a phone call from your Android application or Dial a number using Intent. This tutorial therefore has four different java source files.

The main file Telephony1.java file is as follows:

package com.javasamples.Telephony1;

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;

/**
 * Explore telephony related functionality and APIs in Android.
 * 
 * @author charliecollins
 * 
 */
public class Telephony1 extends Activity {

//You could change this number to your own number.
//This number will be used to DIAL in the dial example.

    public static final String NUMBER = "555-123-1234";

    private Button dialintent;
    private Button callintent;
    private Button gotoSmsExample;
    private Button gotoPnUtilsExample;

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

        this.gotoSmsExample = (Button) findViewById(R.id.gotosms_button);
        this.gotoSmsExample.setOnClickListener(new OnClickListener() {

            public void onClick(final View v) {
                Intent intent = new Intent(Telephony1.this, SmsExample.class);
                startActivity(intent);
            }
        });

        this.gotoPnUtilsExample = (Button) findViewById(R.id.gotopnutils_button);
        this.gotoPnUtilsExample.setOnClickListener(new OnClickListener() {

            public void onClick(final View v) {
                Intent intent = new Intent(Telephony1.this, PhoneNumberUtilsExample.class);
                startActivity(intent);
            }
        });

        this.dialintent = (Button) findViewById(R.id.dialintent_button);
        this.dialintent.setOnClickListener(new OnClickListener() {

            public void onClick(final View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Telephony1.NUMBER));
                startActivity(intent);
            }
        });

        this.callintent = (Button) findViewById(R.id.callintent_button);
        this.callintent.setOnClickListener(new OnClickListener() {

            public void onClick(final View v) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Telephony1.NUMBER));
                startActivity(intent);
             //   Intent intent1 = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "1234"));
               // startActivity(intent1);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}


The code to Send SMS is in this file SmsExample.java :

package com.javasamples.SmsExample;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class SmsExample extends Activity {

    private EditText smsInputText;
    private EditText smsInputDest;
    private Button smsSend;
	private SmsManager smsManager;

    @Override
    public void onCreate(final Bundle icicle) {
        Log.d(Constants.LOGTAG, "SmsExample onCreate");

        super.onCreate(icicle);
        this.setContentView(R.layout.smsexample);

        this.smsInputDest = (EditText) findViewById(R.id.smsinputdest);
        this.smsInputText = (EditText) findViewById(R.id.smsinputtext);
        this.smsSend = (Button) findViewById(R.id.smssend_button);

        this.smsManager = SmsManager.getDefault();

        // pending intent request code NOT USED
        final PendingIntent sentIntent = PendingIntent.getActivity(this, 0, new Intent(this, SmsExample.class), 0);

        this.smsSend.setOnClickListener(new OnClickListener() {

            public void onClick(final View v) {
                Log.d(Constants.LOGTAG, "SmsExample sending SMS message via manager");

                String dest = smsInputDest.getText().toString();
                if (PhoneNumberUtils.isWellFormedSmsAddress(dest)) {

                    // dest, serviceCenter (null for default), message,
                    // sentIntent, deliveryIntent
                    //
                    // Set the second parameter to null. The scAddress relates
                    // to the address of the server on the cellular network that will handle
                    // the message, it is not the address of the sender.
                    smsManager.sendTextMessage(smsInputDest.getText().toString(), null, smsInputText.getText()
                        .toString(), sentIntent, null);

                    Toast.makeText(SmsExample.this, "SMS message sent", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(SmsExample.this, "SMS destination invalid - try again", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}


The code to handle some of the phone number formatting examples are in this file PhoneNumberUtilsExample.java :

package com.javasamples.PhoneNumberUtilsExample;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class PhoneNumberUtilsExample extends Activity {

    private TextView pnOutput;
    private EditText pnInput;
    private EditText pnInPlaceInput;
    private Button pnFormat;

    @Override
    public void onCreate(final Bundle icicle) {
        Log.d(Constants.LOGTAG, "PhoneNumberUtilsExample onCreate");

        super.onCreate(icicle);
        this.setContentView(R.layout.phonenumberutilsexample);

        this.pnOutput = (TextView) findViewById(R.id.pnoutput);
        this.pnInput = (EditText) findViewById(R.id.pninput);
        this.pnInPlaceInput = (EditText) findViewById(R.id.pninplaceinput);
        this.pnFormat = (Button) findViewById(R.id.pnformat);

        this.pnFormat.setOnClickListener(new OnClickListener() {

            public void onClick(final View v) {
                Log.d(Constants.LOGTAG, "PhoneNumberUtilsExample format TextView input - "
                    + pnInput.getText().toString());

                // format as a phone number FIRST
                String phoneNumber = PhoneNumberUtils.formatNumber(pnInput.getText().toString());
                // then convert phone number keypad alpha to numeric
                phoneNumber = PhoneNumberUtils.convertKeypadLettersToDigits(pnInput.getText().toString());

                StringBuilder result = new StringBuilder();
                result.append(phoneNumber);
                result.append("\nisGlobal - " + PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber));
                result.append("\nisEmergency - " + PhoneNumberUtils.isEmergencyNumber(phoneNumber));

                pnOutput.setText(result.toString());

                pnInput.setText("");
            }
        });

        this.pnInPlaceInput.setOnFocusChangeListener(new OnFocusChangeListener() {

            public void onFocusChange(final View v, final boolean b) {
                if (v.equals(pnInPlaceInput) && (b == false)) {
                    Log.d(Constants.LOGTAG, "PhoneNumberUtilsExample formatInPlace TextView input - "
                        + pnInPlaceInput.getText().toString());
                    PhoneNumberUtils.formatNumber(pnInPlaceInput.getText(), PhoneNumberUtils.FORMAT_NANP);
                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}


This is just a file to store some constants values

package com.sqlstar;

public class Constants {

    public static final String LOGTAG = "TelephonyExplorer";
}

For the resources you will have three different layouts and hence three xmls.

The main.xml file in your res/layout/ folder will be as follows

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_horizontal" android:padding="10px" android.setVerticalScrollBarEnabled="true" android:background="#000000">

<TextView android:id="@+id/intro_label_main" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="15px" android:layout_marginTop="15px" android:textStyle="bold" android:text="TelephonyExplorer" />

<Button android:id="@+id/gotopnutils_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/intro_label_main" android:layout_marginLeft="5px" android:layout_marginBottom="10px" android:text="PhoneNumberUtils Example" /> <Button android:id="@+id/gotosms_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/gotopnutils_button" android:layout_marginLeft="5px" android:layout_marginBottom="10px" android:text="SMS Example" />

<Button android:id="@+id/dialintent_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/gotosms_button" android:layout_marginLeft="5px" android:layout_marginBottom="5px" android:text="Dial via Intent" />

<Button android:id="@+id/callintent_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/dialintent_button" android:layout_marginLeft="5px" android:layout_marginBottom="20px" android:text="Call via Intent" />

</RelativeLayout>
</ScrollView>

The smsexample.xml file in your res/layout/ folder will be as follows

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_horizontal" android:padding="10px" android.setVerticalScrollBarEnabled="true" android:background="#000000">

<TextView android:id="@+id/intro_label_sms" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="15px" android:textStyle="bold" android:text="SMS Example" />

<TextView android:id="@+id/label_smsinputdest" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="5px" android:layout_below="@id/intro_label_sms" android:text="Enter destination number:" /> <EditText android:id="@+id/smsinputdest" android:layout_width="150dip" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="5px" android:layout_below="@id/label_smsinputdest" android:text="" />

<TextView android:id="@+id/label_smsinputtext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="5px" android:layout_below="@id/smsinputdest" android:text="Enter text to send:" /> <EditText android:id="@+id/smsinputtext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="5px" android:layout_below="@id/label_smsinputtext" android:text="" />

<Button android:id="@+id/smssend_button" android:layout_width="150dip" android:layout_height="wrap_content" android:layout_below="@id/smsinputtext" android:layout_marginLeft="10px" android:layout_marginBottom="10px" android:text="Send SMS" />

</RelativeLayout>
</ScrollView>

The phonenumberutilsexample.xml file in your res/layout/ folder will be as follows

<?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" android:gravity="center_horizontal" android:padding="10px" android.setVerticalScrollBarEnabled="true" android:background="#000000">

<TextView android:id="@+id/intro_label_pn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="15px" android:textStyle="bold" android:text="PhoneNumberUtils Example" /> <TextView android:id="@+id/label_pninput" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="5px" android:layout_below="@id/intro_label_pn" android:text="Input string to format:" /> <EditText android:id="@+id/pninput" android:layout_width="250dip" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="20px" android:layout_below="@id/label_pninput" android:text="" />

<Button android:id="@+id/pnformat" android:layout_width="150dip" android:layout_height="wrap_content" android:layout_below="@id/pninput" android:layout_marginLeft="10px" android:layout_marginBottom="10px" android:text="Format" />

<TextView android:id="@+id/label_pnoutput" android:layout_width="150dip" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="5px" android:layout_below="@id/pnformat" android:text="Formatting Results:" /> <TextView android:id="@+id/pnoutput" android:layout_width="150dip" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="25px" android:layout_below="@id/label_pnoutput" android:text="" />

<TextView android:id="@+id/label_pninplaceinput" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="5px" android:layout_below="@id/pnoutput" android:text="Edit in place phone number:" /> <EditText android:id="@+id/pninplaceinput" android:layout_width="250dip" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="5px" android:layout_below="@id/label_pninplaceinput" android:text="" />

<EditText android:id="@+id/pnnextfocus" android:layout_width="250dip" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginBottom="20px" android:layout_below="@id/pninplaceinput" android:text="Change focus to here to format previous field" />

</RelativeLayout>

Very importantly, you should add appropriate permissions in your AndroidManifest.xml file as below. Otherwise when you run the application you will get permission denied errors.

<?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sqlstar">

   <application android:icon="@drawable/icon">

   <activity android:name=".Telephony1" android:label="@string/app_name">

   <intent-filter>

   <action android:name="android.intent.action.MAIN" />

   <category android:name="android.intent.category.LAUNCHER" />

   </intent-filter>

   </activity> 

 <activity android:name=".PhoneNumberUtilsExample" android:label="@string/app_name" />
   <activity android:name=".SmsExample" android:label="@string/app_name" />

 </application> 

 <uses-permission android:name="android.permission.CALL_PHONE" />
   <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />

   <uses-permission android:name="android.permission.READ_PHONE_STATE" />

   <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />

   <uses-permission android:name="android.permission.RECEIVE_SMS" />

   <uses-permission android:name="android.permission.READ_SMS" />

   <uses-permission android:name="android.permission.WRITE_SMS" />

   <uses-permission android:name="android.permission.SEND_SMS" />

  </manifest>

The output of this program will be as shown in the android emulator below.


Android Home | All Android Tutorials | Latest Android Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(13)


1. View Comment

i wnt develope application on cal time send message if this application will run

View Tutorial          By: saurab at 2012-10-11 12:02:52
2. View Comment

very nice tutorial.. keep it up. cheers

can you share source code zip. will be more helpful for new user :)

Thanks in advance


View Tutorial          By: chanchal at 2013-01-24 06:54:23
3. View Comment

The code is running successfully.........but , I m not getting what exactly u have done ........means , call via intent and dial via intent ,these 2 options are of no use , after putting any no. on emulator, I was clicking green button for call and then it was appearing as if it was calling. I want a code for actual calling .plzzzz help me...post acode through which I can actually put real nos and can call on those nos. I want to run this application on actual mobile...

View Tutorial          By: Harshita at 2013-03-26 19:25:58
4. View Comment

@Harshita you cannot test the SMS and call features in emulator. You can copy the apk file to your android phone and test it. It will work there.

View Tutorial          By: Anonymous at 2013-03-28 01:32:47
5. View Comment

thanx a lot for this tutorial brother!!!!! a great help to noobs like me!!!! :-) :-)

View Tutorial          By: manas at 2013-04-01 17:18:00
6. View Comment

i'am having an error in main.xml in line RelativeLayout : Unexpected namespace prefix "xmlns" found for tag RelativeLayout. And line android.setVerticalScrollBarEnabled="true" : attribute is missing the Android namespace PREFIX. Can u help me please?

View Tutorial          By: Nova at 2013-04-18 11:21:06
7. View Comment

Hi, it looks great!
I'm just starting with Android programing and I dont see how to build the app from here.
I'm using Eclipse as an environnement, but I can't import.
Would you have the whole example in a zip hierarchy?

Thank you!
Bertrand


View Tutorial          By: Bertrand at 2013-04-28 19:20:42
8. View Comment

detailed article.
I found this one better than all other android call/sms tutorials.
+1


View Tutorial          By: Neo at 2013-05-04 16:42:12
9. View Comment

This is a good tutorial. Now how can I send SMS multiple times automatically to particular number or dial a number say 10 times for specific duration ?

View Tutorial          By: Alkesh at 2013-05-11 14:51:53
10. View Comment

Thanks alot ,,, it is really more the excellent n has answered my question .. keep it up !!! n thaks very much once again :)

View Tutorial          By: SaraFaqera at 2013-12-16 16:00:07
11. View Comment

How to execute above sqlstr file.

View Tutorial          By: shriyash at 2014-02-23 09:32:36
12. View Comment

very nice keep sharing thanks a lot

View Tutorial          By: Adeel at 2014-09-24 09:50:00
13. View Comment

how to run this code....... Please tell somebody mail @ (singhbakshi16@hotmail.com)

View Tutorial          By: Honey at 2015-01-24 14:27:38

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Ashley
Is autodiscover CNAME a must in Office 365
Directory Synchronization tool in Office 365
Configure Outlook Manually for Office 365
Review: Ruggear - The world's most Rugged Phone in Singapore
Solution to error: unable to open connection to server due to security error
Making your Alias email as 'Send As' in Office 365
Steps to Create Shared Mailbox in office 365
xxxx cannot be loaded because the execution of scripts is disabled on this system. Please see “get-help about_signing” for more details.
The user's Outlook Live mailbox is full.
Outlook Live couldn't connect to the IMAP server.
The user's mailbox has already been migrated.
An Outlook Live mailbox wasn't found for the user.
Outlook Live couldn't sign in to the user account on the IMAP messaging system.
Android Send SMS and Make a phone call in Android Application
Android Preferences - Using Preferences in Android Tutorial

More Tutorials in Android
Getting Started with Android
Solution to error: unable to open connection to server due to security error
Android Preferences - Using Preferences in Android Tutorial
Android Send SMS and Make a phone call in Android Application
Android Emulator
Intent in Android to call one activity from another activity.
Animation sample program in Android
Another Animation sample program in Android
ArrayAdapter sample program in Android
Spinner sample program in Android
GridView sample program in Android
Gallery sample program in Android
Date and Time sample program in Android
Progress bar and downloading a file sample program in Android
Reading a file sample program in Android

More Latest News
Most Viewed Articles (in Android )
Progress bar and downloading a file sample program in Android
Reading and Writing a file to SD card sample program in Android
ArrayAdapter sample program in Android
Spinner sample program in Android
Intent in Android to call one activity from another activity.
Reading a file sample program in Android
Android Send SMS and Make a phone call in Android Application
Date and Time sample program in Android
Solution to error: unable to open connection to server due to security error
GridView sample program in Android
Gallery sample program in Android
Animation sample program in Android
Android Emulator
Android Preferences - Using Preferences in Android Tutorial
Getting Started with Android
Most Emailed Articles (in Android)
Reading and Writing a file to SD card sample program in Android
AlertDialog sample program in Android
Android Preferences - Using Preferences in Android Tutorial
ArrayAdapter sample program in Android
GridView sample program in Android
Progress bar and downloading a file sample program in Android
Getting Started with Android
Another Animation sample program in Android
Spinner sample program in Android
Gallery sample program in Android
Reading a file sample program in Android
Android Emulator
Animation sample program in Android
Error generating R.java from manifest
Date and Time sample program in Android