0% found this document useful (0 votes)
24 views40 pages

Internet Connection

The document discusses connecting to the internet and performing background tasks on Android. It covers checking for an internet connection, creating a worker thread to perform network operations asynchronously, building a URI for a request, making an HTTP connection, downloading data, and processing results on the background thread to avoid blocking the UI. It also provides best practices for security when making network requests.

Uploaded by

Arjun Ramavath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views40 pages

Internet Connection

The document discusses connecting to the internet and performing background tasks on Android. It covers checking for an internet connection, creating a worker thread to perform network operations asynchronously, building a URI for a request, making an HTTP connection, downloading data, and processing results on the background thread to avoid blocking the UI. It also provides best practices for security when making network requests.

Uploaded by

Arjun Ramavath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Android Developer Fundamentals V2

Background
Tasks
Lesson 7

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 1
connection
License.
7.2 Internet connection

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
connection
License.
Steps to connect to the Internet
1. Add permissions to Android Manifest
2. Check Network Connection
3. Create Worker Thread
4. Implement background task
a. Create URI
b. Make HTTP Connection
c. Connect and GET Data
5. Process results
a. Parse Results

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
connection
License.
Security best practices for network operations:

• Use appropriate protocols for sensitive data. For example for secure web traffic, use the
HttpsURLConnection subclass of HttpURLConnection .

• Use HTTPS instead of HTTP anywhere that HTTPS is supported on the server, because mobile
devices frequently connect on insecure networks such as public Wi-Fi hotspots. Consider using
SSLSocketClass to implement authenticated, encrypted socket-level communication.

• Don't use localhost network ports to handle sensitive interprocess communication (IPC), because
other applications on the device can access these local ports. Instead, use a mechanism that lets
you use authentication, for example a Service.

• Don't trust data downloaded from HTTP or other insecure protocols. Validate input that's entered
into a WebView and responses to intents that you issue against HTTP.

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 4
connection
License.
Permissions

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
connection
License.
Permissions in AndroidManifest

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

Check Network State


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

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
connection
License.
Manage
Network
Connection

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
connection
License.
Getting Network information
● ConnectivityManager
○ Answers queries about the state of network connectivity
○ Notifies applications when network connectivity changes
● NetworkInfo
○ Describes status of a network interface of a given type
○ Mobile or Wi-Fi

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
connection
License.
Check if network is available
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

if (networkInfo != null && networkInfo.isConnected()) {


// Create background thread to connect and get data
new DownloadWebpageTask().execute(stringUrl);
} else {
textView.setText("No network connection available.");
}

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
connection
License.
Check for WiFi & Mobile
NetworkInfo networkInfo =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConn = networkInfo.isConnected();

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

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
connection
License.
Worker Thread

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
connection
License.
Use Worker Thread

● AsyncTask—very short task, or no result returned to UI


● AsyncTaskLoader—for longer tasks, returns result to UI
● Background Service—later chapter

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
connection
License.
Worker Thread
Always perform network operations on a worker thread, separate from the UI.

For example, in your Java code you could create an AsyncTask (or AsyncTaskLoader )
implementation that opens a network connection and queries an API.

Your main code checks whether a network connection is active. If so, it runs the AsyncTask
in a separate thread, then displays the results in the UI.

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
connection
License.
Background work

In the background task (for example in doInBackground())


1. Create URI
2. Make HTTP Connection
3. Download Data

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
connection
License.
Create URI

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
connection
License.
URI = Uniform Resource Identifier

String that names or locates a particular resource


● file://
● http:// and https://
● content://

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
connection
License.
Sample URL for Google Books API
https://www.googleapis.com/books/v1/volumes?
q=pride+prejudice&maxResults=5&printType=books

Constants for Parameters


final String BASE_URL =
"https://www.googleapis.com/books/v1/volumes?";
final String QUERY_PARAM = "q";
final String MAX_RESULTS = "maxResults";
final String PRINT_TYPE = "printType";
Internet This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 17
connection
License.
Build a URI for the request

