Lesson 11 Connect To The Internet

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

Lesson 11:

Connect to the
internet

Android Development with Kotlin v1.0 This work is licensed under the Apache 2 license. 1
About this lesson
Lesson 11: Connect to the internet
● Android permissions
● Connect to, and use, network resources
● Connect to a web service
● Display images
● Summary

Android Development with Kotlin This work is licensed under the Apache 2 license. 2
Android permissions

Android Development with Kotlin This work is licensed under the Apache 2 license. 3
Permissions

● Protect the privacy of an Android user


● Declared with the <uses-permission> tag in the
AndroidManifest.xml

Android Development with Kotlin This work is licensed under the Apache 2 license. 4
Permissions granted to your app

● Permissions can be granted during installation or runtime,


depending on protection level.
● Each permission has a protection level: normal, signature, or
dangerous.
● For permissions granted during runtime, prompt users to
explicitly grant or deny access to your app.

Android Development with Kotlin This work is licensed under the Apache 2 license. 5
Permission protection levels

Protection Level Granted when? Must prompt Examples


before use?
Normal Install time No ACCESS_WIFI_STATE,
BLUETOOTH, VIBRATE,
INTERNET

Signature Install time No N/A

Dangerous Runtime Yes GET_ACCOUNTS, CAMERA,


CALL_PHONE

Android Development with Kotlin This work is licensed under the Apache 2 license. 6
Add permissions to the manifest
In AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sampleapp">
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<application>
<activity
android:name=".MainActivity" ... >
...
</activity>
</application>
</manifest>

Android Development with Kotlin This work is licensed under the Apache 2 license. 7
Internet access permissions

In AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Android Development with Kotlin This work is licensed under the Apache 2 license. 8
Request dangerous permissions

● Prompt the user to grant the permission when they try to


access functionality that requires a dangerous permission.
● Explain to the user why the permission is needed.
● Fall back gracefully if the user denies the permission (app
should still function).

Android Development with Kotlin This work is licensed under the Apache 2 license. 9
Prompt for dangerous permission

Android Development with Kotlin This work is licensed under the Apache 2 license. 10
App permissions best practices

● Only use the permissions necessary for your app to work.


● Pay attention to permissions required by libraries.
● Be transparent.
● Make system accesses explicit.

Android Development with Kotlin This work is licensed under the Apache 2 license. 11
Connect to, and use,
network resources

Android Development with Kotlin This work is licensed under the Apache 2 license. 12
Retrofit

● Networking library that turns your HTTP API into a Kotlin and
Java interface
● Enables processing of requests and responses into objects for
use by your apps
○ Provides base support for parsing common response types,
such as XML and JSON
○ Can be extended to support other response types

Android Development with Kotlin This work is licensed under the Apache 2 license. 13
Why use Retrofit?

● Builds on industry standard libraries, like OkHttp, that provide:


○ HTTP/2 support
○ Connection pooling
○ Response caching and enhanced security
● Frees the developer from the scaffolding setup needed to run a
request

Android Development with Kotlin This work is licensed under the Apache 2 license. 14
Add Gradle dependencies

implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-moshi:2.9.0"

implementation "com.squareup.moshi:moshi:$moshi_version"
implementation "com.squareup.moshi:moshi-kotlin:$moshi_version"
kapt "com.squareup.moshi:moshi-kotlin-codegen:$moshi_version"

Android Development with Kotlin This work is licensed under the Apache 2 license. 15
Connect to a web service

Android Development with Kotlin This work is licensed under the Apache 2 license. 16
HTTP methods

● GET

● POST

● PUT

● DELETE

Android Development with Kotlin This work is licensed under the Apache 2 license. 17
Example web service API

URL DESCRIPTION METHOD

example.com/posts Get a list of all posts GET


example.com/posts/username Get a list of posts by GET
user
example.com/posts/search?filter=queryterm Search posts using a GET
filter
example.com/posts/new Create a new post POST

Android Development with Kotlin This work is licensed under the Apache 2 license. 18
Define a Retrofit service
interface SimpleService {
@GET("posts")
suspend fun listAll(): List<Post>

@GET("posts/{userId}")
suspend fun listByUser(@Path("userId") userId:String): List<Post>

@GET("posts/search") // becomes post/search?filter=query


suspend fun search(@Query("filter") search: String): List<Post>

@POST("posts/new")
suspend fun create(@Body post : Post): Post
}

Android Development with Kotlin This work is licensed under the Apache 2 license. 19
Create a Retrofit object for network access

