Android Communications Via Network and the Web PDF
Document Details
Uploaded by IdyllicEpiphany1838
Arba Minch University
Tags
Summary
This document covers Android programming concepts related to network communications. It details networking basics, checking network availability, network types using Android's ConnectivityManager class, and Android telephony. It also covers sending and receiving SMS messages and creating notifications and alarms.
Full Transcript
Communications Via Network and the Web Chapter 5 Contents ➔ Networking basics ➔ Determining network status ➔ Android telephony ➔ Notifications and alarms Networking basics Nodes – Each addressed device in a network is known as a node. It can be a PC, Mainframe, any dev...
Communications Via Network and the Web Chapter 5 Contents ➔ Networking basics ➔ Determining network status ➔ Android telephony ➔ Notifications and alarms Networking basics Nodes – Each addressed device in a network is known as a node. It can be a PC, Mainframe, any device. Protocols – are predefined and agreed up on set of rules for communication. Protocols are layered. E.g TCP/IP IP – is in charge of the addressing system and delivering packets TCP vs UDP – TCP is reliable. UDP is fire and forget. Client and Servers : requester and responder. Port – Represents particular area of PC memory (0 -65535) Connectivity Manager ConnectivityManager is an Android class that provides access to network connectivity information and network management It allows monitoring network availability, determining network types, and handling network-related events. Obtaining an Instance To use ConnectivityManager, obtain an instance using getSystemService(): ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); … Commonly Used Methods by Connectivity Manager class Method Description getActiveNetwork() Returns the currently active network. Provides details about the capabilities of the getNetworkCapabilities(Network network) specified network. Returns an array of all networks currently getAllNetworks() tracked by the framework. Returns information about a specific network getNetworkInfo(int networkType) type. registerNetworkCallback() Registers a callback for network changes. Unregisters a previously registered network unregisterNetworkCallback() callback. Checking the network status Use Connectivity Manager class to determine whether network connectivity exists and to get notifications of network changes. Checking the network status The short example shows that you can get a handle to the ConnectivityManager through the context’s getSystemService() method by passing the CONNECTIVITY_SERVICE constant. When you have the manager, you can obtain network information via the NetworkInfo object. The toString() method of the NetworkInfo object returns the output. Checking the network status We can use the isAvailable() or isConnected() method (which returns a boolean value), or you’ll directly query the NetworkInfo.State using the getState() method. NetworkInfo.State is an enum that defines the state of the connection. The possible values are CONNECTED, CONNECTING, DISCONNECTED, and DISCONNECTING. Checking Network Availability Use getActiveNetworkInfo() to check the availability of an active network connection NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { // Network is available } else { // No network available } Network Types ConnectivityManager provides constants for different network types (17 types ). Some are: - TYPE_WIFI: Wi-Fi connection - TYPE_MOBILE: Mobile data connection - TYPE_ETHERNET: Ethernet connection - TYPE_BLUETOOTH: Bluetooth connection Use getNetworkInfo(int networkType) to check the availability and status of a specific network type Android Telephony Introduction Android Telephony allows interaction with telephony features on Android devices Access and control phone calls, SMS, network information, and SIM card management Telephony Manager class Primary API for accessing telephony-related functionalities Obtain information about network operator, phone type, signal strength, and call state Example: TelephonyManager teleMgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); … Commonly Used Methods by Telephony Manager class Method Description getDeviceId() Returns the unique device ID for GSM/CDMA phones. Deprecated; use getImei() or getMeid(). getSubscriberId() Retrieves the IMSI (International Mobile Subscriber Identity). getSimSerialNumber() Returns the SIM card serial number. getLine1Number() Returns the phone number of the device (if available). getNetworkOperatorName() Gets the name of the current registered operator (e.g., “ethiotel"). getNetworkType() Returns the type of network (e.g., LTE, 3G). Retrieves the current call state (e.g., CALL_STATE_IDLE, getCallState() CALL_STATE_RINGING). getSimState() Gets the state of the SIM card (e.g., SIM_STATE_READY). getDataState() Returns the data connection state (e.g., DATA_CONNECTED). Example TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager != null) { String imei = telephonyManager.getImei(); // Get the IMEI String simSerial = telephonyManager.getSimSerialNumber(); // SIM serial number String operatorName = telephonyManager.getNetworkOperatorName();//Network operator int simState = telephonyManager.getSimState(); // SIM state } Making and Receiving Calls Use ACTION_CALL intent to initiate outgoing calls Example: String phoneNumber = "1234567890"; Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:" + phoneNumber)); startActivity(intent); Handling Incoming Calls Register BroadcastReceiver to listen for PHONE_STATE broadcast intent Handle call events and perform actions accordingly Example - 1 Example - 2 Sending and Receiving SMS Use SmsManager class to send SMS messages Example: Receiving SMS Register BroadcastReceiver to listen for SMS_RECEIVED broadcast intent. Retrieve incoming SMS messages and process them Register the necessary permissions in Manifest file Notifications and alarms Introduction to Notifications and Alarms Notifications and alarms are essential features in mobile applications to provide timely information and alerts to users. Notifications display information to users even when the app is not in the foreground Alarms schedule and trigger specific actions at specified times Notifications in Android Android provides the Notification API to create and display notifications Use the NotificationCompat.Builder class to build and customize notifications Notifications can include titles, text, icons, images, actions, and more Show notifications using the NotificationManager system service Creating a Notification Create a NotificationCompat.Builder object and set its properties NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId).setSmallIcon(R.drawable.notification_icon).setContentTitle("Notification Title").setContentText("Notification Text").setPriority(NotificationCompat.PRIORITY_DEFAULT).setContentIntent(pendingIntent).setAutoCancel(true); Displaying the Notification Use the NotificationManager to display the notification NotificationManager notificationManager = getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(notificationId, builder.build()); Alarms in Android Alarms allow scheduling and triggering actions at specific times or intervals. Use the AlarmManager class to set and manage alarms Alarms can start a service, send a broadcast, or display a notification Setting a One-Time Alarm Create an Intent for the desired action and wrap it in a PendingIntent Intent intent = new Intent(context, MyReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, flags); Scheduling the Alarm Use the AlarmManager to schedule the alarm AlarmManager alarmManager = getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTimeMillis, pendingIntent); Repeating Alarms Use setRepeating() or setInexactRepeating() to schedule recurring alarms alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTimeMillis, intervalMillis, pendingIntent); Canceling an Alarm Cancel a scheduled alarm using its corresponding PendingIntent alarmManager.cancel(pendingIntent); The End