Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore CU-MCA-SEM-VI-Advanced mobile application development-Second Draft

CU-MCA-SEM-VI-Advanced mobile application development-Second Draft

Published by Teamlease Edtech Ltd (Amita Chitroda), 2021-11-02 18:06:12

Description: CU-MCA-SEM-VI-Advanced mobile application development-Second Draft

Search

Read the Text Version

UNIT - 9:SMS AND E-MAIL CONNECTIVITY STRUCTURE 9.0 Learning Objectives 9.1 Introduction 9.2 Send SMS 9.3 Send Email 9.4 Monitoring data connectivity and activity 9.5 Accessing phone properties and status 9.6 Controlling the phone 9.7 Sending messages 9.8 Web URLs 9.9 Email Address 9.10 Map address 9.11 Summary 9.12 Keywords 9.13Learning Activity 9.14Unit End Questions 9.15References 9.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Describe the procedure to send sms through android.  Describe the procedure to send email through android.  Describe the procedure using web services on android.  Interface map with android mobile.  Access phone properties and status 9.1 INTRODUCTION People use Android devices to surf the web, download and store data, access networks, find location information, and use many types of applications. Android can even make phone calls. 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. You can easily leverage Android’s telephony support into your own applications. 151 CU IDOL SELF LEARNING MATERIAL (SLM)

In this Unit, we’ll discuss telephony in general and cover terms related to mobile devices. We’ll move on to basic Android telephony packages, which handle calls using built-in Intent actions, and more advanced operations via the TelephonyManager and PhoneStateListener classes. The Intent actions can initiate basic phone calls in your applications. TelephonyManager doesn’t make phone calls directly but is used to retrieve all kinds of telephony-related data, such as the state of the voice network, the device’s own phone number, and other details. TelephonyManager supports adding a PhoneStateListener, which can alert you when call or phone network states change. 9.2 SEND SMS  Only the default SMS app (selected by the user in system settings) is able to write to the SMS Provider (the tables defined within the Telephony class) and only the default SMS app receives the Telephony.Sms.Intents.SMS_DELIVER_ACTION broadcast when the user receives an SMS or the Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION broadcast when the user receives an MMS.  Any app that wants to behave as the user's default SMS app must handle the following intents: In a broadcast receiver, include an intent filter for Telephony.Sms.Intents.SMS_DELIVER_ACTION (\"android.provider.Telephony.SMS_DELIVER\"). The broadcast receiver must also require the Manifest.permission.BROADCAST_SMS permission. This allows your app to directly receive incoming SMS messages.  In a broadcast receiver, include an intent filter for Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION} (\"android.provider.Telephony.WAP_PUSH_DELIVER\") with the MIME type \"application/vnd.wap.mms-message\". The broadcast receiver must also require the Manifest.permission.BROADCAST_WAP_PUSH permission. This allows your app to directly receive incoming MMS messages.  In your activity that delivers new messages, include an intent filter for Intent.ACTION_SENDTO (\"android.intent.action.SENDTO\" ) with schemas, sms:, smsto:, mms:, and mmsto:. This allows your app to receive intents from other apps that want to deliver a message.  In a service, include an intent filter for TelephonyManager.ACTION_RESPOND_VIA_MESSAGE (\"android.intent.action.RESPOND_VIA_MESSAGE\") with schemas, sms:, smsto:, mms:, and mmsto:. This service must also require the Manifest.permission.SEND_RESPOND_VIA_MESSAGE permission. 152 CU IDOL SELF LEARNING MATERIAL (SLM)

This allows users to respond to incoming phone calls with an immediate text message using your app. 9.3 SEND EMAIL Before starting Email Activity, You must know Email functionality with intent, 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. In this example, we are going to send an email from our app by using an Intent object that launches existing email clients. Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to}); email.putExtra(Intent.EXTRA_SUBJECT, subject); email.putExtra(Intent.EXTRA_TEXT, message); //need this to prompts email client only email.setType(\"message/rfc822\"); startActivity(Intent.createChooser(email, \"Choose an Email client :\")); MainActivity.java package com.example.sendemail; import android.os.Bundle; 153 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; CU IDOL SELF LEARNING MATERIAL (SLM)

import android.widget.EditText; 154 public class MainActivity extends Activity { EditText editTextTo,editTextSubject,editTextMessage; Button send; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextTo=(EditText)findViewById(R.id.editText1); editTextSubject=(EditText)findViewById(R.id.editText2); editTextMessage=(EditText)findViewById(R.id.editText3); send=(Button)findViewById(R.id.button1); send.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { String to=editTextTo.getText().toString(); String subject=editTextSubject.getText().toString(); String message=editTextMessage.getText().toString(); Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to}); email.putExtra(Intent.EXTRA_SUBJECT, subject); email.putExtra(Intent.EXTRA_TEXT, message); CU IDOL SELF LEARNING MATERIAL (SLM)

//need this to prompts email client only email.setType(\"message/rfc822\"); startActivity(Intent.createChooser(email, \"Choose an Email client :\")); } }); } @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; } } 9.4 MONITORING DATA CONNECTIVITY AND ACTIVITY As well as voice and service details, you can also use a Phone State Listener to monitor changes in mobile data connectivity and mobile data transfer. The Phone State Listener includes two event handlers for monitoring the device data connection. Override onDataActivity to track data transfer activity, and onDataConnectionStateChanged to request notifications for data connection state changes. Listing 12-12 shows both handlers overridden, with switch statements demonstrating each of the possible values for the state and data-flow direction parameters passed in to each event. LISTING 12-12: Monitoring data connections and transfers Available for PhoneStateListener dataStateListener = new PhoneStateListener() { Wrax°comn public void onDataActivity(int direction) { switch (direction) { 155 CU IDOL SELF LEARNING MATERIAL (SLM)

