0% found this document useful (0 votes)
36 views27 pages

Mad Unit-4

This document provides an overview of Android Services, including types such as Foreground, Background, and Bound Services, along with their lifecycle and methods. It also covers Intent Services, multi-threading concepts like Handlers and AsyncTasks, and Broadcast Receivers for system-wide event handling. The document includes code examples for implementing services and handling communication between activities and services.

Uploaded by

lavanya naren007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views27 pages

Mad Unit-4

This document provides an overview of Android Services, including types such as Foreground, Background, and Bound Services, along with their lifecycle and methods. It also covers Intent Services, multi-threading concepts like Handlers and AsyncTasks, and Broadcast Receivers for system-wide event handling. The document includes code examples for implementing services and handling communication between activities and services.

Uploaded by

lavanya naren007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

UNIT IV:ANDROID SERVICES

INDEX:

Services: Introduction to services – Local service – Remote service –


Binding the service –Communication between service and activity
–Intent Service – Multi–Threading: Handlers – AsyncTask– Android network programming:
HttpUrlConnection– Conn based Web services –Broad cast receivers :
Local Broadcast Manage Dynamicbroadcastreceiver – System Broadcast –Telephony Manager :
Sending SMS and making calls.

Introduction to services

What is Service?

Service is a component which keeps an app running in the background to perform long-
running operations based on our requirements.

For Service, we don't have any user interface and it will run the apps in the background
like playing the music in the background or handle network operations when the user in a different
app, interacting content providers.

The android.app.Service is subclass of Context Wrapper class.


MOBILE APPLICATION DEVELOPMENT
Characteristics of services

 Started with an Intent.


 Can stay running when user switches applications.
 Lifecycle—which you must manage.
 Other apps can use the service—manage permissions.

Types of Android Services

1. Foreground Services:

Foreground services are those services that are visible to the


users.
The users can interact with them at easily and track what’s
MOBILE APPLICATION DEVELOPMENT
happening.
These services continue to run even when users are using otherapplications.
Foreground services have own lifecycle that independent from activity or fragment that they
were created.

Example

-Music Player App(notification of the current song)


-Fitness App(show the distance that user has traveled)

2. Background Services:
These services run in the background, such that the user can’t
see or access them.

These are the tasks that don’t need the user to know them.

Background services have own lifecycle that independent fromactivity or fragment that they
were created.

Example

-Syncing and Storing data


3. Bound Services
This type of android service allows the components of the application like activity or
Fragments to bound themselves with it.

Bound services perform their task as long as any applicationcomponent is bound to it.

Many components can bind to one service at a time, but once theyall unbind, the service will
destroy.

In order to bind an application component with a service

bindservice () method is used.

Bound services have no own lifecycle.That’s why, they use


the lifecycle of the activity or fragment they were bounded.

Lifecycle of Android Services

The life cycle of service will follow two different paths


MOBILE APPLICATION DEVELOPMENT
1. Started Service

2. Bound Service

1. Started Service

A service is Started when an application component, such as an activity calls


startService() method.

Once it started, it will run indefinitely in background even if the component that started is
destroyed.

This service can be stopped only in one of the two cases:

 By using the stopService() method.

 By stopping itself using the stopSelf() method.

2. Bound Service

A service is bound when an application component binds to it bycalling bindService().

A bound service offers a client-server interface that allows components to interact with the
service, send requests, get results, and even do so across processes with interprocess communication
(IPC).

This service runs in the background as long as another application isbound to it.

Or it can be unbound according to our requirement by using the unbindService() method.


MOBILE APPLICATION DEVELOPMENT

Methods of Android Services

The service base class defines certain callback methods to performoperations on applications.

The following are a few important methods of Android services :

 onStartCommand()
 onBind()
 onCreate()
 onUnbind()
 onDestroy()
 onRebind()
MOBILE APPLICATION DEVELOPMENT

S.No. Callback & Description

1
onStartCommand()
The system calls this method when another component, such as an activity, requests
that the service be started, by calling startService().
If you implement this method, it is your responsibility to stop the service when its work is
done, by calling stopSelf() or stopService() methods.

2
onBind()
The system calls this method when another component wants to bind with the service by
calling bindService().
If you implement this method, you must provide an interface that clients use to communicate
with the service, by returning an IBinder object.
You must always implement this method, but if you don't want to allow binding, then you
should return null.

3
onUnbind()
The system calls this method when all clients have disconnected from a particular interface
published by the service.

4
onRebind()
The system calls this method when new clients have connected to the service, after it had
previously been notified that all had disconnected in its onUnbind(Intent).

