Communication in android

33
Communication in Android by Yuriy Voznyak, Software Engineer eleks.com You can view the presentation on http:// eleksdev.blogspot.com 1

Transcript of Communication in android

Page 1: Communication in android

Communication in Android

by Yuriy Voznyak, Software Engineer

eleks.com

You can view the presentation on

http://eleksdev.blogspot.com

1

Page 2: Communication in android

Agenda● Networking in

Android● Useful Networking

Libraries● Bluetooth● NFC

2

Page 3: Communication in android

Connecting to the NetworkWe are going to learn how to implement a simple application that connects to the network. It explains some of the best practices you should follow in creating even the simplest network-connected app.

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

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

Most network-connected Android apps use HTTP to send and receive data. The Android platform includes the HttpURLConnection client, which supports HTTPS, streaming uploads and downloads, configurable timeouts, IPv6, and connection pooling.

3

Page 4: Communication in android

Check the Network ConnectionBefore your app attempts to connect to the network, it should check to see whether a network connection is available using getActiveNetworkInfo() and isConnected(). Remember, the device may be out of range of a network, or the user may have disabled both Wi-Fi and mobile data access.

ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();if (networkInfo != null && networkInfo.isConnected()) { // fetch data} else { // display error}

4

Page 5: Communication in android

Network Operations on a Separate ThreadNetwork operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread.

private class DownloadWebpageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { try { return downloadUrl(urls[0]); } catch (IOException e) { return "Unable to retrieve web page. URL may be invalid."; } } @Override protected void onPostExecute(String result) { textView.setText(result); // Executes in Main Thread }}

5

Page 6: Communication in android

Connect and Download DataIn 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 calling getInputStream().private String downloadUrl(String myurl) throws IOException { InputStream is = null; int len = 500; // Only display the first 500 characters try { URL url = new URL(myurl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.connect(); // Starts the query Log.d(DEBUG_TAG, "The response code is: " + conn.getResponseCode()); // HTTP Response code is = connection.getInputStream(); return readToString(is, len); // Convert the InputStream into a string; See next slide } finally { if (is != null) is.close(); // Makes sure that the InputStream is close }} 6

Page 7: Communication in android

Convert the InputStream to a Data

7

In the example shown above, the InputStream represents the text of a web page. This is how the example converts the InputStream to a string so that the activity can display it in the UI:public String readToString(InputStream stream, int len) throws IOException, UnsupportedEncodingException { Reader reader = null; reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer);}

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. For example, if you were downloading image data, you might decode and display it like this:

InputStream is = null;… // Get some dataBitmap bitmap = BitmapFactory.decodeStream(is);ImageView imageView = (ImageView) findViewById(R.id.image_view);imageView.setImageBitmap(bitmap);

Page 8: Communication in android

Managing Network UsageIt is important to know 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, such as how often your app syncs data, whether to perform uploads/downloads only when on Wi-Fi, whether to use data while roaming, and so on. With these controls available to them, users are much less likely to disable your app’s access to background data when they approach their limits, because they can instead precisely control how much data your app uses.

8

Page 9: Communication in android

Check a Device's Network ConnectionA device can have various types of network connections. This lesson focuses on using either a Wi-Fi or a mobile network connection. For the full list of possible network types, see ConnectivityManager.

Wi-Fi is typically faster. Also, mobile data is often metered, which can get expensive. A common strategy for apps is to only fetch large data if a Wi-Fi network is available.

Before you perform network operations, it's good practice to check the state of network connectivity. Among other things, this could prevent your app from inadvertently using the wrong radio. If a network connection is unavailable, your application should respond gracefully.

9

Page 10: Communication in android

Network Connection Type ExampleTo check the network connection, you typically use the following classes:

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

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

private static final String DEBUG_TAG = "NetworkStatusExample";ConnectivityManager connMgr = (ConnectivityManager)

getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);boolean isWifiConnected = networkInfo.isConnected();

networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);boolean isMobileConnected = networkInfo.isConnected();

Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConnected);Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConnected);

10

Page 11: Communication in android

Efficient Network AccessUsing the wireless radio to transfer data is potentially one of your app's most significant sources of battery drain. To minimize the battery drain associated with network activity, it's critical that you understand how your connectivity model will affect the underlying radio hardware.

It is good approach to minimize your data connections, use prefetching, and bundle your transfers in order to minimize the battery drain associated with your data transfers.

11

Page 12: Communication in android

The Radio State MachineThe 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.

12

Page 13: Communication in android

How Apps Impact the Radio States

13

For example, 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.

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.

Page 14: Communication in android

Prefetch Data

14

“The single most important measure: transmit as much data as possible in a single burst and then end the connection.”

