0% found this document useful (0 votes)
8 views35 pages

Chapter 5

Chapter 5 discusses various communication methods available in Android, including telephony, SMS, Wi-Fi, and Bluetooth. It outlines how to utilize Android's APIs for making phone calls, sending SMS messages, and managing Bluetooth connections, as well as accessing network status through the ConnectivityManager class. Additionally, it provides examples of using intents to send emails and manage Bluetooth functionalities within Android applications.
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)
8 views35 pages

Chapter 5

Chapter 5 discusses various communication methods available in Android, including telephony, SMS, Wi-Fi, and Bluetooth. It outlines how to utilize Android's APIs for making phone calls, sending SMS messages, and managing Bluetooth connections, as well as accessing network status through the ConnectivityManager class. Additionally, it provides examples of using intents to send emails and manage Bluetooth functionalities within Android applications.
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/ 35

Chapter 5

Communications Via
Network and Web services
OUTLINES
 Telephony manager
 Phone Call
 SMS Message
 Wi-fi
 Bluetooth
 Notifications
 Alarms
Network and Web services

 Android provides access to networking in several ways, including mobile Internet Protocol
(IP), Wi-Fi, and Bluetooth.
 It also provides some open and closed source third party implementations of other networking
standards such as ZigBee and Worldwide Interoperability for Microwave Access (WiMAX).
 Android provides a portion of the java.net package and the org.apache.httpclient package to
support basic networking.
 Other related packages, such as android.net, address internal networking details and general
connectivity properties.
 In terms of connectivity properties using the ConnectivityManager class to determine when
the network connection is active and what type of connection it is: mobile or Wi-Fi.
Checking the network status
 Android provides a host of utilities that determine the device configuration and the status of
various services, including the network.
 Use the ConnectivityManager class to determine whether network connectivity exists and to get
notifications of network changes.
 The main Activity in the NetworkExplorer application, demonstrates basic usage of the
ConnectivityManager.
onStart method of the NetworkExplorer main Activity
@Override
public void onStart() {
super.onStart();
ConnectivityManager cMgr = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cMgr.getActiveNetworkInfo();
this.status.setText(netInfo.toString());
}
Cont..
 Network and web services are crucial components for dynamic Android applications.
 Android provides several ways to access networking and web services, including mobile
Internet Protocol (IP), Wi-Fi, and Bluetooth.
 Android Web Services is a standardized system that helps various applications and systems to
communicate with each other.
 Examples of network and web services in Android include Android Restful Web Service and
Android Network Connectivity Service.
 To work with network and web services in Android, you need to create network requests, parse
the data received from the server and then handle the response data in your app. This involves
creating network connections, handling response codes, and parsing response payloads.
Telephony
 Android phones support dialing numbers, receiving calls, sending and receiving text and
multimedia messages, and other related telephony services. In contrast to other smartphone
platforms, all these items are accessible to developers through simple-to-use APIs and built-in
applications.
 Telephony is a general term that refers to electrical voice communications over telephone
networks.
 The android.telephony.TelephonyManager class provides information about the telephony
services such as subscriber id, sim serial number, phone network type etc.
 Android Telephony framework provides us the functionalities of the mobile. It gives us information
about functionalities like calls, SMS, MMS, network, data services, IMEI number, and so on.
Example of how to use the TelephonyManager class in Android:
In manifest file add this: <uses-permission android:name="android.permission.READ_PHONE_STATE" />
Then create an instance of the TelephonyManager class and use its methods to access
information about the telephony services;
TelephonyManager telephonyManager =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
// Get the phone number of the device
String phoneNumber = telephonyManager.getLine1Number();
// Get the network operator name
String operatorName = telephonyManager.getNetworkOperatorName();
// Get the SIM card serial number
String simSerialNumber = telephonyManager.getSimSerialNumber();
// Get the signal strength (requires the ACCESS_FINE_LOCATION permission)
int signalStrength = telephonyManager.getSignalStrength().getLevel();
// Get the phone type (GSM, CDMA, etc.)
int phoneType = telephonyManager.getPhoneType();
Example
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
//create telephony manager
telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, READ_SMS) !=
PackageManager.PERMISSION_GRANTED &&ActivityCompat.checkSelfPermission(this,
READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{READ_SMS, READ_PHONE_NUMBERS,
READ_PHONE_STATE}, PERMISSION_REQUEST_CODE);
} else {
textView.setText("IMEI No. "+telephonyManager.getImei());
}
}
Android - Phone Calls
 Make a phone call from android applications by invoking built-in phone calls app using
