building apps with connectivity & the cloud. connecting devices wirelessly performing network...

41
Building Apps with Connectivity & the Cloud

Upload: justin-lang

Post on 23-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Building Apps with Connectivity & the Cloud

Page 2: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• Connecting Devices Wirelessly• Performing Network Operations• Transferring Data Without Draining the Battery• Syncing to the Cloud

Page 3: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Connecting Devices Wirelessly• Network Service Discovery (NSD)• Describes the key APIs for finding and

connecting to other devices from your application.

• Using NSD• Connecting with Wi-Fi Direct• Using Wi-Fi Direct for Service Discovery

Page 4: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Using NSD

• Adding NSD to your app allows your users to identify other devices on the local network that support the services your app requests.

• 1.Setting up a discovery listener with the relevant callbacks

• 2.Making a single asynchronous API call to discoverServices().

Page 5: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• First, instantiate an anonymous class that implements NsdManager.DiscoveryListener

• This snippet does several checks when a service is found.

1. The service name of the found service is compared to the service name of the local service to determine if the device just picked up its own broadcast (which is valid).

2. The service type is checked, to verify it's a type of service your application can connect to.

3. The service name is checked to verify connection to the

correct application.

Page 6: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• It must first determine the connection information for that service, using the resolveService() method.

• Implement a NsdManager.ResolveListener to pass into this method.

Page 7: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Connecting with Wi-Fi Direct

• Shows you how to find and connect to nearby devices using Wi-Fi Direct.

• Set Up Application Permissions• <uses-permission

android:required="true" android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:required="true" android:name="android.permission.CHANGE_WIFI_STATE"/> <uses-permission android:required="true" android:name="android.permission.INTERNET"/>

Page 8: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• Set Up a Broadcast Receiver and Peer-to-Peer Manager

• WIFI_P2P_STATE_CHANGED_ACTION indicates whether Wi-Fi Peer-To-Peer (P2P) is enabled

• WIFI_P2P_PEERS_CHANGED_ACTION indicates that the available peer list has changed.

• WIFI_P2P_CONNECTION_CHANGED_ACTION indicates the state of Wi-Fi P2P connectivity has changed.

• WFIF_P2P_THIS_DEVICE_CHANGED_ACTION indicates this device's configuration details have changed.

• Create a new BroadcastReceiver class that you'll use to listen for changes to the System's Wi-Fi P2P state. In the onReveive() method, add a condition to handle each P2P state change listed above.

Page 9: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Initiate Peer Discovery• discoverPeers() • The WifiP2pManager.Channel you received

back when you initialized the peer-to-peer mManager.

• An implementation of WifiP2pManager. ActionListener with methods the system

invokes for successful and unsuccessful discovery.

Page 10: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Connect to a Peer

• In order to connect to a peer, create a new WifiP2pConfig object, and copy data into it from the WifiP2pDevice representing the device you want to connect to. Then call the connect() method.

Page 11: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• Connecting to the Network• Managing Network Usage• Parsing XML Data

Performing Network Operations

Page 12: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• Note that to perform the network operations described in this lesson, your application manifest must include the following permissions:

• <uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Connecting to the Network

Page 13: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Choose an HTTP Client• HttpURLConnection and Apache HttpClient

• Using HttpURLConnection for applications targeted at Gingerbread and higher.

<Note>智能手機操作系統 Android 2.3,代號 Gingerbread (薑餅 )

Page 14: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Perform Network Operations on a Separate Thread

• To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI.

• AsyncTask• dolnBackground() executes the method downloadUrl(). It passes the web page URL

as a parameter. The method downloadUrl() fetches and processes the web page content. When it finishes, it passes back a result string.

• onPostExecute() takes the returned string and displays it in the UI.• onPostExecute() takes the returned string and displays it in the UI.

Page 15: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• When users click the button that invokes myClickHandler(), the app passes the specified URL to the AsyncTask subclass DownloadWebpageTask.

• The AsyncTask method doInBackground() calls the downloadUrl() method.

• The downloadUrl() method takes a URL string as a parameter and uses it to create a URL object.

• The URL object is used to establish an HttpURLConnection.• Once the connection has been established,

the HttpURLConnection object fetches the web page content as an InputStream.

• The InputStream is passed to the readIt() method, which converts the stream to a string.

• Finally, the AsyncTask's onPostExecute() method displays the string in the main activity's UI.

Page 16: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Connect and Download Data• In your thread that performs your network transactions,

you can use HttpURLConnection to perform a GET and download your data. After you call connect(), you can get an InputStream of the data by callinggetInputStream()

• the doInBackground() method calls the method downloadUrl(). ThedownloadUrl() method takes the given URL and uses it to connect to the network via HttpURLConnection. Once a connection has been established, the app uses the method getInputStream() to retrieve the data as anInputStream.

Page 17: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Convert the InputStream to a String

• An InputStream is a readable source of bytes. Once you get an InputStream, it's common to decode or convert it into a target data type

Page 18: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Managing Network Usage

• Describes how to write applications that have fine-grained control over their usage of network resources.

• If your application performs a lot of network operations, you should provide user settings that allow users to control your app's data habits

