Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery."— Presentation transcript:

1 Building Apps with Connectivity & the Cloud

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

3 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

4 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().

5 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.

6 It must first determine the connection information for that service, using the resolveService() method. Implement a NsdManager.ResolveListener to pass into this method.

7 Connecting with Wi-Fi Direct Shows you how to find and connect to nearby devices using Wi-Fi Direct. Set Up Application Permissions

8 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.

9 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.

10 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.

11 Connecting to the Network Managing Network Usage Parsing XML Data Performing Network Operations

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

13 Choose an HTTP Client HttpURLConnection and Apache HttpClient Using HttpURLConnection for applications targeted at Gingerbread and higher. 智能手機操作系統 Android 2.3 ,代號 Gingerbread ( 薑餅 )

14 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.

15 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.

16 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.

17 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

18 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

19 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.

20 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).

21 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)

22 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 acti on (introduced in Android 4.0) to indicate that your application defines an activity that offers options to control data usage.

23 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.

24 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.

25 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.

26 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.

27 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.

28 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.

29 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

30 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

31 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.

32

33 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.

34 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.

35 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

36 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

37

38 Syncing to the Cloud Using the Backup API Making the Most of Google Cloud Messaging

39 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.

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

41 END


Download ppt "Building Apps with Connectivity & the Cloud. Connecting Devices Wirelessly Performing Network Operations Transferring Data Without Draining the Battery."

Similar presentations


Ads by Google