Chapter 5
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.
//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.
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)
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 −
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.