Uri builtURI = Uri.parse(BASE_URL).buildUpon()


.appendQueryParameter(QUERY_PARAM, "pride+prejudice")
.appendQueryParameter(MAX_RESULTS, "10")
.appendQueryParameter(PRINT_TYPE, "books")
.build();
URL requestURL = new URL(builtURI.toString());

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
connection
License.
HTTP Client
Connection

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 19
connection
License.
How toa connect
Make connection
to the
from
Internet?
scratch

● Use HttpURLConnection
● Must be done on a separate thread
● Requires InputStreams and try/catch blocks

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 20
connection
License.
Create a HttpURLConnection

HttpURLConnection conn =
(HttpURLConnection) requestURL.openConnection();

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 21
connection
License.
Configure connection

conn.setReadTimeout(10000 /* milliseconds */);


conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 22
connection
License.
Connect and get response
conn.connect();
int response = conn.getResponseCode();

InputStream is = conn.getInputStream();
String contentAsString = convertIsToString(is, len);
return contentAsString;

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 23
connection
License.
Close connection and stream

} finally {
conn.disconnect();
if (is != null) {
is.close();
}
}

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 24
connection
License.
Convert
Response to
String

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 25
connection
License.
Convert input stream into a string
public String convertIsToString(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);
}
Internet This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 26
connection
License.
BufferedReader is more efficient
StringBuilder builder = new StringBuilder();
BufferedReader reader =
new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
if (builder.length() == 0) {
return null;
}
resultString = builder.toString();

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 27
connection
License.
HTTP Client
Connection
Libraries

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 28
connection
License.
How toa connect
Make connection
to the
using
Internet?
libraries

● Use a third party library like OkHttp or Volley


● Can be called on the main thread
● Much less code

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 29
connection
License.
How to connect to the Internet?
Volley
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,


new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Do something with response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {}
});
queue.add(stringRequest);

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 30
connection
License.
OkHttp
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt").build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, final Response response)
throws IOException {
try {
String responseData = response.body().string();
JSONObject json = new JSONObject(responseData);
final String owner = json.getString("name");
} catch (JSONException e) {}
}
});

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 31
connection
License.
Parse Results

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 32
connection
License.
Parsing the results

● Implement method to receive and handle results


( onPostExecute())
● Response is often JSON or XML
Parse results using helper classes
● JSONObject, JSONArray
● XMLPullParser—parses XML

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 33
connection
License.
JSON basics

{
"population":1,252,000,000,
"country":"India",
"cities":["New Delhi","Mumbai","Kolkata","Chennai"]
}

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 34
connection
License.
JSONObject basics

JSONObject jsonObject = new JSONObject(response);


String nameOfCountry = (String) jsonObject.get("country");
long population = (Long) jsonObject.get("population");
JSONArray listOfCities = (JSONArray) jsonObject.get("cities");
Iterator<String> iterator = listOfCities.iterator();
while (iterator.hasNext()) {
// do something
}

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 35
connection
License.
Another JSON example
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}
Internet This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 36
connection
License.
Another JSON example
Get "onclick" value of the 3rd item in the "menuitem" array

JSONObject data = new JSONObject(responseString);


JSONArray menuItemArray =
data.getJSONArray("menuitem");
JSONObject thirdItem =
menuItemArray.getJSONObject(2);
String onClick = thirdItem.getString("onclick");
Internet This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 37
connection
License.
Learn more

● Connect to the Network Guide


● Managing Network Usage Guide
● HttpURLConnection reference
● ConnectivityManager reference
● InputStream reference

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 38
connection
License.
What's Next?

● Concept Chapter: 7.2 Internet connection


● Practical: 7.2 AsyncTask and AsyncTaskLoader

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 39
connection
License.
END

Android Developer Fundamentals V2 40

You might also like