SlideShare a Scribd company logo
Communication in Android
by Yuriy Voznyak, Software Engineer
eleks.com
You can view the presentation on http://eleksdev.blogspot.com
1
Agenda
● Networking in Android
● Useful Networking
Libraries
● Bluetooth
● NFC
2
Connecting to the Network
We 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
Check the Network Connection
Before 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
Network Operations on a Separate Thread
Network 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
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 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
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 data
Bitmap bitmap = BitmapFactory.decodeStream(is);
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setImageBitmap(bitmap);
Managing Network Usage
It 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
Check a Device's Network Connection
A 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
Network Connection Type Example
To 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
Efficient Network Access
Using 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
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.
12
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.
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 Labs
By 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.
Android Libs for Effective Networking
15
Just a small amount of them
● Retrofit
● okHttp
● Volley
● RoboSpice
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.
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) {
}
});
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.
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.
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.
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);
}
}
Relationships
22
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
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" />
Beginning work with Bluetooth
25
Get the BluetoothAdapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
Enable Bluetooth if not enabled
if (!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.
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.
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());
}
}
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
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.
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).
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.
NFC: is it all?
32
NFC is a technology which is complex enough.
NFC communication performs through Magnetic Field coupling, like RFID.
Inspired by Technology.
Driven by Value.
Find us at eleks.com Have a question? Write to eleksinfo@eleks.com
33

More Related Content

What's hot

cloud computing preservity
cloud computing preservitycloud computing preservity
cloud computing preservity
chennuruvishnu
 
Seminar presentation on embedded web technology
Seminar presentation on embedded web technologySeminar presentation on embedded web technology
Seminar presentation on embedded web technology
Ranol R C
 
Attributes based encryption with verifiable outsourced decryption
Attributes based encryption with verifiable outsourced decryptionAttributes based encryption with verifiable outsourced decryption
Attributes based encryption with verifiable outsourced decryption
KaashivInfoTech Company
 
Towards secure and dependable storage service in cloud
Towards secure and dependable storage service in cloudTowards secure and dependable storage service in cloud
Towards secure and dependable storage service in cloudsibidlegend
 
PURSe and the PURSe Portlets
PURSe and the PURSe PortletsPURSe and the PURSe Portlets
PURSe and the PURSe Portlets
marcuschristie
 
Open Programmable Architecture for Java-enabled Network Devices
Open Programmable Architecture for Java-enabled Network DevicesOpen Programmable Architecture for Java-enabled Network Devices
Open Programmable Architecture for Java-enabled Network Devices
Tal Lavian Ph.D.
 
Location Provider with Privacy Using Localized Server and GPS
  Location Provider with Privacy Using Localized Server and GPS   Location Provider with Privacy Using Localized Server and GPS
Location Provider with Privacy Using Localized Server and GPS
Editor IJCATR
 
FRONT END AND BACK END DATABASE SECURITY IN THREE TIER WEB APPLICATION
FRONT END AND BACK END DATABASE SECURITY IN THREE TIER WEB APPLICATIONFRONT END AND BACK END DATABASE SECURITY IN THREE TIER WEB APPLICATION
FRONT END AND BACK END DATABASE SECURITY IN THREE TIER WEB APPLICATION
ijiert bestjournal
 
Ki3517881791
Ki3517881791Ki3517881791
Ki3517881791
IJERA Editor
 
Narrative of digital signature technology and moving forward
Narrative of digital signature technology and moving forwardNarrative of digital signature technology and moving forward
Narrative of digital signature technology and moving forward
Conference Papers
 

What's hot (10)

cloud computing preservity
cloud computing preservitycloud computing preservity
cloud computing preservity
 
Seminar presentation on embedded web technology
Seminar presentation on embedded web technologySeminar presentation on embedded web technology
Seminar presentation on embedded web technology
 
Attributes based encryption with verifiable outsourced decryption
Attributes based encryption with verifiable outsourced decryptionAttributes based encryption with verifiable outsourced decryption
Attributes based encryption with verifiable outsourced decryption
 
Towards secure and dependable storage service in cloud
Towards secure and dependable storage service in cloudTowards secure and dependable storage service in cloud
Towards secure and dependable storage service in cloud
 
PURSe and the PURSe Portlets
PURSe and the PURSe PortletsPURSe and the PURSe Portlets
PURSe and the PURSe Portlets
 
Open Programmable Architecture for Java-enabled Network Devices
Open Programmable Architecture for Java-enabled Network DevicesOpen Programmable Architecture for Java-enabled Network Devices
Open Programmable Architecture for Java-enabled Network Devices
 
Location Provider with Privacy Using Localized Server and GPS
  Location Provider with Privacy Using Localized Server and GPS   Location Provider with Privacy Using Localized Server and GPS
Location Provider with Privacy Using Localized Server and GPS
 
