Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Android Fundamentals #5- Networking

Android Fundamentals #5- Networking

Britt Barak

November 28, 2017
Tweet

More Decks by Britt Barak

Other Decks in Programming

Transcript

  1. Android Academy Staff Yonatan Levin Google Developer Expert & CTO

    @ KolGene Britt Barak Google Developer Expert Yossi Segev Mobile engineer Colu
  2. AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" />

    <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  3. • Hypertext Transfer Protocol. • Stateless protocol. • By default:

    HTTP uses port 80 and HTTPS uses port 443 HTTP
  4. HTTP Verb • GET: fetch an existing resource, by the

    URL’s info. • POST: create a new resource, by the request’s payload. • PUT: update an existing resource, by the request’s payload. • DELETE: delete an existing resource.
  5. Status Code 1xx: Informational Messages - Expect: 100-continue 2xx: Successful

    - 200 OK, 204 No Content 3xx: Redirection - Additional action needed. Commonly go to another url. 4xx: Client Error - 404 Not Found, 400 Bad Request,401 Unauthorized, 5xx: Server Error - 503 Service Unavailable
  6. URL url = new URL(myurl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true); // Starts the query urlConnection.connect(); int response = urlConnection.getResponseCode(); is = urlConnection.getInputStream(); // Convert the InputStream into a string String contentAsString = readIt(is, len); return contentAsString;
  7. @GET("venues/explore") Call<VenuesResponse> getVenues( @QueryMap Map<String, String> options); @GET("venues/{VENUE_ID}/photos") Call<PhotosResponse> getPhotos(

    @Path("VENUE_ID") String venueId); //an example I made up :) @POST("venues/add") Call<AddVenueResponse> addVenue( @Header("Authorization") String authorization, @Body("name") Venue venue);
  8. "groups": [ { "type": "Recommended Places", "name": "recommended", "items": [

    { "reasons": { "count": 0, "items": [ { "summary": "This spot is popular", "type": "general", "reasonName": "globalInteractionReason" } ] }, "venue": {
  9. class Venue { } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact":

    { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }
  10. class Venue { String id; } "venue": { "id":"56d92e05498e6c54b6325b19", "name":

    "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }
  11. class Venue { String id; String name; } "venue": {

    "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }
  12. class Venue { String id; String name; ContactInfo contact; }

    class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }
  13. class Venue { String id; String name; @SerializedName("contact") ContactInfo contactInfo;

    } class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }
  14. class Venue { String id; String name; @SerializedName("contact") ContactInfo contactInfo;

    } class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }
  15. class Venue { String id; String name; @SerializedName("contact") ContactInfo contactInfo;

    float rating; } class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }
  16. class Venue { String id; String name; @SerializedName("contact") ContactInfo contactInfo;

    float rating; } class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }
  17. class Venue { String id; String name; @SerializedName("contact") ContactInfo contactInfo;

    String photoUrl; } class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }
  18. {"items":[{"reasons":{"count":0,"items":[{"summary":"This spot is popular","type":"general","reasonName":"globalInteractionReason"}]},"venue":{"id ":"4b488bfff964a520184f26e3","name":"Anita La Mamma Del Gelato (הטינא)","contact":{"phone":"+97235170505","formattedPhone":"+972

    3-517-0505"},"location":{"address":"42 Shabazi St","crossStreet":"at Pines St","lat":32.06274494279335,"lng":34.76648985707776,"labeledLatLngs":[{"label":" display","lat":32.06274494279335,"lng":34.76648985707776}],"postalCode":"65150", "cc":"IL","city":"ופי-ביבא לת","state":"ביבא לת","country":" לארשי","formattedAddress":["42 Shabazi St (at Pines St)","","65150 ופי-ביבא לת לארשי"]},"categories":[{"id":"4bf58dd8d48988d1c9941735","name":"Ice Cream Shop","pluralName":"Ice Cream Shops","shortName":"Ice Cream","icon":{"prefix":"https://ss3.4sqi.net/img/categories_v2/food/icecream_", "suffix":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":1941 ,"usersCount":1192,"tipCount":78},"url":"http://www.anitaglida.co.il","price":{" tier":1,"message":"Cheap","currency":"$"},"rating":9.5,"ratingColor":"00B551","r atingSignals":310,"allowMenuUrlEdit":true,"beenHere":{"count":0,"marked":false," lastCheckinExpiredAt":0},"hours":{"status":"Open until 12:30 AM","richStatus":{"entities":[],"text":"Open until 12:30
  19. Convertors • Gson: com.squareup.retrofit2:converter-gson • Jackson: com.squareup.retrofit2:converter-jackson • Moshi: com.squareup.retrofit2:converter-moshi

    • Protobuf: com.squareup.retrofit2:converter-protobuf • Wire: com.squareup.retrofit2:converter-wire • Simple XML: com.squareup.retrofit2:converter-simplexml • Scalars: com.squareup.retrofit2:converter-scalars
  20. static final String BASE_URL = "https://api.foursquare.com/v2/"; static Retrofit.Builder retrofitBuilder =

    new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()); ServiceGenerator.java
  21. static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); static Retrofit retrofit =

    retrofitBuilder .client(httpClient.build()) .build(); ServiceGenerator.java
  22. How to perform a network request? 1. Ask permission 2.

    Setup the Service Generator 3. Create the response data model
  23. How to perform a network request? 1. Ask permission 2.

    Setup the Service Generator 3. Create the response data model 4. Create the service interface
  24. How to perform a network request? 1. Ask permission 2.

    Setup the Service Generator 3. Create the response data model 4. Create the service interface 5. Perform Call!
  25. callback = new Callback<VenuesResponse>() { @Override public void onResponse(Call<VenuesResponse> call,

    Response<VenuesResponse> response) { VenuesResponse data = response.body(); adapter.setItems(data); } };
  26. callback = new Callback<VenuesResponse>() { @Override public void onResponse(Call<VenuesResponse> call,

    Response<VenuesResponse> response) { VenuesResponse data = response.body(); //handle response data } @Override public void onFailure(...) { //handle failure } };
  27. Challenges 1. Heavy 2. Out of memory (Exception) 3. Caching

    4. Resize 5. Image manipulation (round corners…)
  28. VenuesAdapter.java - (Example) public void onBindViewHolder(VenueViewHolder holder, int position){ textView.setText(venues.get(position).getName());

    if (! TextUtils.isEmpty(venue.getImageUrl())) { Picasso.with(imageView.getContext()) .load(venue.getImageUrl()) .into(imageView); } }
  29. Interceptor apiKeyInterceptor = new Interceptor() { @Override public Response intercept(Chain

    chain) throws IOException { Request original = chain.request(); HttpUrl originalHttpUrl = original.url(); } ServiceGenerator.java
  30. Interceptor apiKeyInterceptor = new Interceptor() { @Override public Response intercept(Chain

    chain) throws IOException { Request original = chain.request(); HttpUrl originalHttpUrl = original.url(); HttpUrl url = originalHttpUrl.newBuilder() .addQueryParameter("client_id",CLIENT_ID) .addQueryParameter("client_secret",CLIENT_SECRET) .build(); ServiceGenerator.java