0% found this document useful (0 votes)
11 views37 pages

Lesson 11 - Connect To The Internet

You should probably get to work!

Uploaded by

carlgray8719
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)
11 views37 pages

Lesson 11 - Connect To The Internet

You should probably get to work!

Uploaded by

carlgray8719
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/ 37

Lesson 11:

Connect to the
internet

This work is licensed under the


Android Development with Kotlin Apache 2 license. 1
v1.0
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

This work is licensed under the


Android Development with Kotlin Apache 2 license. 2
Android permissions

This work is licensed under the


Android Development with Kotlin Apache 2 license. 3
Permissions

● Protect the privacy of an Android user


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

This work is licensed under the


Android Development with Kotlin 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.

This work is licensed under the


Android Development with Kotlin Apache 2 license. 5
Permission protection levels

Protection Granted when? Must Examples


Level prompt
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

This work is licensed under the


Android Development with Kotlin 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" />

This work is licensed under the


Android Development with Kotlin 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).

This work is licensed under the


Android Development with Kotlin Apache 2 license. 9
Prompt for dangerous
permission

This work is licensed under the


Android Development with Kotlin 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.

This work is licensed under the


Android Development with Kotlin Apache 2 license. 11
Connect to, and use,
network resources

This work is licensed under the


Android Development with Kotlin 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

This work is licensed under the


Android Development with Kotlin 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

This work is licensed under the


Android Development with Kotlin 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"
This work is licensed under the
Android Development with Kotlin Apache 2 license. 15
Connect to a web
service

This work is licensed under the


Android Development with Kotlin Apache 2 license. 16
HTTP methods

● GET

● POST

● PUT

● DELETE

This work is licensed under the


Android Development with Kotlin Apache 2 license. 17
Example web service API

URL DESCRIPTION METHO


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

This work is licensed under the


Android Development with Kotlin Apache 2 license. 18
Define a Retrofit service
interface SimpleService {
@GET("posts")
suspend fun listPosts(): 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):ThisPost
work is licensed under the
} Android Development with Kotlin 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)

This work is licensed under the


Android Development with Kotlin Apache 2 license. 20
End-to-end diagram

Retrofit
Service HTTP Request
App UI
Server
ViewMod HTTP
Web API
el Response
(JSON
Converter )

Moshi

This work is licensed under the


Android Development with Kotlin 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)

This work is licensed under the


Android Development with Kotlin 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
Post Moshi
response
objects

This work is licensed under the


Android Development with Kotlin 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?)

This work is licensed under the


Android Development with Kotlin 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
"
}

This work is licensed under the


Android Development with Kotlin 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)
}
}
This work is licensed under the
Android Development with Kotlin 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"))
}

This work is licensed under the


Android Development with Kotlin Apache 2 license. 27
Display images

This work is licensed under the


Android Development with Kotlin 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

This work is licensed under the


Android Development with Kotlin Apache 2 license. 29
Add Gradle dependency

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

This work is licensed under the


Android Development with Kotlin Apache 2 license. 30
Load an image

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

This work is licensed under the


Android Development with Kotlin 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

This work is licensed under the


Android Development with Kotlin 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)
}
} This work is licensed under the
Android Development with Kotlin Apache 2 license. 33
Summary

This work is licensed under the


Android Development with Kotlin 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 dangerous (prompt the user at runtime for dangerous p
ermissions)
● Use the Retrofit library to make web service API calls from yo
ur app
● Use the Moshi library to parse JSON response into class objec
This work is licensed under the
ts Android Development with Kotlin Apache 2 license. 35
Learn More

● App permissions best practices


● Retrofit
● Moshi
● Glide

This work is licensed under the


Android Development with Kotlin Apache 2 license. 36
Pathway

Practice what you’ve learned by


completing the pathway:
Lesson 11: Connect to the internet

This work is licensed under the


Android Development with Kotlin Apache 2 license. 37

You might also like