Page 19: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Check a Device's Network Connection

• A device can have various types of network connections.

• Wi_Fi and Mobile network• A common strategy for apps is to only fetch

large data if a Wi-Fi network is available.

Page 20: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• To check the network connection, you typically use the following classes:

• 1. ConnectivityManager : Answers queries about the state of network connectivity. It also notifies applications when network connectivity changes.

• 2. NetworkInfo : Describes the status of a network interface of a given type (currently either Mobile or Wi-Fi).

Page 21: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• You should not base decisions on whether a network is "available." You should always check isConnected() before performing network operations

• A more concise way of checking whether a network interface is available is as follows. The method getActiveNetworkInfo() returns a NetworkInfo instance representing the first connected network interface it can find, or null if none of the interfaces is connected (meaning that an internet connection is not available)

Page 22: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• You can implement a preferences activity that gives users explicit control over your app's usage of network resources.

• Your manifest must have the right permissions and intent filters.

• You can declare the intent filter for the ACTION_MANAGE_NETWORK_USAGE action (introduced in Android 4.0) to indicate that your application defines an activity that offers options to control data usage.

Page 23: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Respond to Preference Changes• When the user changes preferences in the

settings screen, it typically has consequences for the app's behavior.

• if there is a match between the setting and the device's network connection, the app downloads the feed and refreshes the display.

Page 24: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Detect Connection Changes• When the device's network connection

changes, NetworkReceiver intercepts the action CONNECTIVITY_ACTION , determines what the network connection status is, and sets the flags wifiConnected and mobileConnected to true/false accordingly.

• Setting up a BroadcastReceiver that gets called unnecessarily can be a drain on system resources.

Page 25: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Parsing XML Data

• Extensible Markup Language (XML) is a set of rules for encoding documents in machine-readable form.

• Choose a Parser• We recommend XmlPullParser , which is an

efficient and maintainable way to parse XML on Android.

Page 26: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Analyze the Feed

• The first step in parsing a feed is to decide which fields you're interested in. The parser extracts data for those fields and ignores the rest.

Page 27: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Instantiate the Parser

• Instantiate a parser and kick off the parsing process.

• A parser is initialized to not process namespaces, and to use the provided InputStream as its input.

Page 28: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Read the Feed• The readFeed() method does the actual work

of processing the feed. It looks for elements tagged "entry" as a starting point for recursively processing the feed. If a tag isn't an entry tag, it skips it. Once the whole feed has been recursively processed, readFeed() returns a List containing the entries (including nested data members) it extracted from the feed. This List is then returned by the parser.

Page 29: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Parse XML

• As described in Analyze the Feed, identify the tags you want to include in your app. This example extracts data for the entry tag and its nested tags title, link, and summary.

• Create the following methods:A "read" method for each tag you're interested in.Methods to extract data for each different type of tag and to advance the parser to the next tag

Page 30: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Transferring Data Without Draining the Battery

• Optimizing Downloads for Efficient Network Access

• Minimizing the Effect of Regular Updates• Redundant Downloads are Redundant• Modifying your Download Patterns Based on

the Connectivity Type

Page 31: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Optimizing Downloads for Efficient Network Access

• The Radio State Machine• The state machine for a typical 3G network radio

consists of three energy states:• Full power: Used when a connection is active,

allowing the device to transfer data at its highest possible rate.

• Low power: An intermediate state that uses around 50% of the battery power at the full state.

• Standby: The minimal energy state during which no network connection is active or required.

Page 32: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery
Page 33: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• The general principles and resulting best practices are applicable for all wireless radio implementations

• Vary based on the wireless radio technology employed (2G, 3G, LTE, etc.)

• This approach is particularly effective for typical web browsing as it prevents unwelcome latency while users browse the web.

Page 34: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

How Apps Impact the Radio State Machine

• In the case of the typical 3G radio state machine described above, it will remain at full power for the duration of your transfer—plus an additional 5 seconds of tail time—followed by 12 seconds at the low energy state. So for a typical 3G device, every data transfer session will cause the radio to draw energy for almost 20 seconds.

Page 35: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• In practice, this means an app that transfers unbundled data for 1 second every 18 seconds will keep the wireless radio perpetually active, moving it back to high power just as it was about to become idle. As a result, every minute it will consume battery at the high power state for 18 seconds, and at the low power state for the remaining 42 seconds.--------Unbundled Transfer

Page 36: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• By comparison, the same app that bundles transfers of 3 seconds of every minute will keep the radio in the high power state for only 8 seconds, and will keep it in the low power state for only an additional 12 seconds.------------Bundled Transfer

Page 37: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery
Page 38: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Syncing to the Cloud

• Using the Backup API• Making the Most of Google Cloud Messaging

Page 39: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

Using the Backup API

• When a user purchases a new device or resets their existing one, they might expect that when Google Play restores your app back to their device during the initial setup, the previous data associated with the app restores as well. By default, that doesn't happen and all the user's accomplishments or settings in your app are lost.

Page 40: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

• Register for the Android Backup Service• Write Your Backup Agent• Request a Backup• Restore from a Backup

Page 41: Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery

END