Working sample of Android Address book appAndroidfp 17 enhaddr fm Page 3 Tuesday, June 5, 2012 11: 55 AM17. 2 Test-Driving the Enhanced Address Book AppPreparing a Device to Receive a ContactTo receive a contact from another device that's running the Enhanced Address Book appopen the menu while viewing the contact list, then touch the device's Receive Contactmenu item(Fig. 17.1(a)). a dialog asks your permission to make the device discoverableTouch Yes to make it discoverable for 120 seconds(fig. 17.1(b)). Another device can nowconnect to this device and send a contact. a Toast will appear on the receiving devicewhen a contact is received and the new contact will be displayed in the contact list.a) Touch Receive Contact in the menu tob) Touch Yes in the dialog to make the devicereceive a contact from another devicediscoverable and allow device to receive a contact令D勇11:18令Dm11:19Address BookAddress BookasonJessicaBluetooth permissionrequestMattAn application on your phoneyoIs requesting permIssion toRachelmake your phone discoverableby other Bluetooth devices for120 seconds do you want toResado this?YesNoRichWillia中8Add ContactReceive ContactFig. I7. 1 Selecting the Receive Contact menu item on the receiving device causesAndroid to ask whether the device should be discoverable for l20 secondsSending a ContactTo send a contact to another device that's running the Enhanced Address Book app, firstselect the contact you wish to send to view its details. From the contacts details screenopen the menu and touch Transfer Contact(Fig. 17. 2 ). This displays the DeviceChooserActivity(Fig. 17.3), which immediately searches for nearby Bluetooth devices--if Bluetooth is enabled on the device that launched the device chooser as devices are discoveredthey re displayed in the Device Chooser Activity's ListView. You can also restart thesearch for other devices by touching the Scan for compatible devices Button at the bottomof the screen. When you see the other device that' s running the Enhanced Address Bookapp, touch the device's name to send the contact to that device. Both devices must be running the app for the transfer to occur. Figure 17. 4 shows the receiving device's contact listbefore and after the contact is received201211:55AM4 Chapter 17 Enhanced Address Book AppAddress BookName: PaulPhone:555-555-1357E-maIl:paul@fakeemail.comMain streetTouch transferContact to send thiscontacts information toEdit Contact Delete Contact Transfer Contaanother deviceFig. 17.2 Selecting the Transfer Contact menu item on the sending device学Dm勇11:17ADdress rookDetected DevicesTouch a devicesDroidF4:FC:32:7D:13:3Dcontact to that deviceGT-P7510BC:47:60:FC:57:8E38:E7:D8:2B:11:03Touch this button to re-scanfor nearby devicesScan for compatable devicesFig. 17. 3 List of nearby Bluetooth devices displayed on the sending deviceAndroidfp 17 enhaddr fm Page 5 Tuesday, June 5, 2012 11: 55 AM17.3 Technologies Overview 5a) Contacts list before new contact receivedb) Contacts list after new contact received8令D勇11:198令Dm勇11:19Address BookAddress BookJasonJasonJessicaJessicaMattMattewlyRachelreceived PaulcontactResaRachelResaWilliamRⅰchFig. 17. 4 Receiving device's contacts before and after the new contact is received17.3 Technologies OverviewThis section presents the new technologies that we use in the Enhanced Address Book appThe bluetooth classes are located in the package android.bluetoothGetting a Reference to the bluetooth AdapterIn this app, we use BluetoothAdapter's static method getDefaul tAdapter to obtain anobject that represents the device's bluetooth adapter. You'll use this object to determinewhether Bluetooth is enabled, to"listen" for connections from other devices and to locateother bluetooth devicesDetecting Other bluetooth DevicesTo search for nearby Bluetooth devices, you'll use the BluetoothAdapter's startDiscovery method. Android will perform the discovery task for you and notify you whendevices are found and when the discovery task is completeReceiving broadcast Intents for Found Devices and Discovery CompletionTo get the discovery results, you'll register to receive two broadcast IntentsThe Intent for the action BluetoothAdapter ACTION_FOUND is broadcast foreach Bluetooth device thats discovered. The Intent includes as an extra aBluetoothDevice object that represents a bluetooth-capable deviceThe Intent for the action BluetoothAdapter. ACTION_DISCOVERY_ FINISHED isbroadcast when the scan for devices has completedAndroidfp 17 enhaddr fm Page 6 Tuesday, June 5, 2012 11: 55 AM6 Chapter 17 Enhanced Address Book AppListening For connectionsYou'll use a separate thread to listen for incoming connection requests from other devicesrunning the Enhanced Address Book app. In that thread, you'll call BluetoothAdapter'slistenUsingRfcommWithServiceRecord method, which returns a bluetoothServerSocket that can be used to start listening for connections. The BluetoothServerSocket'saccept method blocks the thread from which it's called and listens for incoming bluctooth connection requests When a connection is received, a bluetooth Socket is returnedThis object contains an InputStream and an Output Stream for communicating with theother device. As you'll see, method listenUsingRfcommWith ServiceRecord receives as anargument a unique identifier that other devices must use to connect to this app on the re-ceiving deviceConnecting to Another DeviceTo connect to another device, you'll use class bluetoothDevice's createRfcommSocketToServiceRecord method, which returns a Bluetooth Socket for communicating withthe remote device. This method requires as an argument a globally unique identifier thatmatches the one passed to bluetoothAdapter's listenUsingRfcommWi th ServiceRecordmethod-this helps ensure that the connection is being made only to another device thatsrunning the Enhanced Address Book app. If the bluetoothSocket is retrieved we call itsconnect method to open a connection to the remote deviceTransferring a ContactOnce we have a connection, we use the bluetooth Socket to get an InputStream on thereceiving device for reading the contact and an OutputStream on the sending device forsending the contact The InputStreams read method is used to obtain the incoming cortact from the remote device. To send a contact we pass a byte buffer representing thatcontact's information to the OutputStream's send methodUsing JSoNObjects to Transmit and Receive dataWe use a JSoNObject(package org. json) to format a contact's data as a String for send-g and to extract the contact 's data on the receiving device17.4 Building the GuI and Resource FilesIn this section, you'll create the Enhanced Address Book app's GUI layout files and modifysome of those that you created in Chapter 10s Address Book app. We show only the newand changed files in the subsections that follow17.4.1 Creating the ProjectBegin by deleting from your eclipse workspace the EnhancedAddress book project that youtest-drove in Section 17.2. To do so, right click the project in the Package Explorer andselect Delete. In the dialog that appears, ensure that delete project contents on disk is notchecked, then click OK. Next, in your computer's file system, copy the Address Book folderfor the Address Book app, rename the copy as EnhancedAddressBook, then import theEnhancedAddress Book project into your workspace using the steps in Section 17.2Androidfp 17 enhaddr fm Page 7 Tuesday, June 5, 2012 11: 55 AM17.4 Building the Gul and Resource Files 717.4.2 AndroidManifest xm1Figure 17.5 shows this app's Androi fest. xml file. There are three new items in thisfile. Lines 6-7 specify two elementsandroid. permission. BLUETOOTH (line 6)allows the app to connect to otherBluetooth-enabled devices that are currently paired with this deviceandroid. permission. BLUETOOTH_ADMIN (line 7)allows the app to discover otherBluetooth-enabled devices and pair with themLines 22-23 specify an element for the new DeviceChooser Activity234manifestxmins:android="http://schemas.androidcom/apk/res/androidpackage="com deitel addressbook android: version Codeandroid: version Name="1.045678931416I718indroid: id="@+id/addcontactitFig. 17.6 Menu for theBook Activity. (Part I of 2.)Androidfp 17 enhaddr fm Page 8 Tuesday, June 5, 2012 11: 55 AM8 Chapter 17 Enhanced Address Book Appandroid: title=@string/ menuitem_add_contact4567890android: icon="@drawable/ic_ menu_addandroid: titleCondensed=" @string/menuitemadd_contactandroid: al phabeticshortcut="a">2menuxmins:android="http://schemas.androidcom/apk/res/android">317 Fig. 17.8 Layout for Device Chooser subclass of ListActivity17.4.6 device_ l ayout xml: Layout for the ListView Items in theDevicechooser listActivity's Listviewigure 17.9 shows the customized TextView that's used to display each item in theDevicechooser activitys listview.2

资源预览