Intents action (ACTION_CALL).
 Generally, the Intent object in android with proper action (ACTION_CALL) and data will
help us to launch a built-in phone calls app to make a phone calls in our application.
 Intent is a messaging object which is used to request an action from another app component
such as activities, services, broadcast receivers, and content providers.

Intent callIntent = new Intent(Intent.ACTION_CALL);


callIntent.setData(Uri.parse("tel:" + txtPhone.getText().toString()));
startActivity(callIntent);
Cont..
Intent Object - Action to make Phone Call
 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);
 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 +251-911-000-000, you need to specify tel: as URI using
setData() method as follows −
phoneIntent.setData(Uri.parse("tel: +251-911-000-000 "));
 To make a phone call, you do not need to specify any extra data or data type.
Example
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting instance of edittext and button
button = findViewById(R.id.button);
edittext = findViewById(R.id.editText);
// Attach set on click listener to the button for initiating intent
button.setOnClickListener(arg -> {
// getting phone number from edit text and changing it to String
String phone_number = edittext.getText().toString();
// Getting instance of Intent with action as ACTION_CALL
Intent phone_intent = new Intent(Intent.ACTION_CALL);
// Set data of Intent through Uri by parsing phone number
phone_intent.setData(Uri.parse("tel:" + phone_number));
// start Intent
startActivity(phone_intent);
});}
Android - Sending SMS
 Sending SMS (Short Message Service) is a basic feature in Android applications that allows
developers to send text messages from their app. Use SmsManager API or devices Built-in SMS
application to send SMS's.
Examples to send SMS message −
SmsManager API
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
Built-in SMS application
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
Step-by-step guide on how to create an SMS sender app in Android
 Firstly, add the permission in AndroidManifest.xml file to send the SMS:
<uses-permission android:name="android.permission.SEND_SMS"/>
 Create a UI for your app that includes a text field for entering the recipient's mobile number, a
text box for entering the message content, and a button to initiate the message sending operation.

//MainActivity.java file
private void sendMessage(String phoneNumber, String message) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
}
 onClick() event of your send button, call the sendMessage() method by passing the phone number
and message as parameters.

String phoneNo = editTextPhoneNo.getText().toString();


String message = editTextSMS.getText().toString();
sendMessage(phoneNo, message);
Functions available in SmsManager class.
Method Description

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

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

void sendDataMessage(String destinationAddress, String scAddress, used to send a data based SMS to a specific
short destinationPort, byte[] data, PendingIntent sentIntent, application port.
PendingIntent deliveryIntent)

void sendMultipartTextMessage(String destinationAddress, String Send a multi-part text based SMS.


scAddress, ArrayList<String> parts, ArrayList<PendingIntent>
sentIntents, ArrayList<PendingIntent> deliveryIntents)

void sendTextMessage(String destinationAddress, String scAddress, Send a text based SMS.


String text, PendingIntent sentIntent, PendingIntent deliveryIntent)
Example
btnSms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("smsto:"));
i.setType("vnd.android-dir/mms-sms");
i.putExtra("address", new String(txtMobile.getText().toString()));
i.putExtra("sms_body",txtMessage.getText().toString());
startActivity(Intent.createChooser(i, "Send sms via:"));
}
catch(Exception e){
Toast.makeText(MainActivity.this, "SMS Failed to Send, Please try again",
Toast.LENGTH_SHORT).show();
}
}
});
Sending Email
 Email is messages distributed by electronic means from one system user to one or more recipients via a
network.
 Intent is carrying data from one component to another component with-in the application or outside the
application.
 To send an email from your application, you don’t have to implement an email client from the beginning, but
you can use an existing one like the default Email app provided from Android, Gmail, Outlook, K-9 Mail etc.
 For this purpose, we need to write an Activity that launches an email client, using an implicit Intent with the