AT&T LabsBy front loading your transfers, you reduce the number of radio activations required to download the data. As a result you not only conserve battery life, but also improve the latency, lower the required bandwidth, and reduce download times.

Prefetching also provides an improved user experience by minimizing in-app latency caused by waiting for downloads to complete before performing an action or viewing data.

Page 15: Communication in android

Android Libs for Effective Networking

15

Just a small amount of them

● Retrofit● okHttp● Volley● RoboSpice

Page 16: Communication in android

Retrofit Advantages

16

A type-safe HTTP client for Android for REST interfaces

From their site: "Retrofit turns your REST API into a Java interface.” It’s an elegant solution for organizing API calls in a project. The request method and relative URL are added with an annotation, which makes code clean and simple.

With annotations, you can easily add a request body, manipulate the URL or headers and add query parameters.

Adding a return type to a method will make it synchronous, while adding a Callback will allow it to finish asynchronously with success or failure.

Retrofit uses Gson by default, so there is no need for custom parsing. Other converters are supported as well.

Page 17: Communication in android

Retrofit Example

17

public interface RetrofitInterface { @GET("/api/user") User getUser(@Query("user_id") int userId, Callback<User> callback);// asynchronously with a callback

@POST("/api/user/register") User registerUser(@Body User user);// synchronously }

RetrofitInterface retrofitInterface = new RestAdapter.Builder() .setEndpoint(API.API_URL).build().create(RetrofitInterface.class);

// fetch user with id 42 retrofitInterface.getUser(42, new Callback<User>() { @Override public void success(User user, Response response) { }

@Override public void failure(RetrofitError retrofitError) { } });

Page 18: Communication in android

okHttp

18

OkHttp is an modern, fast and efficient Http client which supports HTTP/2 and SPDY and does a lot of stuff for you. Reading how many things OkHttp does it’s a good way to understand how hard networking is: Connection pooling, gziping, caching, recovers from network problems, sync and async calls, redirects, retries … and so on.

OkHttp is a very capable networking tool out of the box, without the need of any REST library (Retrofit, Volley…) and probably is the library most developers would choose if they could only include one library in their projects.

OkHttp sits on top of Okio, a library that complements java.io and java.nio to make it much easier to access, store, and process your data. It provides fast I/O and resizable buffers.

OkHttp depends Okio, but Okio can be used by its own.

Page 19: Communication in android

Volley

19

Volley is a REST client that makes easy common networking tasks. Takes care of requesting, loading, caching, threading, synchronization and some more stuff. It’s ready to deal with JSON, images, caching, raw text and allow some customization.

Volley was design for RPC style network operations that populate the UI. Is good for short operations.

Volley by default uses as transport layer the Apache Http stack on Froyo and HttpURLConnection stack on Gingerbread and above. The reason is there are problems with those http stacks have on different Android versions.

Volley allow us to easily set up OkHttp as its transport layer.

Volley was developed by Google.

Page 20: Communication in android

Volley Example

20

final TextView mTextView = (TextView) findViewById(R.id.text); … // Do something important

// Instantiate the RequestQueue. RequestQueue queue = Volley.newRequestQueue(this); String url ="http://www.google.com";

// Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // Display the first 500 characters of the response string. mTextView.setText("Response is: "+ response.substring(0,500)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mTextView.setText("That didn't work!"); } });

queue.add(stringRequest); // Add the request to the RequestQueue.

Page 21: Communication in android

RoboSpice

21

● perform a REST request to a web service (e.g. GitHub API)● convert JSON results to POJOs (Plain Old Java Object)● cache them on disk● let you control cache expiry● notify you app, on the UI thread, when result is ready.

public class DataListRequest extends SpringAndroidSpiceRequest<DataList> { private String user;

public DataListRequest (String user) { super(DataList.class); this.user = user; }

@Override public DataList loadDataFromNetwork() throws Exception { String url = String.format("https://api.site.com/users/%s/data", user); return getRestTemplate().getForObject(url, DataList.class); }}

Page 22: Communication in android

Relationships

22

Page 23: Communication in android

Bluetooth

23

The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The application framework provides access to the Bluetooth functionality through the Android Bluetooth APIs. These APIs let applications wirelessly connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features.

Using the Bluetooth APIs, an Android application can perform the following:● Scan for other Bluetooth devices● Query the local Bluetooth adapter for paired Bluetooth devices● Establish RFCOMM channels● Connect to other devices through service discovery● Transfer data to and from other devices● Manage multiple connections

Page 24: Communication in android

Bluetooth Permissions

24

In order to use Bluetooth features in your application, you must declare the Bluetooth permission BLUETOOTH. You need this permission to perform any Bluetooth communication.