5
onCreate()
The system calls this method when the service is first created
using onStartCommand() or onBind().
MOBILE APPLICATION DEVELOPMENT

This call is required to perform one-time set-up.

6
onDestroy()
The system calls this method when the service is no longer used and isbeing destroyed.
Your service should implement this to clean up any resources such as threads, registered
listeners, receivers, etc.

Communication between Activity and Service in Android

activity_main.xml:

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="MainActivity">
<Button android:id="@+id/buttonStart" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" android:layout_marginTop="74dp" android:text="Start
Service" />
<Button android:id="@+id/buttonStop" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="Stop
Service" />
</RelativeLayout>

Service class:(File: MyService.java)


import android.app.Service; import android.content.Intent;
import android.media.MediaPlayer;import android.os.IBinder;
import android.support.annotation.Nullable;import android.widget.Toast;
public class MyService extends Service {MediaPlayer myPlayer;
@Nullable@Override
public IBinder onBind(Intent intent) {return null;
}
@Override
public void onCreate() { Toast.makeText(this, "Service Created",Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.song);myPlayer.setLooping(false);
MOBILE APPLICATION DEVELOPMENT
}
@Override
public void onStart(Intent intent, int startId) { Toast.makeText(this, "Service Started",
Toast.LENGTH_LONG).show(); myPlayer.start();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped",Toast.LENGTH_LONG).show(); myPlayer.stop();
}
}

MainActivity.java
import android.content.Intent; import android.os.Bundle; import android.view.View; import
android.widget.Button;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implementsView.OnClickListener {
Button buttonStart, buttonStop;@Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); buttonStart = findViewById(R.id.buttonStart); buttonStop
= findViewById(R.id.buttonStop); buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
public void onClick(View src) {switch (src.getId()) {
case R.id.buttonStart:
startService(new Intent(this, MyService.class)); break;
case R.id.buttonStop:
stopService(new Intent(this, MyService.class)); break;
}
}}

AndroidManifest.xml:

In the AndroidManifest.xml file, we will declare the service.

<service
android:name=".MyService" android:enabled="true" android:exported="true"></service>

Output:
MOBILE APPLICATION DEVELOPMENT

Intent services

The Service is the base class for the IntentService.

It uses “work queue process” pattern where


the IntentService handles the on-demand requests (expressed as Intents)of clients.

The Service will be started whenever a client sends a request, and it will be stopped after
each Purpose has been addressed.

Clients can send the request to start a Service byusing Context.startService(Intent).

Here, a worker thread is created and all requests are handled using the worker thread but at a
time, only one request will be processed.

To use IntentService you have to extend the IntentService and implement the
onHandleIntent(android.content.Intent).

Features of Intent Services

1. Thread management: It automatically processes all incoming requests in a separate thread taking
the burden of thread management away fromthe developer.

2. Request Queue: It queues up all the incoming requests and they areprocessed one by one
MOBILE APPLICATION DEVELOPMENT
3. Stop point: Once the request Queue is empty it automatically stops itself, so the developer need
not worry about handling the service lifecycle.

Difference Between Service and IntentService

Service IntentService

You can use Service for the tasks that don’t If you want some background task to be performed
require any UI and also it is not a very long for a very long period oftime, then you should use
running task. the IntentService.

To start a Service you need to call the To start the IntentService by calling
onStartService() Context.startService(Intent)
method

Service always runs on the Mainthread The IntentService runs on a separate Worker
thread

There is a chance of blocking the main thread Tasks will be performed on a queue basis i.e,First
come first serve basis.

Easy to interact with UI of theapplication Difficult to interact with UI of theapplication

To stop service we have to No need to stop the service, it will stop


use stopService() or stopSelf() automatically.

Multi–Threading

Working on multiple tasks at the same time is Multitasking.

Multiple threads running at the same time in a machine iscalled Multi-Threading.

A thread is a unit of a process. Multiple such threads combine toform a process.

This means when a process is broken, the equivalent number ofthreads are available.
MOBILE APPLICATION DEVELOPMENT
Threading in Android

In Android, you can categorize all threading components into two basiccategories:

1. Threads that are attached to an activity/fragment: These threads are tied to the lifecycle of the
activity/fragment and are terminated assoon as the activity/fragment is destroyed.
2. Threads that are not attached to any activity/fragment: These threads can continue to run beyond
the lifetime of the activity/fragment (if any) from which they were spawned.
MOBILE APPLICATION DEVELOPMENT

Handler in android

A Handler is a threading class defined in thethrough which android.os package


we can send and
process and objects associated with a
Message Runnable
thread’s MessageQueue .
MOBILE APPLICATION DEVELOPMENT

Uses of Handler

In android Handler is mainly used to update the main thread from background thread or other than
main thread. There are two methods are inhandler.

 Post() − it going to post message from background thread to


main thread using looper.
 sendmessage() − if you want to organize what you have sent to ui (message from background thread)
or ui functions. you shoulduse sendMessage().

Handler is a class fundamental to how we do threading in android, at the infrastructure level. It


works hand in hand with the Looper.

Looper
will take care of dispatching work on its message-loop

thread. On the other hand Handler will serve two roles:

1. First it will provide an interface to submit messages to itsLooper queue.

2. Secondly it will implement the callback for processing thosemessages when they are dispatched
by the Looper

Example for Handler

Write Ex no 6

AsyncTask

Android AsyncTask is an abstract class provided by Android which gives us the liberty to
perform heavy tasks in the background and keep the UI thread light thus making the application more
responsive.

Android application runs on a single thread when launched.

Due to this single thread model tasks that take longer time to fetchthe response can make the
application non-responsive.

To avoid this we use android AsyncTask to perform the heavy tasks in background on a
dedicated thread and passing the results back to the UI thread.
MOBILE APPLICATION DEVELOPMENT
Hence use of AsyncTask in android application keeps the UI thread responsive at all times.

The basic methods used in an android AsyncTask class are definedbelow :

doInBackground() : This method contains the code which needs to be executed in background. In
this method we can send results

multiple times to the UI thread by publishProgress() method. To notify that the background
processing has been completed we justneed to use the return statements
onPreExecute() : This method contains the code which is executed before the background processing
starts
onPostExecute() : This method is called after doInBackground method completes processing. Result
from doInBackground is passedto this method
onProgressUpdate() : This method receives progress updates from doInBackground method, which
is published via publishProgress method, and this method can use this progress update to update the
UI thread

Generic Types in Async Task


 TypeOfVarArgParams − It contains information about what type of params used for execution.
 ProgressValue − It contains information about progress units. While doing background operation we
can update information on ui using onProgressUpdate().

 ResultValue −It contains information about result type.


AsyncTask Example

The following code must be present in the MainActivity class in order to launch an
AsyncTask.
MyTask myTask = new MyTask();myTask.execute();
The execute method is used to start the background thread in theexcerpt above, where we’ve
used a sample class name that extends AsyncTask.

public class MainActivity extends AppCompatActivity {@Override


protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); ExampleAsync task = new ExampleAsync;
task.execute(5);
MOBILE APPLICATION DEVELOPMENT

private static class ExampleAsync extends AsyncTask<Integer, Integer,String> {

@Override

protected void onPreExecute() {super.onPreExecute();

// ...

}
@Override

protected String doInBackground(Integer... integers) {


// ...

return "Finished!"; }@Override


protected void onProgressUpdate(Integer... values) {super.onProgressUpdate(values);
// ...
}

@Override
protected void onPostExecute(String string) {super.onPostExecute(string);

// ...

}
}
}
MOBILE APPLICATION DEVELOPMENT

Broad cast receivers

Broad cast

Broadcasts are messages that the Android system and Android appssend when events occur
that might affect the functionality of other apps.
For example, the Android system sends an event when the systemboots up, when power is
connected or disconnected, and when headphones are connected or disconnected.

Broadcasts are messaging components used for communicating across apps when events of
interest occur.
There are two types of broadcasts:

System broadcasts are delivered by the system.


Custom broadcasts are delivered by your app.

System broadcasts
A system broadcast is a message that the Android system sendswhen a system event occurs.
System broadcasts are wrapped in Intent objects.
The intent object's action field contains event details such
as android.intent.action.HEADSET_PLUG, which is sent when a wired headset is connected or
disconnected.
The intent can also contain more data about the event in its extra field, for example a
boolean extra indicating whether a headset is connected or disconnected.Examples:

When the device boots, the system broadcasts a system Intent with the action
ACTION_BOOT_COMPLETED.
When the device is disconnected from external power, the system sends a system Intent with the
action
field ACTION_POWER_DISCONNECTED.

Broadcast receivers

A Broadcast receiver (receiver) is an Android component which allows us to listens to


system-wide broadcast events or intents.

When any of these events occur it brings the application into action by either creating a status
bar notification or performing a task.
MOBILE APPLICATION DEVELOPMENT
For eg : a Broadcast receiver triggers battery Low notification that you see on your mobile
screen..

Broadcast receivers helps our app communicate with Android OS andother apps.

