Presentation is loading. Please wait.

Presentation is loading. Please wait.

Android Developer Fundamentals V2

Similar presentations


Presentation on theme: "Android Developer Fundamentals V2"— Presentation transcript:

1 Android Developer Fundamentals V2
Internet connection

2 Manage Network Connection

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

4 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

5 Check if network is available
ConnectivityManager connMgr = ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { text1.setText("Connected to "+networkInfo.getTypeName()); } else { text1.setText("No network connection available."); }

6 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();

7 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 Do not implement network related codes in UI thread !!

8 AsyncTask Only a UI thread can create and start an AsyncTask
execute(): start AsyncTasks in serial context Concurrent with UI thread but sequntional with other worker threads. executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) Concurrent with UI and worker threads.

9 Socket Prograaming

10 Server Socket Using a Server Socket we can open a port and wait for incoming connections: ServerSocket listener = new ServerSocket(); listener.bind(new InetSocketAddress(InetAddress.getLocalHost(),9090)); while(true) { Socket socket = listener.accept(); publishProgress(socket); }

11 Client Socket Using a Client Socket we can connect to server on a specific port : Socket s= new Socket(“ ", 7000);

12 Writing data to Socket We can use a StreamWriter object to write data in a socket PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.print(“Hello World”); out.flush();

13 Reading data from Socket
We can use a StreamReader object to read data from a socket BufferedReader in; in =new BufferedReader(new InputStreamReader(socket.getInputStream())); while(socket.isConnected()) { String s=in.readLine(); if(s==null) break; publishProgress(s); } socket.close();

14 Special IP Addresses in Emulator
Router/gateway address Special alias to your host loopback interface (i.e., on your development machine) First DNS server / / Optional second, third and fourth DNS server (if any) The emulated device loopback interface

15 Networking on a single Host
ServerSocket ClientSocket Open port 9090 on localhost Connect to port 7000 on host ( ) HOST Forward port 7000 to port 9090

16 Use adb to forwarding ports
adb path: C:\Users\yourname\AppData\Local\Android\Sdk\platform-tools> adb devices : lists available emulators Forward all incoming packets to port 7000 on Host to port 9090 in emulator-5554 adb -s emulator-5554 forward tcp:7000 tcp:9090

17 URI

18 URI = Uniform Resource Identifier
String that names or locates a particular resource file:// and content://

19 Sample URL for Google Books API
q=pride+prejudice&maxResults=5&printType=books Constants for Parameters final String BASE_URL = " final String QUERY_PARAM = "q"; final String MAX_RESULTS = "maxResults"; final String PRINT_TYPE = "printType";

20 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());

21 HTTP Client Connection

22 Background work In the background task (for example in doInBackground()) Create URI Make HTTP Connection Download Data

23 How to connect to the Internet? Make a connection from scratch
Use HttpURLConnection Must be done on a separate thread Requires InputStreams and try/catch blocks

24 Create a HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) requestURL.openConnection();

25 Configure connection conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true);

26 Connect and get response
conn.connect(); int response = conn.getResponseCode(); InputStream is = conn.getInputStream(); String contentAsString = convertIsToString(is, len); return contentAsString;

27 Close connection and stream
} finally { conn.disconnect(); if (is != null) { is.close(); }

28 Convert Response to String

29 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); }

30 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();

31 Uploading Data setDoOutput(true)
When setDoOutput is true, HttpURLConnection uses HTTP POST requests instead. Open an output stream by calling the getOutputStream() method.

32 HTTP Client Connection Libraries

33 How to connect to the Internet? Make a connection using libraries
Use a third party library like OkHttp or Volley Can be called on the main thread Much less code

34 How to connect to the Internet? Volley
RequestQueue queue = Volley.newRequestQueue(this); String url =" 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() { public void onErrorResponse(VolleyError error) {} }); queue.add(stringRequest);

35 How to connect to the Internet? Volley
We need to add Volley to Gradle: dependencies { ... compile 'com.android.volley:volley:1.1.1' }

36 OkHttp - get OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(" 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) {} } });

37 OkHttp – get OkHttpClient client = new OkHttpClient();
String get(String url) throws IOException { Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); return response.body().string(); }

38 OkHttp - post public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).post(body).build(); Response response = client.newCall(request).execute(); return response.body().string(); }

39 OkHttp - gradle compile 'com.squareup.okhttp3:okhttp:3.12.0'

40 Parse Results

41 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

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

43 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 }

44 Another JSON example {"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }

45 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");

46 END


Download ppt "Android Developer Fundamentals V2"

Similar presentations


Ads by Google