case TelephonyManager.DATA_ACTIVITY_IN : break; case TelephonyManager.DATA_ACTIVITY_OUT : break; case TelephonyManager.DATA_ACTIVITY_INOUT : break; case TelephonyManager.DATA_ACTIVITY_NONE : break; public void onDataConnectionStateChanged(int state) { switch (state) { case TelephonyManager.DATA_CONNECTED : break; case break; case TelephonyManager.DATA_CONNECTING : break; case TelephonyManager.DATA_DISCONNECTED : | TelephonyManager.DATA_SUSPENDED : break; telephonyManager.listen(dataStateListener, PhoneStateListener.LISTEN_DATA_ACTIVITY PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); 9.5 ACCESSING PHONE PROPERTIES AND STATUS The Telephony Manager also provides access to several static phone properties. You can obtain the current value of any of the phone state details described previously. The following code snippet shows how to extract the current incoming call number if the phone is ringing: String incomingCall = null; if (telephonyManager.getCallState() == TelephonyManager.CALL_STATE_RINGING) incomingCall = telephonyManager.getLine1Number(); You can also access SIM and network operator details, network information, and voice-mail details. The following code snippet shows the framework used to access the current network details: String srvcName = Context.TELEPHONY_SERVICE; TelephonyManager telephonyManager = (TelephonyManager)getSystemService(srvcName); String networkCountry = telephonyManager.getNetworkCountryIso(); String networkOperatorId = telephonyManager.getNetworkOperator(); String networkName = telephonyManager.getNetworkOperatorName(); int networkType = telephonyManager.getNetworkType(); 156 CU IDOL SELF LEARNING MATERIAL (SLM)

9.6 CONTROLLING THE PHONE  The features in this guide describe device management capabilities you can implement in your device policy controller (DPC) app. You can also use the Test DPC app as a source of sample code for Android's enterprise features.  A DPC app can run in profile owner mode on personal devices or in device owner mode on fully managed devices. This table indicates which features are available when the DPC runs in profile owner mode or device owner mode:  Create a custom lock screen message Running in device owner mode, a DPC can create a custom lock screen message on their users’ devices using the setDeviceOwnerLockScreenInfo method. This message displays on the device screen when locked, and is useful for a lost or stolen device. A common message is “This phone belongs to <company name>, call <phone number> if found.”  Disable data roaming: Data roaming can cause significant charges on mobile carrier bills. To help streamline those costs, a DPC running in device owner mode can disable data roaming by setting the DISALLOW_DATA ROAMING restriction. Once the user restriction is set by the DPC, a user can’t change data roaming via Settings on their device.  Give users a customized message if a setting is blocked : When a user clicks a setting or feature blocked by their IT department, the support message gives a brief explanation of why they can’t access the feature. These messages can be more descriptive than “Action not allowed.” A DPC running in device owner or profile owner mode can customize these messages using the DevicePolicyManager setShortSupportMessage() and setLongSupportMessage() methods.  Lock down the wallpaper: Organizations such as schools or companies that run Android devices as shared devices can block their users from changing the wallpaper on their device home screen. To lock down the wallpaper, a DPC running in device owner or profile owner mode can set DISALLOW_SET_WALLPAPER to true. The default for this setting is false.  Lock down a customer user icon: A DPC running in either device owner or profile owner mode can add users and specify an icon for each user. This user icon is only on the device and is separate from the profile icon that appears in other Google properties, such as a Gmail message or Google Plus profile. A DPC can configure the DISALLOW_SET_USER_ICON to true to restrict a user from changing their icon. The default for this setting is false. 157 CU IDOL SELF LEARNING MATERIAL (SLM)

9.7 SENDING MESSAGES 158 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\" CU IDOL SELF LEARNING MATERIAL (SLM)

android:layout_width=\"wrap_content\" 159 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\" 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> You need to write SEND_SMS permission as given below: <uses-permission android:name=\"android.permission.SEND_SMS\"/> Android-Manifest.xml CU IDOL SELF LEARNING MATERIAL (SLM)

<?xml version=\"1.0\" encoding=\"utf-8\"?> 160 <manifest xmlns:androclass=\"http://schemas.android.com/apk/res/android\" package=\"com.example.sendsms\" android:versionCode=\"1\" android:versionName=\"1.0\" > <uses-sdk android:minSdkVersion=\"8\" android:targetSdkVersion=\"16\" /> <uses-permission android:name=\"android.permission.SEND_SMS\"/> <uses-permission android:name=\"android.permission.RECEIVE_SMS\"/> <application android:allowBackup=\"true\" android:icon=\"@drawable/ic_launcher\" android:label=\"@string/app_name\" android:theme=\"@style/AppTheme\" > <activity android:name=\"com.example.sendsms.MainActivity\" android:label=\"@string/app_name\" > <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> CU IDOL SELF LEARNING MATERIAL (SLM)

</manifest> 161 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); CU IDOL SELF LEARNING MATERIAL (SLM)

//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 method to send message SmsManager sms=SmsManager.getDefault(); sms.sendTextMessage(no, null, msg, pi,null); 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; } 162 CU IDOL SELF LEARNING MATERIAL (SLM)

} Output: Figure 9.1 Send SMS 163 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 9.2 SMS Sent 9.8 WEB URLS Below example shows how you can open a URL programmatically in the built-in web browser rather than within your application. This allows your app to open up a webpage without the need to include the INTERNET permission in your manifest file. public void onBrowseClick(View v) { String url = \"http://www.google.com\"; Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); // Verify that the intent will resolve to an activity if (intent.resolveActivity(getPackageManager()) != null) { // Here we use an intent without a Chooser unlike the next example startActivity(intent); } } Prompting the user to select a browser: 164 CU IDOL SELF LEARNING MATERIAL (SLM)

public void onBrowseClick(View v) { String url = \"http://www.google.com\"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); // Note the Chooser below. If no applications match, // Android displays a system message.So here there is no need for try-catch. startActivity(Intent.createChooser(intent, \"Browse with\")); } 9.9 EMAIL ADDRESS  There are various ways to send email using JavaMail API. For this purpose, you must have SMTP server that is responsible to send mails.  You can use one of the following techniques to get the SMTP server: i. Install and use any SMTP server such as Postcast server, Apache James server, cmail server etc. (or) ii. Use the SMTP server provided by the host provider e.g. my SMTP server is mail.javatpoint.com (or) iii. Use the SMTP Server provided by other companies e.g. gmail etc.  Steps to send email using JavaMail API There are following three steps to send email using JavaMail. They are as follows: i. Get the session object that stores all the information of host like host name, username, password etc. ii. Compose the message iii. Send the message  Example: For sending the email using JavaMail API, you need to load the two jar files: 1. Mail.jar 2. Activation.jar import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail 165 CU IDOL SELF LEARNING MATERIAL (SLM)

{ public static void main(String [] args){ String to = \"[email protected]\";//change accordingly String from = \"[email protected]\";change accordingly String host = \"localhost\";//or IP address //Get the session object Properties properties = System.getProperties(); properties.setProperty(\"mail.smtp.host\", host); Session session = Session.getDefaultInstance(properties); //compose the message try{ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO,new InternetAddress(to)); message.setSubject(\"Ping\"); message.setText(\"Hello, this is example of sending email \"); // Send message Transport.send(message); System.out.println(\"message sent successfully....\"); }catch (MessagingException mex) {mex.printStackTrace();} } } 166 CU IDOL SELF LEARNING MATERIAL (SLM)

9.10 MAP ADDRESS  Searching location in Google Map API is done through Geocoder class. Geocoder class is used to handle geocoding and reverse geocoding.  Geocoding is a process in which street address is converted into a coordinate (latitude,longitude). Reverse geocoding is a process in which a coordinate (latitude,longitude) is converted into an address.  Methods of Geocoder class 1. List<Address> getFromLocation(double latitude, double longitude, int maxResults): This method returns an array of Address which specifies the surrounding latitude and longitude. 2. List<Address> getFromLocationName(String location, int results, double leftLatitude, double leftLongitude, double rightLatitude, double rightLongitude): This method returns an array of Address which describes the given location such as place, an address, etc. 3. List<Address> getFromLocationName(String location, int results): This method returns an array of Address which describes te given location such as place, an address, etc. 4. static boolean isPresent(): This method returns true if the methods getFromLocation() and getFromLocationName() are implemented.  Code which convert location name into coordinate. List<Address> addressList = geocoder.getFromLocationName(location, 1); Address address = addressList.get(0); LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());  Example: activity_maps.xml <fragment xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:map=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/map\" android:name=\"com.google.android.gms.maps.SupportMapFragment\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"example.com.mapexample.MapsActivity\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <EditText 167 CU IDOL SELF LEARNING MATERIAL (SLM)

android:layout_width=\"248dp\" android:layout_height=\"wrap_content\" android:id=\"@+id/editText\" android:layout_weight=\"0.5\" android:inputType=\"textPersonName\" android:hint=\"Search Location\" /> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"0.5\" android:onClick=\"searchLocation\" android:text=\"Search\" /> </LinearLayout> </fragment> build.gradel dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.google.android.gms:play-services-maps:11.8.0' compile 'com.google.android.gms:play-services-location:11.8.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' } MapsActivity.java file. package example.com.mapexample; import android.location.Address; 168 import android.location.Geocoder; import android.os.Build; CU IDOL SELF LEARNING MATERIAL (SLM)

import android.support.v4.app.FragmentActivity; 169 import android.os.Bundle; import com.google.android.gms.common.API.GoogleAPIClient; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.location.LocationServices; import android.location.Location; import android.Manifest; import android.content.pm.PackageManager; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import java.io.IOException; import java.util.List; CU IDOL SELF LEARNING MATERIAL (SLM)

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener,GoogleAPIClient.ConnectionCallbacks, GoogleAPIClient.OnConnectionFailedListener{ private GoogleMap mMap; Location mLastLocation; Marker mCurrLocationMarker; GoogleAPIClient mGoogleAPIClient; LocationRequest mLocationRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 170 if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { CU IDOL SELF LEARNING MATERIAL (SLM)

buildGoogleAPIClient(); mMap.setMyLocationEnabled(true); } } else { buildGoogleAPIClient(); mMap.setMyLocationEnabled(true); } } protected synchronized void buildGoogleAPIClient() { mGoogleAPIClient = new GoogleAPIClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addAPI(LocationServices.API).build(); mGoogleAPIClient.connect(); } @Override public void onConnected(Bundle bundle) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(1000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCU RACY); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 171 CU IDOL SELF LEARNING MATERIAL (SLM)

LocationServices.FusedLocationAPI.requestLocationUpdates(mGoogleAPIClient, mLocationRequest, this); } } @Override public void onConnectionSuspended(int i) { } @Override public void onLocationChanged(Location location) { mLastLocation = location; if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } //Place current location marker LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title(\"Current Position\"); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE _GREEN)); mCurrLocationMarker = mMap.addMarker(markerOptions); //move map camera 172 mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); CU IDOL SELF LEARNING MATERIAL (SLM)