right action and data.
Intent Object - Action to send Email
You will use ACTION_SEND action to launch an email client installed on your Android device. Following is
simple syntax to create an intent with ACTION_SEND action.
Intent emailIntent = new Intent(Intent.ACTION_SEND);
Cont..
Intent Object - Data/Type to send Email
To send an email you need to specify mailto: as URI using setData() method and data type will be to
text/plain using setType() method as follows −
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
Intent Object - Extra to send Email
Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be attached to the
intent before sending the intent to a target email client.
Cont..
Extra Data Description
EXTRA_BCC A String[] holding e-mail addresses that should be blind carbon copied.
EXTRA_CC A String[] holding e-mail addresses that should be carbon copied.
EXTRA_EMAIL A String[] holding e-mail addresses that should be delivered to.
EXTRA_HTML_TEXT A constant String that is associated with the Intent, used with ACTION_SEND to
supply an alternative to EXTRA_TEXT as HTML formatted text.
EXTRA_SUBJECT A constant string holding the desired subject line of a message.
EXTRA_TEXT A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent.
EXTRA_TITLE A CharSequence dialog title to provide to the user when used with a
ACTION_CHOOSER.
Example showing you how to assign extra data to your intent
emailIntent.putExtra(Intent.EXTRA_EMAIL , new String[]{"Recipient"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
emailIntent.putExtra(Intent.EXTRA_TEXT , "Message Body");
Example
protected void sendEmail() {
Log.i("Send email", "");
String[] TO = {""};
String[] CC = {""};
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");
try { startActivity(Intent.createChooser(emailIntent, "Send mail..."));
finish();
Log.i("Finished sending email...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There is no email client installed.",
Toast.LENGTH_SHORT).show();
}
Android Bluetooth
 Bluetooth is a communication network protocol, which allows devices to connect wirelessly to
exchange the data with other Bluetooth devices.
 Generally, in android applications by using Bluetooth API’s we can implement Bluetooth
functionalities, such as searching for the available Bluetooth devices, connecting with the devices and
managing the data transfer between devices within the range.
 Android Bluetooth API’s in android applications, we can perform the following functionalities.
 Scan for the available Bluetooth devices within the range
 Use local Bluetooth adapter for paired Bluetooth devices
 Connect to other devices through service discovery
 Transfer data to and from other devices
 Manage multiple connections
Cont..
 To transfer the data between two Bluetooth devices first, they must establish a communication
channel using the pairing process. The devices which we are going to pair must be discoverable and
should accept the incoming connection requests. Generally, the devices will find discoverable
devices using a service discovery process. Once the device accepts the pairing request, the two
devices will exchange security keys to complete the bonding process and the devices will cache
these security keys for later use.
 Once the pairing and bonding process completes, the devices are ready to exchange the required
information. When the session is complete, the device that initiated the pairing request will release
the channel that linked to the discoverable device. The two devices remain bonded, so they can
reconnect automatically during a future session as long as they're in the range of each other.
Cont..
 Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this
calling by calling the static method getDefaultAdapter(). Its syntax is given below.
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
 In order to enable the Bluetooth of your device, call the intent with the following Bluetooth
constant ACTION_REQUEST_ENABLE. Its syntax is.
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
There are other constants provided the API , that supports different tasks.
 ACTION_REQUEST_DISCOVERABLE - used for turn on discovering of Bluetooth.
 ACTION_STATE_CHANGED - will notify that Bluetooth state has been changed.
 ACTION_FOUND - used for receiving information about each device that is discovered.
Cont..
Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method.
It returns a set of bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices; pairedDevices = BA.getBondedDevices();
Apart form the parried Devices , there are other methods in the API that gives more control over
Blueetooth.
Method description
 enable() enables the adapter if not enabled
 isEnabled() returns true if adapter is enabled
 disable() disables the adapter
 getName() returns the name of the Bluetooth adapter

 setName(String name) changes the Bluetooth name


 getState() returns the current state of the Bluetooth Adapter.

 startDiscovery() starts the discovery process of the Bluetooth for 120 seconds.
Example
public void onClick(View v) {
if(bAdapter == null){
Toast.makeText(getApplicationContext(),"Bluetooth Not
Supported",Toast.LENGTH_SHORT).show();
}else{
if(!bAdapter.isEnabled()){
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),1);
Toast.makeText(getApplicationContext(),"Bluetooth Turned
ON",Toast.LENGTH_SHORT).show();
}}}});
btntOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bAdapter.disable();
Toast.makeText(getApplicationContext(),"Bluetooth Turned OFF",
Toast.LENGTH_SHORT).show();
}
Android - Wi-Fi
 Android allows applications to access to view the access the state of the wireless connections at
very low level. Application can access almost all the information of a wifi connection.
 The information that an application can access includes connected network's link speed,IP
address, negotiation state, other networks information. Applications can also scan, add, save,
terminate and initiate Wi-Fi connections.
 Android provides WifiManager API to manage all aspects of WIFI connectivity. We can
instantiate this class by calling getSystemService method. Its syntax is given below −
WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Cont..
 In order to scan a list of wireless networks, you also need to register your BroadcastReceiver. It
can be registered using registerReceiver method with argument of your receiver class object. Its
syntax is given below −
class WifiScanReceiver extends BroadcastReceiver { public void onReceive(Context c, Intent intent) { }
} WifiScanReceiver wifiReciever = new WifiScanReceiver(); registerReceiver(wifiReciever, new
IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
 The wifi scan can be start by calling the startScan method of the WifiManager class. This
method returns a list of ScanResult objects. You can access any object by calling the get method
of list. Its syntax is given below −

List<ScanResult> wifiScanList = mainWifiObj.getScanResults(); String data =


wifiScanList.get(0).toString();
Cont..
Apart from just Scanning, you can have more control over your WIFI by using the methods defined in
WifiManager class. They are listed as follows −

Method Description
 addNetwork(WifiConfiguration config) add a new network description to the set of configured
networks.
 createWifiLock(String tag) creates a new WifiLock.
 disconnect() disassociate from the currently active access point.
 enableNetwork(int netId, boolean allow a previously configured network to be associated with.
disableOthers)
 getWifiState() gets the Wi-Fi enabled state
 isWifiEnabled() return whether Wi-Fi is enabled or disabled.
 setWifiEnabled(boolean enabled) enable or disable Wi-Fi.
 updateNetwork(WifiConfiguration config) update the network description of an existing configured
network.
Example
public void onClick(View v) {
WifiManager wmgr =
(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wmgr.setWifiEnabled(true);
}
});
btntOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WifiManager wmgr =
(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wmgr.setWifiEnabled(false);
}
Notifications
Notification is a message which is used to alert the users about some events that happening in our app.
Generally, the android Notifications will be displayed outside of our app’s normal UI and alert the users
without interrupting their current activities.
In android, we can alert the users about our app notifications in different forms like a flash the LED or make
sounds or display an icon in the status bar, etc.
When we tell the system to issue a notification, first it will display an icon in notification bar like as shown
below.

To use NotificationCompat class to implement notification in our android application. The


NotificationCompat class supports different types of notification views, such as normal view, big view
and it provides the best support for a wide range of platforms.
Create a Notification in Android
 To create a notification, we need to specify the UI content and required actions with a
NotificationCompat.Builder object.
 To display an icon, title and detailed text of notification we need to set the following properties in
Builder object.
setSmallIcon() - It is used to set the small icon for our notification.
setContentTitle() - It is used to set the title of our notification.
setContentText() - It is used to set the detailed text to display in notification.
 The above-mentioned properties are necessary to display a notification and we can set a different
type of properties to our notification like setStyle, setSound, setLights, setLargeIcon, etc. based
on our requirements using Builder object.
Example of creating a notification using NotificationCompat.Build object and setting the
notification properties.
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Sample notification")
.setContentText("Hi, Welcome to Tutlane.com");
Example
public void onClick(View v) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Tutlane Send New Message")
.setContentText("Hi, Welcome to tutlane tutorial site");
// Set the intent to fire when the user taps on notification.
Intent resultIntent = new Intent(MainActivity.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, resultIntent, 0);
mBuilder.setContentIntent(pendingIntent);
// Sets an ID for the notification
int mNotificationId = 001;
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// It will display the notification in notification bar
notificationManager.notify(mNotificationId, mBuilder.build());
}
Android Alarm Manager
 Alarm Manager is a class provided by Android to access the system’s alarm services.
 The AlarmManager class allows you to schedule your application to run at a particular time.
Even if you close your application or if your device goes to sleep still the alarm triggers at that
particular time.
 Even if your device goes off, the alarm can wake up your device. But if you power off and
reboot your system, then the intent gets deregistered, and you don’t get the alarm triggered.
 You need to register an Intent to access the system’s alarm service. Whenever a particular time
is reached, then a broadcast is made to make the intent active.
 After the alarm is off, then the intent is deregistered from the broadcast.
 The AlarmManager holds on to your device’s CPU Clock and releases it when it receives
the onReceive() method.
Characteristics of AlarmManager:
 schedules the intents to trigger at a specific time or time intervals.
 Provides the application with the ability to run at a specific time. Even if the application is not
running or your device falls asleep still the alarm can trigger to start your application.
 Used to minimize the requirement of many resources.
 Allows you to operate with the broadcast receivers to start or stop specific services.
 Holds your CPU clock and waits until we force it to stop or reboot our device.
 Now let’s see an example of how you can initialise AlarmManager and use it in your project.
Example
public void startAlert(){
EditText text = findViewById(R.id.time);
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).show();
}
Thank You!

You might also like