Two important steps to make Broadcast Receiver works for thesystem broadcasted items:

1. Creating the Broadcast Receiver.


2. Registering Broadcast Receiver.
1. Creating the Broadcast Receiver
To create a new Broadcast Receiver, we need to create a new class that extends the Broadcast
Receiver class. Then you can override the onReceive function of the class.

Syntax

Public class AirplaneModeReceiver extends BroadcastReceiver()

Override
Public void onReceive(context: Context, intent: Intent)

// body of the function

}
}

2.Registering Broadcast Receiver.

Register the broadcast receiver, either statically or dynamically.


MOBILE APPLICATION DEVELOPMENT

1. Statically (manifest-declared) - This receiver can be registered via the AndroidManifest.xml file.
2. Dynamically (context-registered) - This registers a receiver dynamically via the
Context.registerReceiver() method.

System wide generated intents and its Description

Following are some of the important system wide generated intents.

1. android.intent.action.BATTERY_LOW : Indicates low batterycondition on the device.


2. android.intent.action.BOOT_COMPLETED : This is broadcast once, after the system has finished
booting

3. android.intent.action.CALL : To perform a call to someone specifiedby the data


4. android.intent.action.DATE_CHANGED : The date has changed
5. android.intent.action.REBOOT : Have the device reboot
6. android.net.conn.CONNECTIVITY_CHANGE : The mobile network or wifi connection is
changed(or reset)

1. Static Broadcast Receivers


These types of Receivers are declared in the manifest file and workseven if the app is closed.
Manifest-declared receivers(Statically)

The registration is done in the manifest file, using <register> tags.

Firstly, specify the receiver in your manifest file.

<receiver android:name=".MyBroadcastReceiver"

android:exported="true">
<intent-filter>
<action
android:name="android.net.conn.CONNECTIVITY_CHANGE""/>

</intent-filter>
</receiver>
MOBILE APPLICATION DEVELOPMENT

Secondly, create class as a subclass of BroadcastReceiver class and overriding the onReceive()
method where each message is received as aIntent object parameter.

public class MyBroadcastReceiver extends BroadcastReceiver