FRONT END AND BACK END DATABASE SECURITY IN THREE TIER WEB APPLICATION
FRONT END AND BACK END DATABASE SECURITY IN THREE TIER WEB APPLICATIONFRONT END AND BACK END DATABASE SECURITY IN THREE TIER WEB APPLICATION
FRONT END AND BACK END DATABASE SECURITY IN THREE TIER WEB APPLICATION
 
Ki3517881791
Ki3517881791Ki3517881791
Ki3517881791
 
Narrative of digital signature technology and moving forward
Narrative of digital signature technology and moving forwardNarrative of digital signature technology and moving forward
Narrative of digital signature technology and moving forward
 

Similar to Communication in android

Configuring LIFA for remote communication using web architecture
Configuring LIFA for remote communication using web architecture Configuring LIFA for remote communication using web architecture
Configuring LIFA for remote communication using web architecture
Ami Goswami
 
Manual redes - network programming with j2 me wireless devices
Manual   redes - network programming with j2 me wireless devicesManual   redes - network programming with j2 me wireless devices
Manual redes - network programming with j2 me wireless devicesVictor Garcia Vara
 
Doug Sillars on App Optimization
Doug Sillars on App OptimizationDoug Sillars on App Optimization
Doug Sillars on App Optimization
wipjam
 
ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA
ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATAANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA
ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA
IJCSEIT Journal
 
mumble: Framework for Seamless Message Transfer on Smartphones
mumble: Framework for Seamless Message Transfer on Smartphonesmumble: Framework for Seamless Message Transfer on Smartphones
mumble: Framework for Seamless Message Transfer on Smartphones
Anand Bhojan
 
Offline and Online Bank Data Synchronization System
Offline and Online Bank Data Synchronization SystemOffline and Online Bank Data Synchronization System
Offline and Online Bank Data Synchronization System
ijceronline
 
Configuring lifa for remote communication using web architecture
Configuring lifa for remote communication using web architectureConfiguring lifa for remote communication using web architecture
Configuring lifa for remote communication using web architecture
Vatsal N Shah
 
Introduction to back-end
Introduction to back-endIntroduction to back-end
Introduction to back-end
Mosaab Ehab
 
Contemporary Energy Optimization for Mobile and Cloud Environment
Contemporary Energy Optimization for Mobile and Cloud EnvironmentContemporary Energy Optimization for Mobile and Cloud Environment
Contemporary Energy Optimization for Mobile and Cloud Environment
ijceronline
 
Assessment to Delegate the Task to Cloud for Increasing Energy Efficiency of ...
Assessment to Delegate the Task to Cloud for Increasing Energy Efficiency of ...Assessment to Delegate the Task to Cloud for Increasing Energy Efficiency of ...
Assessment to Delegate the Task to Cloud for Increasing Energy Efficiency of ...
IRJET Journal
 
Optimize Data Connectivity in .NET Applications
Optimize Data Connectivity in .NET ApplicationsOptimize Data Connectivity in .NET Applications
Optimize Data Connectivity in .NET Applications
Abhishek Kant
 
Java Networking
Java NetworkingJava Networking
Java Networking
68SachinYadavSYCS
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
Matteo Bonifazi
 
How do I - Networking and Webservices - Transcript.pdf
How do I - Networking and Webservices - Transcript.pdfHow do I - Networking and Webservices - Transcript.pdf
How do I - Networking and Webservices - Transcript.pdf
ShaiAlmog1
 
Decision to offload the task to Cloud for increasing energy efficiency of Mob...
Decision to offload the task to Cloud for increasing energy efficiency of Mob...Decision to offload the task to Cloud for increasing energy efficiency of Mob...
Decision to offload the task to Cloud for increasing energy efficiency of Mob...
IRJET Journal
 
Energy Optimized Link Selection Algorithm for Mobile Cloud Computing
Energy Optimized Link Selection Algorithm for Mobile Cloud ComputingEnergy Optimized Link Selection Algorithm for Mobile Cloud Computing
Energy Optimized Link Selection Algorithm for Mobile Cloud Computing
Eswar Publications
 
Android Trainning Session 2
Android Trainning  Session 2Android Trainning  Session 2
Android Trainning Session 2
Shanmugapriya D
 
Wirelessmicroservers 111212193716-phpapp02(1)
Wirelessmicroservers 111212193716-phpapp02(1)Wirelessmicroservers 111212193716-phpapp02(1)
Wirelessmicroservers 111212193716-phpapp02(1)gunasagar123
 
Weighted Round Robin Load Balancer to Enhance Web Server Cluster in OpenFlow ...
Weighted Round Robin Load Balancer to Enhance Web Server Cluster in OpenFlow ...Weighted Round Robin Load Balancer to Enhance Web Server Cluster in OpenFlow ...
Weighted Round Robin Load Balancer to Enhance Web Server Cluster in OpenFlow ...
TELKOMNIKA JOURNAL
 