//stop location updates if (mGoogleAPIClient != null) { LocationServices.FusedLocationAPI.removeLocationUpdates(mGoogleAPIClient, this); } } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } public void searchLocation(View view) { EditText locationSearch = (EditText) findViewById(R.id.editText); String location = locationSearch.getText().toString(); List<Address> addressList = null; if (location != null || !location.equals(\"\")) { Geocoder geocoder = new Geocoder(this); try { addressList = geocoder.getFromLocationName(location, 1); } catch (IOException e) { e.printStackTrace(); } Address address = addressList.get(0); LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); mMap.addMarker(new MarkerOptions().position(latLng).title(location)); 173 CU IDOL SELF LEARNING MATERIAL (SLM)

mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); Toast.makeText(getApplicationContext(),address.getLatitude()+\" \"+address.getLongitude(),Toast.LENGTH_LONG).show(); } } } Required Permission in AndroidManifest.xml <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" /> <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" /> <uses-permission android:name=\"android.permission.INTERNET\" /> AndroidManifest.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"example.com.mapexample\"> <!-- The ACCESS_COARSE/FINE_LOCATION permissions are not required to use Google Maps Android API v2, but you must specify either coarse or fine location permissions for the 'MyLocation' functionality. --> <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" /> <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" /> <uses-permission android:name=\"android.permission.INTERNET\" /> <application 174 android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" CU IDOL SELF LEARNING MATERIAL (SLM)

android:theme=\"@style/AppTheme\"> <!-- The API key for Google Maps-based APIs is defined as a string resource. (See the file \"res/values/google_maps_API.xml\"). Note that the API key is linked to the encryption key used to sign the APK. You need a different API key for each encryption key, including the release key that is used to sign the APK for publishing. You can define the keys for the debug and release targets in src/debug/ and src/release/. --> <meta-data android:name=\"com.google.android.geo.API_KEY\" android:value=\"@string/google_maps_key\" /> <activity android:name=\".MapsActivity\" android:label=\"@string/title_activity_maps\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest> Output: 175 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 9.3 Map- Search Location 176 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 9.4 Map Address 177 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 9.5 Map Address 9.11 SUMMARY  Only the default SMS app (selected by the user in system settings) is able to write to the SMS Provider (the tables defined within the Telephony class) and only the default SMS app receives the Telephony.Sms.Intents.SMS_DELIVER_ACTION broadcast when the user receives an SMS or theTelephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION broadcast when the user receives an MMS.  The Phone State Listener includes two event handlers for monitoring the device data connection. Override onDataActivity to track data transfer activity, and onDataConnectionStateChanged to request notifications for data connection state changes.  A DPC app can run in profile owner mode on personal devices or in device owner mode on fully managed devices. This table indicates which features are available when the DPC runs in profile owner mode or device owner mode:  following techniques to get the SMTP server: 178 CU IDOL SELF LEARNING MATERIAL (SLM)

1. Install and use any SMTP server such as Postcast server, Apache James server, cmail server etc. (or) 2. Use the SMTP server provided by the host provider e.g. my SMTP server is mail.javatpoint.com (or) 3. Use the SMTP Server provided by other companies e.g. gmail etc. 9.12 KEYWORDS  URL:On the Internet, these addresses are called URLs (Uniform Resource Locators). A webpage's URL—such as http://support.google.com/google-ads—is made up of a domain name (here it's \"google\"), a domain category (\".com\"), and sometimes other elements like a subdomain (\"support\") and path  SMS:SMS is an acronym for \"Short Message Service\" and is the oldest, most widespread, and frequently used texting technology that is supported by every single mobile network and device today. In the U.S. alone, over 6 billion SMS messages are sent daily.  EMAIL:Electronic mail (email or e-mail) is a method of exchanging messages (\"mail\") between people using electronic devices.  Intent:An intent is to perform an action on the screen. It is mostly used to start activity, send broadcast receiver, start services and send message between two activities. There are two intents available in android as Implicit Intents and Explicit Intents. Here is a sample example to start new activity with old activity.  Adapters: An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. 9.13 LEARNING ACTIVITY 1. What is the intent that needs to be handle by default SMS app? ___________________________________________________________________________ ___________________________________________________________________________ 2. What is the command that is used receive incoming MMS? ___________________________________________________________________________ ___________________________________________________________________________ 9.14 UNIT END QUESTIONS A. Descriptive Questions Short Questions 179 CU IDOL SELF LEARNING MATERIAL (SLM)

1. What is the process of sending SMS 180 2. How is phone properties access? 3. Explain how WEB URL access through android programming. 4. How is Email address access? Long Questions 1. What is the process of sending EMAIL? 2. Explain in detail about data connectivity activity in android. 3. Explain how phone control? 4. Write a program for sending message. 5. How is map interfaced in android? B. Multiple Choice Questions 1 DPC runs in ______ mode a. profile owner b. profile rental c. safe d. active. 2. ______ server that is responsible to send mails. a. UDP b. SMTP c. TCP d. Client 3. For sending the email using JavaMail API, you need _____ a. client.jar b. java.jar c. Mail.jar d. listener.jar CU IDOL SELF LEARNING MATERIAL (SLM)

4. Searching location in Google Map API is done through _________ class a. Main Class b. Intent Class c. Adapter d. Geocoder 5. API key is linked to the ________key used to sign the APK a. encryption b. private c. public d. decryption Answers 1-a, 2-b, 3-c, 4-d, 5-a 9.15 REFERENCES Book References  “Professional Android 4 Application Development” by Reto Meier  “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart  “Professional Android 4 Application Development” by Reto Meier  “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart E-References 181 CU IDOL SELF LEARNING MATERIAL (SLM)

 Introduction to Android: http://developer.android.com/guide/index.html.  Android API: http://developer.android.com/reference/packages.html  Java 6 API: http://docs.oracle.com/javase/6/docs/API/  Android Fundamentals: http://developer.android.com/guide/components/fundamentals.html 182 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 10: DEVICE CONNECTIVITY STRUCTURE 10.0Learning Objectives 10.1 Introduction 10.2 Bluetooth 10.3 WIFI 10.4 Android Web Service 10.5 Controlling local Bluetooth device 10.6 Discovering and bonding with Bluetooth devices 10.7 Managing Bluetooth connections 10.8 Communicating with Bluetooth 10.9 Monitoring and managing Internet connectivity 10.10 Managing active connections 10.11 Managing Wi-Fi networks 10.12 Summary 10.13 Keywords 10.14 Learning Activity 10.15 Unit End Questions 10.16 References 10.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Describe the connectivity process of Bluetooth using android.  Describe the connectivity process of WIFI using android.  Explain the communication with Bluetooth on android.  ManageWi-Fi networks  Monitor and manage Internet connectivity 10.1 INTRODUCTION Besides enabling communication with the cloud, Android's wireless APIs also enable communication with other devices on the same local network, and even devices which are not on a network, but are physically nearby. The addition of Network Service Discovery (NSD) takes this further by allowing an application to seek out a nearby device running services with which it can communicate. Integrating this functionality into your application helps you provide a wide range of features, such as playing games with users in the same room, pulling 183 CU IDOL SELF LEARNING MATERIAL (SLM)

images from a networked NSD-enabled webcam, or remotely logging into other machines on the same network. This class describes the key APIs for finding and connecting to other devices from your application. Specifically, it describes the NSD API for discovering available services and the Wi-Fi Peer-to-Peer (P2P) API for doing peer-to-peer wireless connections. This class also shows you how to use NSD and Wi-Fi P2P in combination to detect the services offered by a device and connect to the device when neither device is connected to a network. 10.2 BLUETOOTH  The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The app framework provides access to the Bluetooth functionality through Bluetooth APIs. These APIs let apps connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features.  Using the Bluetooth APIs, an app can perform the following: i. Scan for other Bluetooth devices. ii. Query the local Bluetooth adapter for paired Bluetooth devices. iii. Establish RFCOMM channels. iv. Connect to other devices through service discovery. v. Transfer data to and from other devices. vi. Manage multiple connections.  Bluetooth is the right choice for more battery-intensive operations, which include streaming and communicating between devices. For Bluetooth devices with low power requirements, consider using Bluetooth Low Energy connections.  For Bluetooth-enabled devices to transmit data between each other, they must first form a channel of communication using a pairing process. One device, a discoverable device, makes itself available for incoming connection requests. Another device finds the discoverable device using a service discovery process.  After the discoverable device accepts the pairing request, the two devices complete a bonding process in which they exchange security keys. The devices cache these keys for later use. After the pairing and bonding processes are complete, the two devices exchange information.  When the session is complete, the device that initiated the pairing request releases the channel that had linked it to the discoverable device. The two devices remain bonded, however, so they can reconnect automatically during a future session as long as they're in range of each other and neither device has removed the bond. 184 CU IDOL SELF LEARNING MATERIAL (SLM)

10.3 WIFI  You can use the Wi-Fi scanning capabilities provided by the WifiManager API to get a list of Wi-Fi access points that are visible from the device.  Wi-Fi scanning process There are three steps to the scanning process: i. Register a broadcast listener for SCAN_RESULTS_AVAILABLE_ACTION, which is called when scan requests are completed, providing their success/failure status. For devices running Android 10 (API level 29) and higher, this broadcast will be sent for any full Wi-Fi scan performed on the device by the platform or other apps. Apps can passively listen to all scan completions on device by using the broadcast without issuing a scan of their own. ii. Request a scan using WifiManager.startScan(). Make sure to check the return status of the method, since the call may fail for any of the following reasons: a. Scan requests may be throttled because of too many scans in a short time. b. The device is idle and scanning is disabled. c. Wi-Fi hardware reports a scan failure. iii. Get scan results using WifiManager.getScanResults(). The returned scan results are the most recently updated results, which may be from a previous scan if your current scan has not completed or succeeded. This means that you might get older scan results if you call this method before receiving a successful SCAN_RESULTS_AVAILABLE_ACTION broadcast.  The following code provides an example of how to implement these steps: WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() { 185 @Override public void onReceive(Context c, Intent intent) { boolean success = intent.getBooleanExtra( WifiManager.EXTRA_RESULTS_UPDATED, false); if (success) { scanSuccess(); } else { // scan failure handling scanFailure(); } } CU IDOL SELF LEARNING MATERIAL (SLM)

}; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); context.registerReceiver(wifiScanReceiver, intentFilter); boolean success = wifiManager.startScan(); if (!success) { // scan failure handling scanFailure(); } .... private void scanSuccess() { List<ScanResult> results = wifiManager.getScanResults(); ... use new scan results ... } private void scanFailure() { // handle failure: new scan did NOT succeed // consider using old scan results: these are the OLD results! List<ScanResult> results = wifiManager.getScanResults(); ... potentially use older scan results ... } 10.4 ANDROID WEB SERVICE A web service is basically required to provide interoperability, i.e. connecting various applications. It allows different apps to communicate with each other and share the data and services among themselves. Web services provide a standard for all the types of client applications to invoke functions on every type of app server. Activity_main.xml 186 <?xml version=\"1.0\" encoding=\"utf-8\"?> <RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" CU IDOL SELF LEARNING MATERIAL (SLM)

xmlns:tools=\"http://schemas.android.com/tools\" 187 android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <EditText android:hint=\"Type URL Here\" android:id=\"@+id/website\" android:layout_width=\"fill_parent\" android:layout_height=\"75dp\" android:ems=\"5\"></EditText> <Button android:id=\"@+id/runWebsite\" android:layout_width=\"fill_parent\" android:layout_height=\"45dp\" android:text=\"Run WebSite on Browser\" /> </LinearLayout> </RelativeLayout> Main_Activity.java package com.maharashtracollege.profshahidansari; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; CU IDOL SELF LEARNING MATERIAL (SLM)

import android.graphics.Color; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button runWebsite = (Button) findViewById(R.id.runWebsite); 188 runWebsite.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { EditText website = (EditText) findViewById(R.id.website); String strURL = website.getText().toString(); if (strURL.indexOf(\"http://www\") < 0) { strURL = \"http://www.\" + strURL; } Intent implicit = new Intent(Intent.ACTION_VIEW, Uri.parse(strURL)); startActivity(implicit); } CU IDOL SELF LEARNING MATERIAL (SLM)

}); } } Output: Fig 10.1 Android web serivce 10.5 CONTROLLING LOCAL BLUETOOTH DEVICE  Using the BluetoothAdapter, you can find remote Bluetooth devices either through device discovery or by querying the list of paired devices.  Make sure you have the appropriate Bluetooth permissions and set up your app for Bluetooth before attempting to find Bluetooth devices. 189 CU IDOL SELF LEARNING MATERIAL (SLM)

 Device discovery is a scanning procedure that searches the local area for Bluetooth- enabled devices and requests some information about each one. This process is sometimes referred to as discovering, inquiring, or scanning.  A nearby Bluetooth device responds to a discovery request only if it is currently accepting information requests by being discoverable.  If a device is discoverable, it responds to the discovery request by sharing some information, such as the device's name, its class, and its unique MAC address. Using this information, the device that is performing the discovery process can then choose to initiate a connection to the discovered device.  Because discoverable devices might reveal information about the user's location, the device discovery process requires location access. If your app is being used on a device that runs Android 8.0 (API level 26) or higher, consider using the Companion Device Manager API instead. This API performs device discovery on your app's behalf, so your app doesn't need to request location permissions.  Once a connection is made with a remote device for the first time, a pairing request is automatically presented to the user. When a device is paired, the basic information about that device—such as the device's name, class, and MAC address—is saved and can be read using the Bluetooth APIs. Using the known MAC address for a remote device, a connection can be initiated with it at any time without performing discovery, assuming the device is still within range.  Note that there is a difference between being paired and being connected:  To be paired means that two devices are aware of each other's existence, have a shared link-key that can be used for authentication, and are capable of establishing an encrypted connection with each other.  To be connected means that the devices currently share an RFCOMM channel and are able to transmit data with each other. The current Bluetooth APIs require devices to be paired before an RFCOMM connection can be established. Pairing is automatically performed when you initiate an encrypted connection with the Bluetooth APIs.  Query paired devices: Before performing device discovery, it's worth querying the set of paired devices to see if the desired device is already known. To do so, call getBondedDevices(). This returns a set of BluetoothDevice objects representing paired devices. For example, you can query all paired devices and get the name and MAC address of each device, as the following code snippet demonstrates: Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { 190 // There are paired devices. Get the name and address of each paired device. for (BluetoothDevice device : pairedDevices) { CU IDOL SELF LEARNING MATERIAL (SLM)

String deviceName = device.getName(); String deviceHardwareAddress = device.getAddress(); // MAC address } } 10.6 DISCOVERING AND BONDING WITH BLUETOOTH DEVICES  To start discovering devices, call startDiscovery(). The process is asynchronous and returns a boolean value indicating whether discovery has successfully started.  The discovery process usually involves an inquiry scan of about 12 seconds, followed by a page scan of each device found to retrieve its Bluetooth name.  To receive information about each device discovered, your app must register a BroadcastReceiver for the ACTION_FOUND intent. The system broadcasts this intent for each device.  The intent contains the extra fields EXTRA_DEVICE and EXTRA_CLASS, which in turn contain a BluetoothDevice and a BluetoothClass, respectively. The following code snippet shows how you can register to handle the broadcast when devices are discovered: @Override protected void onCreate(Bundle savedInstanceState) { ... // Register for broadcasts when a device is discovered. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(receiver, filter); } // Create a BroadcastReceiver for ACTION_FOUND. private final BroadcastReceiver receiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Discovery has found a device. Get the BluetoothDevice // object and its info from the Intent. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String deviceName = device.getName(); String deviceHardwareAddress = device.getAddress(); // MAC address } 191 CU IDOL SELF LEARNING MATERIAL (SLM)

} }; @Override protected void onDestroy() { super.onDestroy(); ... // Don't forget to unregister the ACTION_FOUND receiver. unregisterReceiver(receiver); } 10.7 MANAGING BLUETOOTH CONNECTIONS  To initiate a connection with a Bluetooth device, you call getAddress() on the BluetoothDevice to retrieve the associated MAC address.  Enable discoverability To make the local device discoverable to other devices, call startActivityForResult(Intent, int) with the ACTION_REQUEST_DISCOVERABLE intent. This issues a request to enable the system's discoverable mode without having to navigate to the Settings app, which would stop your own app. By default, the device becomes discoverable for two minutes. You can define a different duration, up to one hour, by adding the EXTRA_DISCOVERABLE_DURATION extra.  The following code snippet sets the device to be discoverable for five minutes: int requestCode = 1; Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATI ON, 300); startActivityForResult(discoverableIntent, requestCode);  A dialog is displayed, requesting the user's permission to make the device discoverable, as shown in figure 2. If the user responds \"Allow,\" then the device becomes discoverable for the specified amount of time. Your activity then receives a call to the onActivityResult() callback, with the result code equal to the duration that the device is discoverable. If the user responded \"Deny\", or if an error occurred, the result code is RESULT_CANCELED.  The device silently remains in discoverable mode for the allotted time. To be notified when the discoverable mode has changed, register a BroadcastReceiver for the ACTION_SCAN_MODE_CHANGED intent. This intent contains the extra fields 192 CU IDOL SELF LEARNING MATERIAL (SLM)

EXTRA_SCAN_MODE and EXTRA_PREVIOUS_SCAN_MODE, which provide the new and old scan mode, respectively. 10.8 COMMUNICATING WITH BLUETOOTH  For Bluetooth-enabled devices to transmit data between each other, they must first form a channel of communication using a pairing process. One device, a discoverable device, makes itself available for incoming connection requests.  Another device finds the discoverable device using a service discovery process. After the discoverable device accepts the pairing request, the two devices complete a bonding process in which they exchange security keys.  The devices cache these keys for later use. After the pairing and bonding processes are complete, the two devices exchange information. When the session is complete, the device that initiated the pairing request releases the channel that had linked it to the discoverable device.  The two devices remain bonded, however, so they can reconnect automatically during a future session as long as they're in range of each other and neither device has removed the bond.  Use of the Bluetooth APIs requires declaring several permissions in your manifest file. Once your app has permission to use Bluetooth, your app needs to access the BluetoothAdapter and determine if Bluetooth is available on the device. If Bluetooth is available, there are three steps to make a connection: 1. Find nearby Bluetooth devices, either devices that are already paired or new ones. 2. Connect to a Bluetooth device. 3. Transfer data with the connected device.  Certain devices use a specific Bluetooth profile that declares the data it provides. 10.9 MONITORING AND MANAGING INTERNET CONNECTIVITY  You can use the ConnectivityManager to check that you're connected to the internet, and if you are, to determine what type of connection is in place.  Determine whether you have an internet connection You can't run an update based on an internet resource if you aren't connected to the internet. The recommended way to schedule tasks that require internet connectivity is using WorkManager. For more information, see Schedule tasks with WorkManager. You can also use the method shown below to interactively query the active network to determine if it has internet connectivity. ConnectivityManager cm = 193 CU IDOL SELF LEARNING MATERIAL (SLM)

(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVI CE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();  Determine the type of internet connection It's also possible to determine the type of internet connection currently available. Device connectivity can be provided by mobile data, WiMAX, Wi-Fi, and Ethernet connections. By querying the type of the active network, as shown in the following code sample, you can change your app's behavior based on the bandwidth available. ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVI CE); boolean isMetered = cm.isActiveNetworkMetered(); 10.10 MANAGING ACTIVE CONNECTIONS  WorkManager is an API that makes it easy to schedule reliable, asynchronous tasks that are expected to run even if the app exits or the device restarts. The WorkManager API is a suitable and recommended replacement for all previous Android background scheduling APIs, including FirebaseJobDispatcher, GcmNetworkManager, and Job Scheduler. WorkManager incorporates the features of its predecessors in a modern, consistent API that works back to API level 14 while also being conscious of battery life.  Under the hood WorkManager uses an underlying job dispatching service based on the following criteria: 194 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 10.2 Managing active connections  Use WorkManager for Reliable Work : WorkManager is intended for work that required to run reliably even if the user navigates off a screen, the app exits, or the device restarts. For example: Sending logs or analytics to backend services Periodically syncing application data with a server WorkManager is not intended for in-process background work that can safely be terminated if the app process goes away or for work that requires immediate execution. Please review the background processing guide to see which solution meets your needs. 10.11 MANAGING WIFI NETWORKS.  public class WifiManager Extends Object java.lang.Object ↳ android.net.wifi.WifiManager  This class provides the primary API for managing all aspects of Wi-Fi connectivity.  On releases before Build.VERSION_CODES.N, this object should only be obtained from an application context, and not from any other derived context to avoid memory leaks within the calling process.  It deals with several categories of items: 195 CU IDOL SELF LEARNING MATERIAL (SLM)

1. The list of configured networks. The list can be viewed and updated, and attributes of individual entries can be modified. 2. The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried. 3. Results of access point scans, containing enough information to make decisions about what access point to connect to. 4. It defines the names of various Intent actions that are broadcast upon any sort of change in Wi-Fi state.  This is the API to use when performing Wi-Fi specific operations. To perform operations that pertain to network connectivity at an abstract level, use Connectivity Manager. 10.12 SUMMARY  Using the Bluetooth APIs, an app can perform the following: i. Scan for other Bluetooth devices. ii. Query the local Bluetooth adapter for paired Bluetooth devices. iii. Establish RFCOMM channels. iv. Connect to other devices through service discovery. v. Transfer data to and from other devices. vi. Manage multiple connections.  There are three steps to the scanning process: i. Register a broadcast listener for SCAN_RESULTS_AVAILABLE_ACTION, which is called when scan requests are completed, providing their success/failure status. For devices running Android 10 (API level 29) and higher, this broadcast will be sent for any full Wi-Fi scan performed on the device by the platform or other apps. Apps can passively listen to all scan completions on device by using the broadcast without issuing a scan of their own. ii. Request a scan using WifiManager.startScan(). Make sure to check the return status of the method, since the call may fail for any of the following reasons: a. Scan requests may be throttled because of too many scans in a short time. b. The device is idle and scanning is disabled. c. Wi-Fi hardware reports a scan failure. iii. Get scan results using WifiManager.getScanResults(). The returned scan results are the most recently updated results, which may be from a previous scan if your current scan has not completed or succeeded. This means that you might get older scan results if you call this method before receiving a successful SCAN_RESULTS_AVAILABLE_ACTION broadcast. 196 CU IDOL SELF LEARNING MATERIAL (SLM)

 Device discovery is a scanning procedure that searches the local area for Bluetooth- enabled devices and requests some information about each one. This process is sometimes referred to as discovering, inquiring, or scanning  Query paired devices: Before performing device discovery, it's worth querying the set of paired devices to see if the desired device is already known. To do so, call getBondedDevices(). This returns a set of Bluetooth Device objects representing paired devices. 10.13 KEYWORDS  NETWORKS: computer network, two or more computers that are connected with one another for the purpose of communicating data electronically.  WIFI:Wi-Fi is the wireless technology used to connect computers, tablets, smartphones and other devices to the internet. Wi-Fi is the radio signal sent from a wireless router to a nearby device, which translates the signal into data you can see and use.  Reliable Work: People or things that are reliable can be trusted to work well or to behave in the way that you want them to.  API:Application programming interfaces, or APIs, simplify software development and innovation by enabling applications to exchange data and functionality easily and securely.  Bluetooth: Bluetooth is a wireless technology that allows the exchange of data between different devices. While Bluetooth uses wavelength to transmit information, it generally only works within a short distance for the devices to stay connected.. 10.14 LEARNING ACTIVITY 1. Explain with diagram how does work manager uses hood? ___________________________________________________________________________ ___________________________________________________________________________ 2. How does type of internet connection determine? ___________________________________________________________________________ ___________________________________________________________________________ 10.15 UNIT END QUESTIONS 197 A. Descriptive Questions Short Questions CU IDOL SELF LEARNING MATERIAL (SLM)

1. Explain the importance of Bluetooth. 2. List the functions that can be performed using Bluetooth API. 3. Explain the steps for scanning process in WIFI 4. Explain the process of bonding with Bluetooth device 5. How is monitoring and management of internet take place? Long Questions 1. Explain the significance of WIFI 2. How is android web service used in android? 3. How is local Bluetooth controlled? 4. How is WIFI network managed B. Multiple Choice Questions 1. Using the_______, you can find remote Bluetooth devices a. BluetoothAdapter b. Bluetooth c. Adapter d. Device Adapter 2. Using the known ______ address for a remote device, a connection can be initiated with it at any time without performing discovery a. physical b. MAC c. logical d. list 3. Discovering device is ___________ process 198 a. simple b. synchronous c. asynchronous d. complex CU IDOL SELF LEARNING MATERIAL (SLM)

4. For Bluetooth-enabled devices to transmit data between each other, they must first form a channel of communication using a ________ a. search process b. establish process c. connect process d. pairing process 5. WorkManager is an ______ a. API b. Intent c. Class d. Adapter Answers 1-a, 2-b, 3-c, 4-d, 5-a 10.16 REFERENCES Book References  “Professional Android 4 Application Development” by Reto Meier  “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart  “Professional Android 4 Application Development” by Reto Meier  “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart 199 CU IDOL SELF LEARNING MATERIAL (SLM)

E-References  Introduction to Android: http://developer.android.com/guide/index.html.  Android API: http://developer.android.com/reference/packages.html  Java 6 API: http://docs.oracle.com/javase/6/docs/API/  Android Fundamentals: http://developer.android.com/guide/components/fundamentals.html 200 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook