Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
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

Android User Interface
Android User InterfaceAndroid User Interface
Android User Interface
Shakib Hasan Sumon
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
Paul Pajo
 
Introduction to Android ppt
Introduction to Android pptIntroduction to Android ppt
Introduction to Android ppt
Taha Malampatti
 
Android notification
Android notificationAndroid notification
Android notification
Krazy Koder
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
Peter R. Egli
 
Android architecture
Android architectureAndroid architecture
Android architecture
Kartik Kalpande Patil
 
Java API
Java APIJava API
Web fundamentals - part 1
Web fundamentals - part 1Web fundamentals - part 1
Web fundamentals - part 1
Bozhidar Boshnakov
 
Java applet
Java appletJava applet
Java applet
Rohan Gajre
 
Lamport’s algorithm for mutual exclusion
Lamport’s algorithm for mutual exclusionLamport’s algorithm for mutual exclusion
Lamport’s algorithm for mutual exclusion
Neelamani Samal
 
J2ME
J2MEJ2ME
flutter intro.pptx
flutter intro.pptxflutter intro.pptx
flutter intro.pptx
HajerZitouni3
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
S/MIME
S/MIMES/MIME
S/MIME
maria azam
 
Introduction to Google App Engine
Introduction to Google App EngineIntroduction to Google App Engine
Introduction to Google App Engine
rajdeep
 
Components of .NET Framework
Components of .NET FrameworkComponents of .NET Framework
Components of .NET Framework
Roshith S Pai
 
Android OS
Android OSAndroid OS
Android OS
Nitin Ramchandani
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In Android
DivyaKS12
 
Simple Mail Transfer Protocol
Simple Mail Transfer ProtocolSimple Mail Transfer Protocol
Simple Mail Transfer Protocol
Ujjayanta Bhaumik
 
Java Beans
Java BeansJava Beans
Java Beans
Ankit Desai
 

What's hot (20)

Android User Interface
Android User InterfaceAndroid User Interface
Android User Interface
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
Introduction to Android ppt
Introduction to Android pptIntroduction to Android ppt
Introduction to Android ppt
 
Android notification
Android notificationAndroid notification
Android notification
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
 
Android architecture
Android architectureAndroid architecture
Android architecture
 
Java API
Java APIJava API
Java API
 
Web fundamentals - part 1
Web fundamentals - part 1Web fundamentals - part 1
Web fundamentals - part 1
 
Java applet
Java appletJava applet
Java applet
 
Lamport’s algorithm for mutual exclusion
Lamport’s algorithm for mutual exclusionLamport’s algorithm for mutual exclusion
Lamport’s algorithm for mutual exclusion
 
J2ME
J2MEJ2ME
J2ME
 
flutter intro.pptx
flutter intro.pptxflutter intro.pptx
flutter intro.pptx
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
S/MIME
S/MIMES/MIME
S/MIME
 
Introduction to Google App Engine
Introduction to Google App EngineIntroduction to Google App Engine
Introduction to Google App Engine
 
Components of .NET Framework
Components of .NET FrameworkComponents of .NET Framework
Components of .NET Framework
 
Android OS
Android OSAndroid OS
Android OS
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In Android
 
Simple Mail Transfer Protocol
Simple Mail Transfer ProtocolSimple Mail Transfer Protocol
Simple Mail Transfer Protocol
 
Java Beans
Java BeansJava Beans
Java Beans
 

Viewers also liked

Hello android world
Hello android worldHello android world
Hello android world
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
 
Css animation, html5 api
Css animation, html5 apiCss animation, html5 api
Css animation, html5 api
eleksdev
 
Android location and sensors API
Android location and sensors APIAndroid location and sensors API
Android location and sensors API
eleksdev
 

Viewers also liked (6)

Hello android world
Hello android worldHello android world
Hello android world
 
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
 
Css animation, html5 api
Css animation, html5 apiCss animation, html5 api
Css animation, html5 api
 
Android location and sensors API
Android location and sensors APIAndroid location and sensors API
Android location and sensors API
 

Similar to Communication in android

Ki3517881791
Ki3517881791Ki3517881791
Ki3517881791
IJERA Editor
 
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 devices
Victor 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
 

Similar to Communication in android (20)

Ki3517881791
Ki3517881791Ki3517881791
Ki3517881791
 
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 ...
 

More from eleksdev

Frontend basics
Frontend basicsFrontend basics
Frontend basics
eleksdev
 
Advanced styles
Advanced stylesAdvanced styles
Advanced styles
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
 
NoSQL basics
NoSQL basicsNoSQL basics
NoSQL basics
eleksdev
 
tsql
tsqltsql
tsql
eleksdev
 
Sql 04n edited
Sql 04n editedSql 04n edited
Sql 04n edited
eleksdev
 
SQL Grouping, Joins
SQL Grouping, JoinsSQL Grouping, Joins
SQL Grouping, Joins
eleksdev
 

More from eleksdev (20)

Frontend basics
Frontend basicsFrontend basics
Frontend basics
 
Advanced styles
Advanced stylesAdvanced styles
Advanced styles
 
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
 
NoSQL basics
NoSQL basicsNoSQL basics
NoSQL basics
 
tsql
tsqltsql
tsql
 
Sql 04n edited
Sql 04n editedSql 04n edited
Sql 04n edited
 
SQL Grouping, Joins
SQL Grouping, JoinsSQL Grouping, Joins
SQL Grouping, Joins
 

Recently uploaded

Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Erasmo Purificato
 
How Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global ScaleHow Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global Scale
ScyllaDB
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
Knowledge and Prompt Engineering Part 2 Focus on Prompt Design Approaches
Knowledge and Prompt Engineering Part 2 Focus on Prompt Design ApproachesKnowledge and Prompt Engineering Part 2 Focus on Prompt Design Approaches
Knowledge and Prompt Engineering Part 2 Focus on Prompt Design Approaches
Earley Information Science
 
5G bootcamp Sep 2020 (NPI initiative).pptx
5G bootcamp Sep 2020 (NPI initiative).pptx5G bootcamp Sep 2020 (NPI initiative).pptx
5G bootcamp Sep 2020 (NPI initiative).pptx
SATYENDRA100
 
Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1
FellyciaHikmahwarani
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
Stephanie Beckett
 
Performance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy EvertsPerformance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy Everts
ScyllaDB
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
Aurora Consulting
 
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & SolutionsMYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
Linda Zhang
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
KAMAL CHOUDHARY
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
jackson110191
 
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
uuuot
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
Matthew Sinclair
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
Enterprise Wired
 
@Call @Girls Guwahati 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any...
@Call @Girls Guwahati 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any...@Call @Girls Guwahati 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any...
@Call @Girls Guwahati 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any...
kantakumariji156
 

Recently uploaded (20)

Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
 
How Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global ScaleHow Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global Scale
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
Knowledge and Prompt Engineering Part 2 Focus on Prompt Design Approaches
Knowledge and Prompt Engineering Part 2 Focus on Prompt Design ApproachesKnowledge and Prompt Engineering Part 2 Focus on Prompt Design Approaches
Knowledge and Prompt Engineering Part 2 Focus on Prompt Design Approaches
 
5G bootcamp Sep 2020 (NPI initiative).pptx
5G bootcamp Sep 2020 (NPI initiative).pptx5G bootcamp Sep 2020 (NPI initiative).pptx
5G bootcamp Sep 2020 (NPI initiative).pptx
 
Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
 
Performance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy EvertsPerformance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy Everts
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
 
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & SolutionsMYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
 
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
 
@Call @Girls Guwahati 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any...
@Call @Girls Guwahati 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any...@Call @Girls Guwahati 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any...
@Call @Girls Guwahati 🚒 XXXXXXXXXX 🚒 Priya Sharma Beautiful And Cute Girl any...
 

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