투케이2K

103. (kotlin/코틀린) 코루틴 (coroutine) Main 사용해 UI 변경 작업 수행 실시 본문

Kotlin

103. (kotlin/코틀린) 코루틴 (coroutine) Main 사용해 UI 변경 작업 수행 실시

투케이2K 2022. 10. 9. 12:18

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Kotlin

 

 

 

[빌드 환경 설정 방법]

[1]. build.gradle (Project)


buildscript {

    //====코틀린 코드 위함====
    ext.kotlin_version = "1.3.72"


    repositories {

        // ==== 구글 ====
        google()


        // ==== 뱃지 사용위함 ====
        mavenCentral()


        // ==== jcenter() ====
        jcenter()


        // ==== 추가 ====
        maven { url "https://jitpack.io" }
    }
    dependencies {

        classpath "com.android.tools.build:gradle:4.0.0"


        //====코틀린 코드 위함====
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"


        //====구글광고값 얻음====
        classpath 'com.google.gms:google-services:4.3.3'
    }
}

allprojects {
    repositories {

        // ==== 구글 ====
        google()


        // ==== 뱃지 사용위함 ====
        mavenCentral()


        // ==== jcenter() ====
        jcenter()


        // ==== 추가 ====
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}










[2]. build.gradle (Module)

apply plugin: 'com.android.application'


// ====구글 광고값 얻음====
apply plugin: 'com.google.gms.google-services'


// ====코틀린 코드 위함====
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'


android {
    //compileSdkVersion 31
    //buildToolsVersion "30.0.0"

    compileSdkVersion 30
    buildToolsVersion "30.0.0"

    defaultConfig {
        applicationId "kr.co.two2k.manager" //앱 아이디
        minSdkVersion 21


        //targetSdkVersion 31
        targetSdkVersion 30


        versionCode 2 //앱 버전
        versionName "1.0.2" //앱 버전

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release { //프로가드 난독화 설정 여부
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'


    // ======= 코틀린 사용 위함 ========
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.5"
}










[3]. grade.properties

org.gradle.jvmargs=-Xmx2048m

android.useAndroidX=true

android.enableJetifier=true

# ======= [코틀린 사용 위함] =======
kotlin.code.style=official
 

[소스 코드]

    // TODO [테스트 메소드 정의 실시]
    fun testMain(){
        Log.i("---","---")
        Log.d("//===========//","================================================")
        Log.i("","\n"+"[Test_Kotlin > testMain() 메소드 : 테스트 함수 동작 실시]")
        Log.d("//===========//","================================================")
        Log.i("---","---")


        /**
         * ------------------------------------
         * TODO [요약 설명]
         * ------------------------------------
         * 1. 코루틴은 동시성 프로그래밍으로 비동기적으로 실행되는 코드입니다
         * ------------------------------------
         * 2. 코루틴은 백그라운드 스레드 (네트워크 통신) 에서 코드를 처리할 때 자주 사용됩니다
         * ------------------------------------
         * 3. 코틀린 스코프는 새로운 코루틴을 생성함과 동시에 실행되어야 할 Job 을 그룹핑 합니다
         * ------------------------------------
         * 4. Main : 메인 쓰레드에 대한 Context 이며, UI 갱신이나 View 작업에 사용합니다
         * ------------------------------------
         * 5. 필요 import :
         *
         * import kotlinx.coroutines.CoroutineScope
         * import kotlinx.coroutines.Dispatchers.Main
         * import kotlinx.coroutines.launch
         * ------------------------------------
         * 6. 코루틴 개념 참고 사이트 : https://kkh0977.tistory.com/2761
         * ------------------------------------
         * */


        try{

            // ------------------------------------

            // [초기 변수 및 객체 선언]
            var strData = "핼로"

            // ------------------------------------

            // [로직 처리 실시]
            CoroutineScope(Main).launch {
                Log.i("---","---")
                Log.w("//===========//","================================================")
                Log.i("","\n"+"[Test_Kotlin > testMain() 메소드 : CoroutineScope 코루틴 로직 처리 실시]")
                Log.w("//===========//","================================================")
                Log.i("---","---")

                // [작업 내용 처리]
                strData = strData + " 투케이2K"

                // [ui 작업 실시]
                display_textview.setText(strData)
            }

            // ------------------------------------


        }
        catch(e : Exception){
            Log.i("---","---")
            Log.e("//===========//","================================================")
            Log.i("","\n"+"[Test_Kotlin > testMain() 메소드 : 에러 상황 발생]")
            Log.i("","\n"+"[error : "+ e.message +"]")
            Log.e("//===========//","================================================")
            Log.i("---","---")
        }
    }
 

[결과 출력]

 

 
반응형
Comments