안드로이드 앱 개발기 #11 - 처리할 수 없는 예외/크래쉬 발생시 앱 재시작하기

앱 사용 중에 예외 또는 크래쉬가 발생할 수 있습니다. 만약 이를 앱이 다룰 수 없으면, 앱이 강제 종료될 수 있습니다. 그 대신 앱을 재시작하는 방법이 있어 이를 이번 포스트에서 정리하고자 합니다.


처리할 수 없는 예외/크래쉬 발생시 앱 재시작 방법

(1) Application 클래스를 상속받는 자식 클래스(이하 앱 클래스)를 정의하세요.

class CustomApplication : Application() {
}

(2) Thread.UncaughtExceptionHandler 클래스를 물려받는 자식 클래스(이하 CustomUncaughtExceptionHandler 클래스)를 앱 클래스 안에 정의합니다.

class CustomApplication : Application() {
    class CustomUncaughtExceptionHandler : Thread.UncaughtExceptionHandler {
    }
}

(3) CustomUncaughtExceptionHandler 클래스에서 uncaughtException 메소드를 오버라이드 하세요.

class CustomApplication : Application() {
    class CustomUncaughtExceptionHandler : Thread.UncaughtExceptionHandler {
        override fun uncaughtException(thread: Thread, ex: Throwable) {
        }
    }
}

(4) 앱 재시작하는 메소드를 구현하세요.

예 - 앱 재시작하는 기능을 Context 클래스의 확장 함수로 구현

fun Context.restartApp() {
    packageManager.getLaunchIntentForPackage(packageName)?.let {
        startActivity(Intent.makeRestartActivityTask(it.component))
        Runtime.getRuntime().exit(0)
    }
}

(5) 앱 재시작 메소드를 uncaughtException 메소드에서 호출하세요.

class CustomApplication : Application() {
    class CustomUncaughtExceptionHandler : Thread.UncaughtExceptionHandler {
        override fun uncaughtException(thread: Thread, ex: Throwable) {
            restartApp()
        }
    }
}

CustomApplication 클래스도 Context 클래스를 간접 상속 받으므로 확장함수 restartApp()를 바로 호출할 수 있습니다.

(6) 앱 클래스의 onCreate 함수를 추가하고, 그 곳에서 UncaughtExceptionHandler를 설정하는 코드를 추가하세요.

class CustomApplication : Application() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler())
    }

    // ...
}

(7) AndroidManifest.xml 파일에서 Application 태그의 android:name 속성을 1에서 정의한 앱 클래스로 설정하세요.

<application
    android:name=".CustomApplication"
    ... >

    ( 생략 )

</application>

테스트 방법

고의로 예외를 발생시키고 앱이 재시작되는지 확인할 수 있습니다.

예 - NullPointerException 예외 발생시키기
throw NullPointerException()
예 - 버튼 클릭하면, 강제 NullPointerException 발생
findViewById<Button>(R.id.button).setOnClickListener {
    new NullPointerException()
}

(예정) 샘플 코드

샘플 코드는 며칠 내로 작성하여 GitHub에 공유할 예정입니다.


지난 안드로이드 앱 개발기

Sort:  
 2 years ago 

[광고] STEEM 개발자 커뮤니티에 참여 하시면, 다양한 혜택을 받을 수 있습니다.

Coin Marketplace

STEEM 0.20
TRX 0.12
JST 0.029
BTC 61533.72
ETH 3447.25
USDT 1.00
SBD 2.51