{
@Override

public void onReceive(Context context, Intent intent)


{
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}

2. Dynamic Broadcast Receivers


These types of receivers work only if the app is active or minimized.
Context-registered receivers(Dynamically)

The registration is done using Context.registerReceiver() method.

Firstly, register broadcast receiver programmatically.

IntentFilter intentFilter = new IntentFilter();

intentFilter.addAction(getPackageName() +

"android.net.conn.CONNECTIVITY_CHANGE");

MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();


registerReceiver(myReceiver, filter);
MOBILE APPLICATION DEVELOPMENT
Secondly, To unregister a broadcast receiver in onStop() or onPause() of theactivity.

Android TelephonyManager

The android.telephony.TelephonyManager class provides information about the telephony


services such as subscriber id, sim serialnumber, phone network type etc.

activity_main.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" android:layout_marginLeft="38dp"
android:layout_marginTop="30dp" android:text="Phone Details:" />

</RelativeLayout>
MainActivity.java

import android.os.Bundle; import android.app.Activity; import android.content.Context;


import android.telephony.TelephonyManager;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {TextView textView1;


@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textView1=(TextView)findViewById(R.id.textView1);

//Get the instance of TelephonyManager


TelephonyManager tm=(TelephonyManager)getSystemService(Con
text.TELEPHONY_SERVICE);

//Calling the methods of TelephonyManager the returns the information


String IMEINumber=tm.getDeviceId();String subscriberID=tm.getDeviceId();
String SIMSerialNumber=tm.getSimSerialNumber(); String
networkCountryISO=tm.getNetworkCountryIso();String SIMCountryISO=tm.getSimCountryIso();
String softwareVersion=tm.getDeviceSoftwareVersion(); String
voiceMailNumber=tm.getVoiceMailNumber();
MOBILE APPLICATION DEVELOPMENT

String strphoneType="";

int phoneType=tm.getPhoneType();

switch (phoneType)
{
case (TelephonyManager.PHONE_TYPE_CDMA):strphoneType="CDMA";
break;
case (TelephonyManager.PHONE_TYPE_GSM):strphoneType="GSM";
break;
case (TelephonyManager.PHONE_TYPE_NONE):strphoneType="NONE";
break;
}
boolean isRoaming=tm.isNetworkRoaming();

String info="Phone Details:\n"; info+="\n IMEI Number:"+IMEINumber; info+="\n


SubscriberID:"+subscriberID;
info+="\n Sim Serial Number:"+SIMSerialNumber; info+="\n Network Country
ISO:"+networkCountryISO; info+="\n SIM Country ISO:"+SIMCountryISO; info+="\n Software
Version:"+softwareVersion; info+="\n Voice Mail Number:"+voiceMailNumber; info+="\n Phone
Network Type:"+strphoneType; info+="\n In Roaming? :"+isRoaming;

textView1.setText(info);//displaying the information in the textView


}

AndroidManifest.xml

<usespermission android:name="android.permission.READ_PHONE_STATE "/>

Output:
MOBILE APPLICATION DEVELOPMENT

Sending SMS and making callsSending SMS


Android devices can send and receive messages to or from any other phone that supports Short
Message Service (SMS).

Android offers the Messenger app that can send and receive SMSmessages.

//Getting intent and Pending Intent instance


Intent intent=new Intent(getApplicationContext(),MainActivity.class); PendingIntent
pi=PendingIntent.getActivity(getApplicationContext(),0, intent,0);

//Get the SmsManager instance and call the sendTextMessage method to send message
SmsManager sms=SmsManager.getDefault(); sms.sendTextMessage("8802177690", null, "hello
javatpoint", pi,null);

Example of sending sms in android

activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity" >

<EditText android:id="@+id/editText1" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_alignParentRight="true"
android:layout_alignParentTop="true" android:layout_marginRight="20dp" android:ems="10" />

<EditText android:id="@+id/editText2" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1" android:layout_marginTop="26dp" android:ems="10"
android:inputType="textMultiLine" />

<TextView android:id="@+id/textView1" android:layout_width="wrap_content"


android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1" android:layout_toLeftOf="@+id/editText1"
android:text="Mobile No:" />

<TextView android:id="@+id/textView2" android:layout_width="wrap_content"


android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2" android:layout_alignBottom="@+id/editText2"
android:layout_alignLeft="@+id/textView1" android:text="Message:" />

<Button
android:id="@+id/button1" android:layout_width="wrap_content"
MOBILE APPLICATION DEVELOPMENT
android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2" android:layout_marginLeft="34dp"
android:layout_marginTop="48dp" android:text="Send SMS" />

</RelativeLayout>

Write the permission code in Android-Manifest.xml file

You need to write SEND_SMS permission as given below:

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

package com.example.sendsms;

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

public class MainActivity extends Activity {EditText mobileno,message;


Button sendsms;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mobileno=(EditText)findViewById(R.id.editText1);
message=(EditText)findViewById(R.id.editText2); sendsms=(Button)findViewById(R.id.button1);

//Performing action on button click sendsms.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
String no=mobileno.getText().toString(); String msg=message.getText().toString();

//Getting intent and PendingIntent instance


Intent intent=new Intent(getApplicationContext(),MainActivity.class);

PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);

//Get the SmsManager instance and call the sendTextMessage methodto send message
SmsManager sms=SmsManager.getDefault();sms.sendTextMessage(no, null, msg, pi,null);
MOBILE APPLICATION DEVELOPMENT

Toast.makeText(getApplicationContext(), "Message Sent successfully!", Toast.LENGTH_LONG).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.activity_main, menu);
return true;
}

OUTPUT:
MOBILE APPLICATION DEVELOPMENT

Making calls

In android, we can easily make a phone call from our android applications by invoking built-in phone
calls app
using Intents action (ACTION_CALL).

To make a phone call using Intent object in android application, we need to write the code like as
shown below.

Intent callIntent = new Intent(Intent.ACTION_CALL);


callIntent.setData(Uri.parse("tel:"+8802177690));//change the number startActivity(callIntent);

Example of phone call in androidactivity_main.xml


<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity" >

<Button
android:id="@+id/button1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"android:layout_marginTop="118dp" android:text="Call" />

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentTop="true" android:layout_centerHorizontal="true"
android:layout_marginTop="25dp" android:ems="10" />

</RelativeLayout>

Write the permission code in Android-Manifest.xml file

You need to write CALL_PHONE permission as given below:

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

MainActivity.java

package com.example.phonecall;

import android.net.Uri; import android.os.Bundle; import android.app.Activity; import


android.content.Intent;import android.view.Menu; import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
MOBILE APPLICATION DEVELOPMENT

public class MainActivity extends Activity {EditText edittext1;


Button button1;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Getting the edittext and button instance edittext1=(EditText)findViewById(R.id.editText1);


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

//Performing action on button click button1.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
String number=edittext1.getText().toString();
Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:"+number));
startActivity(callIntent);
}

});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

OUTPUT:
MOBILE APPLICATION DEVELOPMENT

You might also like