Load Balance in Data Center SDN Networks
Load Balance in Data Center SDN Networks Load Balance in Data Center SDN Networks
Load Balance in Data Center SDN Networks
IJECEIAES
 

Similar to Communication in android (20)

Configuring LIFA for remote communication using web architecture
Configuring LIFA for remote communication using web architecture Configuring LIFA for remote communication using web architecture
Configuring LIFA for remote communication using web architecture
 
Manual redes - network programming with j2 me wireless devices
Manual   redes - network programming with j2 me wireless devicesManual   redes - network programming with j2 me wireless devices
Manual redes - network programming with j2 me wireless devices
 
Doug Sillars on App Optimization
Doug Sillars on App OptimizationDoug Sillars on App Optimization
Doug Sillars on App Optimization
 
ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA
ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATAANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA
ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA
 
mumble: Framework for Seamless Message Transfer on Smartphones
mumble: Framework for Seamless Message Transfer on Smartphonesmumble: Framework for Seamless Message Transfer on Smartphones
mumble: Framework for Seamless Message Transfer on Smartphones
 
Offline and Online Bank Data Synchronization System
Offline and Online Bank Data Synchronization SystemOffline and Online Bank Data Synchronization System
Offline and Online Bank Data Synchronization System
 
Configuring lifa for remote communication using web architecture
Configuring lifa for remote communication using web architectureConfiguring lifa for remote communication using web architecture
Configuring lifa for remote communication using web architecture
 
Introduction to back-end
Introduction to back-endIntroduction to back-end
Introduction to back-end
 
Contemporary Energy Optimization for Mobile and Cloud Environment
Contemporary Energy Optimization for Mobile and Cloud EnvironmentContemporary Energy Optimization for Mobile and Cloud Environment
Contemporary Energy Optimization for Mobile and Cloud Environment
 
Assessment to Delegate the Task to Cloud for Increasing Energy Efficiency of ...
Assessment to Delegate the Task to Cloud for Increasing Energy Efficiency of ...Assessment to Delegate the Task to Cloud for Increasing Energy Efficiency of ...
Assessment to Delegate the Task to Cloud for Increasing Energy Efficiency of ...
 
Optimize Data Connectivity in .NET Applications
Optimize Data Connectivity in .NET ApplicationsOptimize Data Connectivity in .NET Applications
Optimize Data Connectivity in .NET Applications
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 
How do I - Networking and Webservices - Transcript.pdf
How do I - Networking and Webservices - Transcript.pdfHow do I - Networking and Webservices - Transcript.pdf
How do I - Networking and Webservices - Transcript.pdf
 
Decision to offload the task to Cloud for increasing energy efficiency of Mob...
Decision to offload the task to Cloud for increasing energy efficiency of Mob...Decision to offload the task to Cloud for increasing energy efficiency of Mob...
Decision to offload the task to Cloud for increasing energy efficiency of Mob...
 
Energy Optimized Link Selection Algorithm for Mobile Cloud Computing
Energy Optimized Link Selection Algorithm for Mobile Cloud ComputingEnergy Optimized Link Selection Algorithm for Mobile Cloud Computing
Energy Optimized Link Selection Algorithm for Mobile Cloud Computing
 
Android Trainning Session 2
Android Trainning  Session 2Android Trainning  Session 2
Android Trainning Session 2
 
Wirelessmicroservers 111212193716-phpapp02(1)
Wirelessmicroservers 111212193716-phpapp02(1)Wirelessmicroservers 111212193716-phpapp02(1)
Wirelessmicroservers 111212193716-phpapp02(1)
 
Weighted Round Robin Load Balancer to Enhance Web Server Cluster in OpenFlow ...
Weighted Round Robin Load Balancer to Enhance Web Server Cluster in OpenFlow ...Weighted Round Robin Load Balancer to Enhance Web Server Cluster in OpenFlow ...
Weighted Round Robin Load Balancer to Enhance Web Server Cluster in OpenFlow ...
 
Load Balance in Data Center SDN Networks
Load Balance in Data Center SDN Networks Load Balance in Data Center SDN Networks
Load Balance in Data Center SDN Networks
 

More from eleksdev

Lecture android best practices
Lecture   android best practicesLecture   android best practices
Lecture android best practices
eleksdev
 
Angular. presentation
Angular. presentationAngular. presentation
Angular. presentation
eleksdev
 
Lecture java basics
Lecture   java basicsLecture   java basics
Lecture java basics
eleksdev
 
Frontend basics
Frontend basicsFrontend basics
Frontend basics
eleksdev
 
Advanced styles
Advanced stylesAdvanced styles
Advanced styles
eleksdev
 