val retrofit = Retrofit.Builder()


.baseUrl("https://example.com")
.addConverterFactory(...)
.build()

val service = retrofit.create(SimpleService::class.java)

Android Development with Kotlin This work is licensed under the Apache 2 license. 20
End-to-end diagram

Retrofit Service
HTTP Request

App UI Server
ViewModel Converter HTTP Response Web API
(JSON)

Moshi

Android Development with Kotlin This work is licensed under the Apache 2 license. 21
Converter.Factory

Helps convert from a response type into class objects


● JSON (Gson or Moshi)
● XML (Jackson, SimpleXML, JAXB)
● Protocol buffers
● Scalars (primitives, boxed, and Strings)

Android Development with Kotlin This work is licensed under the Apache 2 license. 22
Moshi

● JSON library for parsing JSON into objects and back


● Add Moshi library dependencies to your app’s Gradle file.
● Configure your Moshi builder to use with Retrofit.

List of JSON
Moshi
Post objects response

Android Development with Kotlin This work is licensed under the Apache 2 license. 23
Moshi JSON encoding

@JsonClass(generateAdapter = true)
data class Post (
val title: String,
val description: String,
val url: String,
val updated: String,
val thumbnail: String,
val closedCaptions: String?)

Android Development with Kotlin This work is licensed under the Apache 2 license. 24
JSON code

{
"title":"Android Jetpack: EmojiCompat",
"description":"Android Jetpack: EmojiCompat",
"url":"https://www.youtube.com/watch?v=sYGKUtM2ga8",
"updated":"2018-06-07T17:09:43+00:00",
"thumbnail":"https://i4.ytimg.com/vi/sYGKUtM2ga8/hqdefault.jpg"
}

Android Development with Kotlin This work is licensed under the Apache 2 license. 25
Set up Retrofit and Moshi
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
object API {
val retrofitService : SimpleService by lazy {
retrofit.create(SimpleService::class.java)
}
}

Android Development with Kotlin This work is licensed under the Apache 2 license. 26
Use Retrofit with coroutines

Launch a new coroutine in the view model:

viewModelScope.launch {
Log.d("posts", API.retrofitService.searchPosts("query"))
}

Android Development with Kotlin This work is licensed under the Apache 2 license. 27
Display images

Android Development with Kotlin This work is licensed under the Apache 2 license. 28
Glide

● Third-party image-loading library in Android


● Focused on performance for smoother scrolling
● Supports images, video stills, and animated GIFs

Android Development with Kotlin This work is licensed under the Apache 2 license. 29
Add Gradle dependency

implementation "com.github.bumptech.glide:glide:$glide_version"

Android Development with Kotlin This work is licensed under the Apache 2 license. 30
Load an image

Glide.with(fragment)
.load(url)
.into(imageView);

Android Development with Kotlin This work is licensed under the Apache 2 license. 31
Customize a request with RequestOptions

● Apply a crop to an image


● Apply transitions
● Set options for placeholder image or error image
● Set caching policies

Android Development with Kotlin This work is licensed under the Apache 2 license. 32
RequestOptions example
@BindingAdapter("imageUrl")
fun bindImage(imgView: ImageView, imgUrl: String?) {
imgUrl?.let {
val imgUri = imgUrl.toUri().buildUpon().scheme("https").build()

Glide.with(imgView)
.load(imgUri)
.apply(RequestOptions()
.placeholder(R.drawable.loading_animation)
.error(R.drawable.ic_broken_image))
.into(imgView)
}
}

Android Development with Kotlin This work is licensed under the Apache 2 license. 33
Summary

Android Development with Kotlin This work is licensed under the Apache 2 license. 34
Summary
In Lesson 11, you learned how to:
● Declare permissions your app needs in AndroidManifest.xml
● Use t
he three protection levels for permissions: normal, signature, and dan
gerous (prompt the user at runtime for dangerous permissions)
● Use the Retrofit library to make web service API calls from your app
● Use the Moshi library to parse JSON response into class objects
● Load and display images from the internet using the Glide library

Android Development with Kotlin This work is licensed under the Apache 2 license. 35
Learn More

● App permissions best practices


● Retrofit
● Moshi
● Glide

Android Development with Kotlin This work is licensed under the Apache 2 license. 36
Pathway

Practice what you’ve learned by


completing the pathway:
Lesson 11: Connect to the internet

Android Development with Kotlin This work is licensed under the Apache 2 license. 37

You might also like