If you want your app to initiate device discovery or manipulate Bluetooth settings, you must also declare the BLUETOOTH_ADMIN permission. Most applications need this permission solely for the ability to discover local Bluetooth devices. The other abilities granted by this permission should not be used, unless the application is a "power manager" that will modify Bluetooth settings upon user request. If you use BLUETOOTH_ADMIN permission, then you must also have the BLUETOOTH permission.

<uses-permission android:name="android.permission.BLUETOOTH" />

Page 25: Communication in android

Beginning work with Bluetooth

25

Get the BluetoothAdapter

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (mBluetoothAdapter == null) { // Device does not support Bluetooth}

Enable Bluetooth if not enabledif (!mBluetoothAdapter.isEnabled()) { Intent enableBluetoothIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BT);}

Optionally, your application can also listen for the ACTION_STATE_CHANGED broadcast Intent, which the system will broadcast whenever the Bluetooth state has changed. This broadcast contains the extra fields EXTRA_STATE and EXTRA_PREVIOUS_STATE, containing the new and old Bluetooth states, respectively. Possible values for these extra fields are STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF, and STATE_OFF.

Page 26: Communication in android

Discovery

26

Device discovery is a scanning procedure that searches the local area for Bluetooth enabled devices and then requesting some information about each one (this is sometimes referred to as "discovering," "inquiring" or "scanning"). However, a Bluetooth device within the local area will respond to a discovery request only if it is currently enabled to be discoverable. If a device is discoverable, it will respond to the discovery request by sharing some information, such as the device name, class, and its unique MAC address. Using this information, the device performing discovery can then choose to initiate a connection to the discovered device.

Page 27: Communication in android

Querying paired devices

27

Before performing device discovery, its worth querying the set of paired devices to see if the desired device is already known. To do so, call getBondedDevices(). This will return a Set of BluetoothDevices representing paired devices. For example, you can query all paired devices and then show the name of each device to the user:

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Just output Name and Address to log Log.d("Devices Info: ", device.getName() + "\n" + device.getAddress()); } }

Page 28: Communication in android

Connecting to Devices

28

When you want to connect two devices, one must act as a server by holding an open BluetoothServerSocket. The purpose of the server socket is to listen for incoming connection requests and when one is accepted, provide a connected BluetoothSocket. When the BluetoothSocket is acquired from the BluetoothServerSocket, the BluetoothServerSocket can (and should) be discarded, unless you want to accept more connections.

● Get a BluetoothServerSocket by calling the listenUsingRfcommWithServiceRecord(String, UUID).

● Start listening for connection requests by calling accept().● Unless you want to accept additional connections, call close().

See more, e.g. on https://developer.android.com/guide/topics/connectivity/bluetooth.html

Page 29: Communication in android

Bluetooth Profiles

29

You can implement the interface BluetoothProfile to write your own classes to support a particular Bluetooth profile. The Android Bluetooth API provides implementations for the following Bluetooth profiles:

● Headset. The Headset profile provides support for Bluetooth headsets to be used with mobile phones.

● A2DP. The Advanced Audio Distribution Profile (A2DP) profile defines how high quality audio can be streamed from one device to another over a Bluetooth connection.

● Health Device. Android 4.0 (API level 14) introduces support for the Bluetooth Health Device Profile (HDP). This lets you create applications that use Bluetooth to communicate with health devices that support Bluetooth, such as heart-rate monitors, blood meters, thermometers, scales, and so on.

Page 30: Communication in android

Near Field Communication

30

Near Field Communication (NFC) is a set of short-range wireless technologies, typically requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small payloads of data between an NFC tag and an Android-powered device, or between two Android-powered devices.

Tags can range in complexity. Simple tags offer just read and write semantics, sometimes with one-time-programmable areas to make the card read-only. More complex tags offer math operations, and have cryptographic hardware to authenticate access to a sector. The most sophisticated tags contain operating environments, allowing complex interactions with code executing on the tag. The data stored in the tag can also be written in a variety of formats, but many of the Android framework APIs are based around a NFC Forum standard called NDEF (NFC Data Exchange Format).

Page 31: Communication in android

NFC Modes

31

Android-powered devices with NFC simultaneously support three main modes of operation:

● Reader/writer mode, allowing the NFC device to read and/or write passive NFC tags and stickers.

● P2P mode, allowing the NFC device to exchange data with other NFC peers; this operation mode is used by Android Beam.

● Card emulation mode, allowing the NFC device itself to act as an NFC card. The emulated NFC card can then be accessed by an external NFC reader, such as an NFC point-of-sale terminal.

Page 32: Communication in android

NFC: is it all?

32

NFC is a technology which is complex enough.

NFC communication performs through Magnetic Field coupling, like RFID.

Page 33: Communication in android

Inspired by Technology.Driven by Value.

Find us at eleks.com

Have a question? Write to [email protected]

33