Css animation, html5 api
Css animation, html5 apiCss animation, html5 api
Css animation, html5 api
eleksdev
 
Improving rpc bkp
Improving rpc bkpImproving rpc bkp
Improving rpc bkp
eleksdev
 
G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2
eleksdev
 
G rpc lection1
G rpc lection1G rpc lection1
G rpc lection1
eleksdev
 
Windows service
Windows serviceWindows service
Windows service
eleksdev
 
Rpc
RpcRpc
DAL
DALDAL
Aspnet core
Aspnet coreAspnet core
Aspnet core
eleksdev
 
Web service lecture
Web service lectureWeb service lecture
Web service lecture
eleksdev
 
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
eleksdev
 
SDLC. QA Role
SDLC. QA RoleSDLC. QA Role
SDLC. QA Role
eleksdev
 
SDLC. UX Role
SDLC. UX RoleSDLC. UX Role
SDLC. UX Role
eleksdev
 
SDLC. PM Role
SDLC. PM RoleSDLC. PM Role
SDLC. PM Role
eleksdev
 
SDLC. BA Role
SDLC. BA RoleSDLC. BA Role
SDLC. BA Role
eleksdev
 
Version control
Version controlVersion control
Version control
eleksdev
 

More from eleksdev (20)

Lecture android best practices
Lecture   android best practicesLecture   android best practices
Lecture android best practices
 
Angular. presentation
Angular. presentationAngular. presentation
Angular. presentation
 
Lecture java basics
Lecture   java basicsLecture   java basics
Lecture java basics
 
Frontend basics
Frontend basicsFrontend basics
Frontend basics
 
Advanced styles
Advanced stylesAdvanced styles
Advanced styles
 
Css animation, html5 api
Css animation, html5 apiCss animation, html5 api
Css animation, html5 api
 
Improving rpc bkp
Improving rpc bkpImproving rpc bkp
Improving rpc bkp
 
G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2
 
G rpc lection1
G rpc lection1G rpc lection1
G rpc lection1
 
Windows service
Windows serviceWindows service
Windows service
 
Rpc
RpcRpc
Rpc
 
DAL
DALDAL
DAL
 
Aspnet core
Aspnet coreAspnet core
Aspnet core
 
Web service lecture
Web service lectureWeb service lecture
Web service lecture
 
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
 
SDLC. QA Role
SDLC. QA RoleSDLC. QA Role
SDLC. QA Role
 
SDLC. UX Role
SDLC. UX RoleSDLC. UX Role
SDLC. UX Role
 
SDLC. PM Role
SDLC. PM RoleSDLC. PM Role
SDLC. PM Role
 
SDLC. BA Role
SDLC. BA RoleSDLC. BA Role
SDLC. BA Role
 
Version control
Version controlVersion control
Version control
 

Recently uploaded

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 

Recently uploaded (20)

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 

Communication in android

  • 1. Communication in Android by Yuriy Voznyak, Software Engineer eleks.com You can view the presentation on http://eleksdev.blogspot.com 1
  • 2. Agenda ● Networking in Android ● Useful Networking Libraries ● Bluetooth ● NFC 2
  • 3. Connecting to the Network We 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
  • 4. Check the Network Connection Before 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
  • 5. Network Operations on a Separate Thread Network 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
  • 6. 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 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
  • 7. 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 data Bitmap bitmap = BitmapFactory.decodeStream(is); ImageView imageView = (ImageView) findViewById(R.id.image_view); imageView.setImageBitmap(bitmap);
  • 8. Managing Network Usage It 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
  • 9. Check a Device's Network Connection A 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
  • 10. Network Connection Type Example To 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
  • 11. Efficient Network Access Using 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
  • 12. 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. 12
  • 13. 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.
  • 14. 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 Labs By 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.
  • 15. Android Libs for Effective Networking 15 Just a small amount of them ● Retrofit ● okHttp ● Volley ● RoboSpice
  • 16. 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.
  • 17. 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) { } });
  • 18. 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.
  • 19. 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.
  • 20. 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.
  • 21. 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); } }
  • 23. 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
  • 24. 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" />
  • 25. Beginning work with Bluetooth 25 Get the BluetoothAdapter BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth } Enable Bluetooth if not enabled if (!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.
  • 26. 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.
  • 27. 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()); } }
  • 28. 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
  • 29. 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.
  • 30. 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).
  • 31. 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.
  • 32. NFC: is it all? 32 NFC is a technology which is complex enough. NFC communication performs through Magnetic Field coupling, like RFID.
  • 33. Inspired by Technology. Driven by Value. Find us at eleks.com Have a question? Write to eleksinfo@eleks.com 33

Editor's Notes

  1. Java is not number one in Eleks though.
  2. Java is not number one in Eleks though.
  3. Java is not number one in Eleks though.
  4. No tuple