0% found this document useful (0 votes)
13 views38 pages

07.2 Internet Connection

Uploaded by

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

07.2 Internet Connection

Uploaded by

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

Android Developer Fundamentals V2

Background
Tasks
Lesson 7

Internet This work is licensed under a


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

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 2
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 3
Fundamentals V2 International License
Permissions

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 4
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 5
Fundamentals V2 International License
Manage
Network
Connection

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 6
Fundamentals V2 International 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
Internet This work is licensed under a
Android Developer connection
Creative Commons Attribution 4.0 7
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 8
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 9
Fundamentals V2 International License
Worker
Thread

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 10
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 11
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 12
Fundamentals V2 International License
Create URI

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 13
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 14
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 15
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 16
Fundamentals V2 International License
HTTP Client
Connection

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 17
Fundamentals V2 International License
How to
Make a connect
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


Android Developer connection
Creative Commons Attribution 4.0 18
Fundamentals V2 International License
Create a HttpURLConnection

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

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 19
Fundamentals V2 International License
Configure connection

conn.setReadTimeout(10000 /* milliseconds
*/);
conn.setConnectTimeout(15000 /* milliseconds
*/);
conn.setRequestMethod("GET");
conn.setDoInput(true);
Internet This work is licensed under a
Android Developer connection
Creative Commons Attribution 4.0 20
Fundamentals V2 International 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
Android Developer connection
Creative Commons Attribution 4.0 21
Fundamentals V2 International License
Close connection and stream

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

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 22
Fundamentals V2 International License
Convert
Response to
String

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 23
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 24
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 25
Fundamentals V2 International License
HTTP Client
Connection
Libraries

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 26
Fundamentals V2 International License
Maketo
How a connect
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


Android Developer connection
Creative Commons Attribution 4.0 27
Fundamentals V2 International 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
Android Developer connection
Creative Commons Attribution 4.0 28
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 29
Fundamentals V2 International License
Parse
Results

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 30
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 31
Fundamentals V2 International License
JSON basics

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

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 32
Fundamentals V2 International 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
Android Developer connection
Creative Commons Attribution 4.0 33
Fundamentals V2 International 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
Android Developer connection
Creative Commons Attribution 4.0 34
Fundamentals V2 International 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);
Internet This work is licensed under a
Android Developer connection
Creative Commons Attribution 4.0 35
Fundamentals V2 International 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


Android Developer connection
Creative Commons Attribution 4.0 36
Fundamentals V2 International License
What's Next?

● Concept Chapter: 7.2 Internet connection


● Practical: 7.2 AsyncTask and AsyncTaskLoader

Internet This work is licensed under a


Android Developer connection
Creative Commons Attribution 4.0 37
Fundamentals V2 International License
END

Android Developer Fundamentals V2 38

You might also like