ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Kotlin] 미세먼지 앱, 레트로핏을 이용한 네트워크 통신
    공부 기록/Kotlin 2022. 4. 3. 17:47
    728x90

    Joyce의 안드로이드 앱 프로그래밍 with 코틀린

    11  project 미세먼지 앱, 레트로핏을 이용한 네트워크 통신


    HTTP 프로토콜이란 서버와 클라이언트가 어떻게 요청하고 어떻게 응답할 것인지 정해놓은 표준 규약

    URL(Uniform Resource Locator)은 URI(Uniform Resource Identifier)의 하위 개념이다.

    식별자(URI) > 리소스의 위치(URL)

    요청 메서드는 자원에 어떤 행동을 하고싶은지 나타냄: GET(리소스를 얻을때), POST(리소스에 어떤 정보를 추가할때), PUT(리소스를 대체할때), DELETE(리소스를 삭제할때)

    레트로핏: 안드로이드와 자바를 위한 타입 안전한 HTTP 클라이언트, a type-safe HTTP client for Android and Java
    -> a type-safe: request body, response body를 원하는 타입으로 안전하게 바꿔줌
    -> HTTP client: API로부터 정보를 가져옴

    안드로이드 프로그래밍에서 서버와 통신할때 거의 필수로 사용됨. 다음 3가지를 구현해야함
    1. HTTP method를 정의한 인터페이스
    2. 레트로핏 클라이언트 객체를 생성하는 레트로핏 클래스
    3. JSON data들을 담을 데이터 클래스

    1. HTTP method를 정의한 인터페이스

    interface ShopService {
    	@GET("product/category") // HTTP 메서드와 상대 URL 정의
        fun getCategoryList(): Call<List<Category>> // 응답 받을 객체를 Call 타입으로 감싼 후 반환 타입으로 명시
        	
        @GET("product/{id}") // HTTP 메서드와 상대 URL 정의
        fun getProductDetail(@Path("id") productId:Int) Call<Product> // 응답 받을 객체를 Call 타입으로 감싼 후 반환 타입으로 명시

    2. 레트로핏 클라이언트 객체를 생성하는 레트로핏 클래스

    class RetrofitClient {
    	companion object {
        	private const val BASE_URL = "http://myvirtualshop.com/"
            var INSTANCE: Retrofit? = null
            
            fun getInstance(): Retrofit {
            	if (INSTANCE == null) {
                	INSTANCE = Retrofit.Builder()
                    .baseUrl(BASE_URL) // API의 베이스URL
                    .addConverterFactory(GsonConverterFactory.create()) // GSon 컨버터를 사용해 JSON 객체를 변환
                    .build()
                }
                return INSTACNE!!
            }
        }
    }

    *GSON: 자바에서 JSON을 파싱하고 생성하는데 사용되는 오픈 소스 라이브러리 (developed by Google)

    3. JSON data들을 담을 데이터 클래스

    [
    	{
        	"categoryId": 1,
            "categoryName": "치마"
        },
        {
        	"categoryId": 2,
            "categoryName": "바지"
        },
        {
        	"categoryId": 3,
            "categoryName": "원피스"
        }
    ]

    레토르핏 응답 메시지는 위와 같이 JSON으로 이루어져 있기 때문에, JSON 객체를 담을 그릇인 데이터 클래스를 생성하고 객체를 적절한 객체 타입으로 변환해주어야 함. 

    data class Category (val categoryId : Int, val categoryName : String)

    // 모듈 수준의 build.gradle 파일 설정
    
    plugins {
        id 'com.android.application'
        id 'kotlin-android'
        id 'kotlin-kapt' // plugins 태그 안 레트로핏 라이브러리 추가함.
    }
    
    android {
        compileSdk 32
    
        defaultConfig {
            applicationId "com.example.airquality"
            minSdk 26
            targetSdk 32
            versionCode 1
            versionName "1.0"
    
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
    
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
        kotlinOptions {
            jvmTarget = '1.8'
        }
        
        viewBinding { // android 태그 안에 뷰 바인딩 설정 코드 추가
            enabled = true
        }
    }
    
    dependencies {
    
        implementation 'androidx.core:core-ktx:1.7.0'
        implementation 'androidx.appcompat:appcompat:1.4.1'
        implementation 'com.google.android.material:material:1.5.0'
        implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
        testImplementation 'junit:junit:4.+'
        androidTestImplementation 'androidx.test.ext:junit:1.1.3'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
        
        // 레트로핏 라이브러리 임포트
        implementation 'com.squareup.retrofit2:retrofit:2.9.0'
        implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    
    }

     

    https://www.iqair.com/ko/dashboard/api 에서 API 키 생성 (난 구글 계정으로 연결함)

     
     
    layout > activity_main.xml 파일 작성 (교재에서 제공한 깃헙 참고)

    laytout > themes에 있는 파일에서 DarkActionBar를 NoActionBar로 수정: 액션바(액티비티에서 기본적으로 제공하는 위젯으로 자주 쓰이는 액션을 추가하는데 사용) 삭제

    <style name="Theme.AirQuality" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    -> 
    <style name="Theme.AirQuality" parent="Theme.MaterialComponents.DayNight.NoActionBar">

    - themes.xml은 기본 모드일 때의 앱 테마파일
    - themes.xml(night)은 어두운(dartk theme) 모드일 때 적용되는 앱 테마파일

    AndroidManifest.xml에서 권한 추가

    <!--     인터넷 허용.-->
        <uses-permission android:name="android.permission.INTERNET"/>
        
    <!--    GPS & 위치 허용.-->
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    댓글

Designed by Tistory.