0. 해결법

시간이 없으신 분들은 이곳을 통해 빠른 해결 하시기를 기원합니다.

https://stackoverflow.com/questions/68387270/android-studio-error-installed-build-tools-revision-31-0-0-is-corrupted

 

 

1. 사건의 발단

회사에 예전에 제작하고 유지하고 있는 안드로이드 프로젝트가 있다. 

그런데 최근 일부 기능이 사용되지 않으면서 외부 서비스에 비용이 매달 지출된다는 것을 발견하였다.

그 기능을 일시적으로 비활성화 하기로 하였다.

 

2. 기능 수정은 간단하군

오랜만에 건드리는 프로젝트라 걱정이 앞섰으나, 사실 그렇게 어려운 부분은 없었다.

해당 기능을 사용할 수 없도록 화면을 약간 수정하고 소스코드를 몇가지 주석처리를 했을 뿐이다.

1시간도 걸리지 않은 것 같다.

 

3. 즐거운 마음으로 배포하고 퇴근하자

오후 4시에 시작한 수정 작업은 5시쯤 완료 되었다. 

테스트폰에 돌려보니 잘돌아간다.

인텔리제이가 targetSdkVersion 30에 노란불을 띄웠길래 버전업이 되었구나 하며 31버전으로 바꾸었다.

이제 구글 플레이 콘솔에 업로드만 하면 배포 준비는 끝... 이라고 생각하였으나

업로드하자 콘솔에서 배포불가능한 코드라는 식의 메시지가 뜬다.

해당 사진자료를 스크린샷하지 못하였지만 대략 아래와 비슷한 내용이었다.

아 안돼... 

퇴근시간 안에 배포해야 한다. 그래야 칼퇴가 가능하다.

 

4. 와 야근!

빨리 빨리...

원인을 찾자. 내가 무얼했지?

아 그래, sdk 버전을 올렸지. 업데이트하는 김에 타겟을 높이면 좋잖아?

그게 문제였나.

좋다. 그럼 버전을 내려서 다시 업로드해야지.

그래들에서 sdk버전을 내린 뒤 apk 빌드를 시작한다... 엥?

The minCompileSdk (31) specified in a dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) is greater than this module's compileSdkVersion (android-30).

위와 같은 에러가 발생했다. 

디펜던시 문제라고 한다.

'androidx.appcompat:appcompat:1.4.1' 때문이란다.

내 프로젝트엔 'androidx.appcompat:appcompat:1.4.1'이 없는데?

점점 미궁으로 빠져든다.

다시 compileSdkVersion과 targetSdkVersion을 31버전으로 올려서 빌드해본다... 엥?

Installed Build Tools revision 31.0.0 is corrupted. Remove and install again using the SDK Manager.

아 현기증이 올라온다. 시간은 벌써 9시.

칼퇴는 무슨... 집으로 가자.

 

5. 간과한 점은 무엇인가

다음 날 아침, 멘탈을 다시 부여잡고 냉정하게 상황 판단을 시작한다.

내가 간과한 것이 무엇인가?
    - 프로젝트를 오랜만에 수정하였다
    - 작업 컴퓨터를 바꾸었다
    - 안드로이드 스튜디오 버전이 바뀌었다
    - 모바일 플랫폼은 수시로 업데이트되고 바뀐다

정리가 되기 시작한다.

프로젝트를 작년에 완료한 후 작업 컴퓨터를 바꾸었고, 해당 프로젝트는 Github에 저장되어 있으니, 로컬에는 받아놓지도 않았다.

젯브레인 툴박스로 안드로이드 스튜디오를 설치하니, Arctic Fox가 설치된다. 일부러 설치 안하던 버전이었는데 이제는 강제로 설치된다.

 컴파일 및 타겟 sdk버전을 주의없이 수정하였다. (이건 억울하다. Arctic Fox 때문이다...)

 

6. 해결

'정답은 구글이 알고 있다'는 옛 선현들의 말씀에 따라 다시 해결책을 찾아 나선다.

인텔리제이 캐시를 비워보기도 하고
그래들 디펜던시 캐시도 삭제해보고
Arctic Fox 최신버전을 설치해보고
sdk버전도 30~32를 넘나들며 바꿔보았다.

그래도 안돼?

이건 정상적인 방법으로는 해결할 수 없다는 직감이 온다.

스택오버플로우를 계속 파본다.

그러던 중 발견한 해결법.

https://stackoverflow.com/questions/68387270/android-studio-error-installed-build-tools-revision-31-0-0-is-corrupted

 

Android Studio error "Installed Build Tools revision 31.0.0 is corrupted"

I'm on Android Studio 4.2.2. I created a new project and haven't added anything to the starter code and whenever I click build or run, I get this error: Installed Build Tools revision 31.0.0 is

stackoverflow.com

 

위 질문에 달린 답변.

요약하자면, 안드로이드 스튜디오 자체의 이슈라는 것.

파일을 직접찾아 변경하라고 한다.

댓글들도 난리가 나 있었다.

 

바로 이게 정답일 확률이 높다고 생각하고 바로 적용해본다.

빌드... 성공!

그래들에 적용한 sdk버전은 위와 같다.

 

결과적으로 인텔리제이 안드로이드 스튜디오 버전 자체의 문제였다고 보인다.

인텔리제이를 원망하지는 않는다.

다른 제품들은 대부분 만족하면서 사용하고 있으며, 안스는 무료툴이기도 하기 때문에.

다만 저런 세계적인 회사도 쉽지 않은 것이 디버깅과 테스트라는 점이 내 마음을 조금 무겁게 했을 뿐이다.

 

이상

 

fcm push가 올 경우 화면을 실시간으로 변경해야될 경우가 있음.

liveData를 이용하여 구현 할 수 있다.

 

안드로이드 App 파일에서

 

스태틱으로 라이브데이터를 선언해준다

 

App파일의 onCreate에서 초기화 라이브데이터를 초기화 해준다.

 

fcm 메시지 리시버 내부에서

 

뱃지와 관련된 글로벌 카운트를 올려준 뒤
라이브 데이터를 변경한다(변경이 되어야 액티비티/프래그먼트에서 변경 감지를 할 수 있다)
메인쓰레드가 아닌곳에서 변경을 하려면 postValue를 이용한다

 

뷰를 변경할 액티비티나 프래그먼트로 이동한다
액티비티는 this / 프래그먼트는 viewLifecycleOwner를 라이프사이클 오너로 입력한다

 

이제 푸시 알림이 오면 해당 뱃지의 뷰가 변경이 된다.

 

rx Customer를 이용하여서도 비슷하게 구성 할 수 있다.

 

 

 

연구 목적 : 내부 값 난독화 목적

결과 : 값 난독화에는 의미가 적음 // 자체제작 라이브러리 난독화에는 의미가 있음(C++)

- 값은 되도록 서버에 저장

- proguard를 이용

 

여러 사이트를 참고하여 ndk를 이용한 키 난독화 작업을 테스트 해보았음.

다만 구글링으로 구성하려고 하면 쉽지 않다.

오히려 안드로이드스튜디오의 템플레이트로 연습해보는 것이 좋다.

 

Native C++ 프로젝트를 열어보면

아래와 같이 cpp 폴더와 함께 CMake 관련 파일들이 생성된다.

 

native-lib.cpp 파일을 보면

Hello from C++을 리턴하게 되어있다.

 

MainActivity를 열어보면 스태틱으로 네이티브 라이브러리와 함수를 로드하게 되어있고

빌드후 실행해보면 Hello from C++가 나오는 간단한 프로젝트이다.

 

 

난독화로서 의미가 적은 이유

apk파일로 만들고 툴을 이용하여 디컴파일 해보면

아래와 같은 파일들이 만들어진다. (jniLibs)

 

위의 예제와 같은 이름의 프로젝트를 만들고 

Project구조로 변경한뒤 

main 폴더 안에 jniLibs라는 폴더를 만들고 그안에 위 파일들을 넣어준다.

그러고난 뒤 메인액티비티의 xml과 클래스파일을 예제 프로젝트와 똑같이 만든 후

빌드 실행 해보면 함수가 호출되어 같은 값이 출력된다.

(큰 의미 없다는 것)

 

jniLibs에 들어간 것은 so 파일인데

c파일은 so파일로 만들어져도 아래 사이트에 업로드해보면 대충 값을 확인할 수 있다.

onlinedisassembler.com/odaweb/

 

ODA - The Online Disassembler

You need to upgrade your browser or enable javascript to view this site!

onlinedisassembler.com

 

cpp파일은 so파일로 만들어지면 위 사이트로 열어봐도 보기 어렵다.

즉 내부코드를 확인하기는 쉽지 않다는 뜻이다. (코드 보안에는 좋을듯 함)

하지만 apk를 디컴파일하여 해당라이브러리를 사용하는 코드를 확인하여 작동해보면 값은 가져올 수 있다.

 

추가로 proguard 로 앱자체를 난독화하여 찾기 어렵게 만들어도 디컴파일 툴을 이용하면

아래와 같이 큰 힘을 들이지 않아도 찾아 낼 수 있다.

 

아이디어라면 라이브러리 이름과 매서드를 한글자(a 등)로 하여 분석하기 매우 힘들게는 가능 할 것 같다.

 

 

사용한 툴

안드로이드 스튜디오
sublimetext
apktool
dex2jar
jd-gui

 

ndk cmark 사용법 관련 주소

(다시 말씀드리지만 ndk cmark 연습은 샘플프로젝트를 이용하는 것이 가장 빠름)

developer.android.com/studio/projects/install-ndk?hl=ko

 

NDK 및 CMake 설치 및 구성  |  Android 개발자  |  Android Developers

앱의 네이티브 코드를 컴파일하고 디버그하려면 다음 구성요소가 필요합니다. Android 네이티브 개발 키트(NDK): Android에서 C 및 C++ 코드를 사용할 수 있도록 해주는 도구 모음입니다. CMake: Gradle과

developer.android.com

 

developer.android.com/studio/projects/add-native-code?hl=ko

 

C 및 C++ 코드를 프로젝트에 추가  |  Android 개발자  |  Android Developers

C 및 C++ 코드를 Android 프로젝트에 추가하는 방법을 알아보세요.

developer.android.com

 

developer.android.com/ndk/samples/sample_hellojni

 

샘플: hello-jni  |  Android NDK  |  Android Developers

이 샘플에서는 NDK로 빌드한 작은 C/C++ 애플리케이션인 hello-jni를 살펴봅니다. 이 샘플은 android-mk 분기 내 ndk-samples 저장소의 hello-jni 디렉터리에 있습니다. Android.mk 다음 두 줄은 네이티브 소스 파

developer.android.com

 

medium.com/programming-lite/securing-api-keys-in-android-app-using-ndk-native-development-kit-7aaa6c0176be

 

Securing API Keys in Android App using NDK (Native Development Kit)

Securing API keys in Android application has become a challenging by traditional methods (storing them in strings.xml or in Gradle etc.)…

medium.com

 

thepassion.tistory.com/332

 

[Android] ndk-build를 이용한 Native Code 빌드 및 사용방법

ndk-build를 이용한 Native Code 빌드 및 사용방법 다음과 같은 이유로 Android App에서 Native Code(C/C++등)로 코드를 작성하여 사용해야 할 경우가 존재합니다. 처리 속도 및 성능향상 C/C++로 만들어진 코드.

thepassion.tistory.com

 

medium.com/@abhi007tyagi/storing-api-keys-using-android-ndk-6abb0adcadad

 

Securing API Keys using Android NDK

Today there are thousands of third-party libraries and APIs available to developers for creating cool, amazing mobile apps. These APIs are…

medium.com

 

blog.mindorks.com/securing-api-keys-using-android-ndk

 

Securing API Keys using Android NDK (Native Development Kit)

In this blog, we will learn how to secure our API Keys that are used in Android applications using the Android NDK (Native Development Kit). We have created a detailed blog of securing the API Keys.

blog.mindorks.com

 

yoo-hyeok.tistory.com/72

 

[Android] NDK를 이용한 C/C++ 연동 개발

NDK란 무엇인가? Android NDK는 C와 C++ 같은 네이티브 코드 언어를 사용하여 앱의 일부를 구현하는 도구모음입니다. 어떤 유형의 앱에서는 네이티브 코드 언어로 작성된 코드 라이브러리를 재사용하

yoo-hyeok.tistory.com

 

 

 

1. app 단위 gradle에서 minifyEnabled true 세팅

 

2. proguard-rules.pro 파일을 수정

외부 라이브러리 등의 난독화 설정을 해줘야한다.
라이브러리 docs에 proguard 관련 내용이 있으니 참고하면 된다.

또한 retrofit2와 rxjava 등을 사용한다면 통신에 필요한 모델들도 난독화에서 제외해야한다.

인텔리제이에서 아래와 같이 빨간줄이 뜨지만 정상작동한다.
(오히려 빨간줄을 없애려고 * 하나 줄이는 등의 작업을 하면 빌드 후 문제가 발생하는 듯 하다.)

 

3. 빌드 후 테스트하여 에러 등을 확인한다.

 

4. apktool / dex2jar / jd-gui 등의 디컴파일 툴 등을 이용하여 디컴파일해서 난독화가 잘되었는지 확인한다.

 

5. 기타

아래는 proguard-rules.pro파일을 수정할 때 필요한 코드 등을 정리한 것이다.
아래 내용에 없는 라이브러리는 해당 라이브러리 사이트나 docs에서 proguard 설정 코드를 찾아본다.
그래도 안된다면 구글링을 하여 선배님들이 만들어 놓은 코드를 사용하자.

더보기
# If you keep the line number information, uncomment this to
# hide the original source file name.
# 소스 파일 변수 명 바꾸는 옵션
-renamesourcefileattribute SourceFile

# Uncomment this to preserve the line number information for
# debugging stack traces.
# 소스 파일의 라인을 섞지 않는 옵션 (이거 안해주면 나중에 stacktrace보고 어느 line에서 오류가 난 것인지 확인 불가)
-keepattributes SourceFile,LineNumberTable

# Retrofit2
# Retrofit does reflection on generic parameters. InnerClasses is required to use Signature and
# EnclosingMethod is required to use InnerClasses.
-keepattributes Signature, InnerClasses, EnclosingMethod

# Retrofit does reflection on method and parameter annotations.
-keepattributes RuntimeVisibleAnnotations, RuntimeVisibleParameterAnnotations

# Retain service method parameters when optimizing.
-keepclassmembers,allowshrinking,allowobfuscation interface * {
    @retrofit2.http.* <methods>;
}

# Ignore annotation used for build tooling.
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

# Ignore JSR 305 annotations for embedding nullability information.
-dontwarn javax.annotation.**

# Guarded by a NoClassDefFoundError try/catch and only used when on the classpath.
-dontwarn kotlin.Unit

# Top-level functions that can only be used by Kotlin.
-dontwarn retrofit2.KotlinExtensions
-dontwarn retrofit2.KotlinExtensions$*

# With R8 full mode, it sees no subtypes of Retrofit interfaces since they are created with a Proxy
# and replaces all potential values with null. Explicitly keeping the interfaces prevents this.
-if interface * { @retrofit2.http.* <methods>; }
-keep,allowobfuscation interface <1>
# Retrofit2

# 카카오 지도 앱 (빨간줄 뜨지만 정상)
-keep class net.daum.** {*;}
-keep class android.opengl.** {*;}
-keep class com.kakao.util.maps.helper.** {*;}
-keepattributes Signature
-keepclassmembers class * {
    public static <fields>;
    public *;
}
# 카카오 지도 앱 (빨간줄 뜨지만 정상)

# 카카오 로그인
-keep class com.kakao.sdk.**.model.* { <fields>; }
-keep class * extends com.google.gson.TypeAdapter
# 카카오 로그인

# 네이버 로그인
-keep public class com.nhn.android.naverlogin.** {
       public protected *;
}
# 네이버 로그인

# firebase 구글 로그인
-keepattributes Signature
-keepattributes *Annotation*
# firebase 구글 로그인

# sqlite
-keep class org.sqlite.** { *; }
-keep class org.sqlite.database.** { *; }
-keep class net.sqlcipher.** { *; }
-dontwarn net.sqlcipher.**
# sqlite

# roomdb (androidx)
-keep class * extends androidx.room.RoomDatabase
-dontwarn androidx.room.paging.**
# roomdb

#glide
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.module.AppGlideModule
-keep public enum com.bumptech.glide.load.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}
#glide


# okhttp3
-dontwarn okhttp3.**
-dontwarn okio.**
-dontnote okhttp3.**
# okhttp3


# support v4 ,v7
-dontwarn android.support.**
# support v4 ,v7


## gson (gson 컨버터와 다른 것)
###---------------Begin: proguard configuration for Gson  ----------
## Gson uses generic type information stored in a class file when working with fields. Proguard
## removes such information by default, so configure it to keep all of it.
#-keepattributes Signature
#
## For using GSON @Expose annotation
#-keepattributes *Annotation*
#
## Gson specific classes
#-dontwarn sun.misc.**
##-keep class com.google.gson.stream.** { *; }
#
## Application classes that will be serialized/deserialized over Gson
#-keep class com.google.gson.examples.android.model.** { *; }
#
## Prevent proguard from stripping interface information from TypeAdapterFactory,
## JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
#-keep class * implements com.google.gson.TypeAdapterFactory
#-keep class * implements com.google.gson.JsonSerializer
#-keep class * implements com.google.gson.JsonDeserializer
#
###---------------End: proguard configuration for Gson  ----------
## gson (gson 컨버터와 다른 것)

 

 

참고 사이트들

medium.com/ics-lab/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-%EC%95%B1-%EB%82%9C%EB%8F%85%ED%99%94-proguard-dexguard-%EB%A5%BC-%ED%95%B4%EB%B3%B4%EC%9E%90-1-%ED%94%84%EB%A1%9C%EA%B0%80%EB%93%9C-%ED%8E%B8-799999a43c4d

 

안드로이드 앱 난독화(Proguard & Dexguard)를 해보자! 1. 프로가드 편

Google play store에서 앱을 받아 apk 파일을 추출하는 어플을 사용하면 쉽게 apk을 얻을 수 있다.

medium.com

 

black-jin0427.tistory.com/89

 

[Android, Proguard] 안드로이드 프로가드 설정하기

안녕하세요. 블랙진입니다. 이번에는 코드 난독화 및 APK 최적화를 위한 프로가드에 대해 알아보겠습니다. Android Proguard 가 필요한 이유 1. 코드 난독화를 통해 디컴파일시 본인의 코드가 노출되

black-jin0427.tistory.com

 

namget.tistory.com/entry/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-proguard-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0-retrofitgsonzxingglideokhttp3supportrxjava

 

안드로이드 proguard 적용하기 (retrofit,gson,zxing,glide,okhttp3,support,rxjava)

안녕하세요 남갯입니다 오늘은 안드로이드 proguard 적용 (난독화)하는 방법에대해 알려드리겠습니다. 일단 release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'progu..

namget.tistory.com

 

bigmatch.i-um.net/2016/08/05/retrofit2-rxjava-proguard-settings/

 

Retrofit2 + RxJava proguard 설정하기

안녕하세요, 이음소시어스에서 안드로이드 앱 개발을 맡고 있는 김범준(준) 입니다. 최근 안드로이드 HTTP Client 라이브러

bigmatch.i-um.net

 

developer88.tistory.com/118

 

ProGuard Rules 정리 (Retrofit & OkHttp, JSoup, GSon, RxJava, Glide etc)

다양한 라이브러리를 사용하는 만큼, 다양한 ProGuard를 사용해야 합니다. 그런데, 어떤 라이브러리는 이 부분에 대해서 명확히 정리하고 있고, 또 어떤 라이브러리는 그렇지 못합니다. 오늘은 제

developer88.tistory.com

 

gogorchg.tistory.com/entry/Android-Project%EC%97%90-Proguard-%EC%A0%81%EC%9A%A9-%ED%95%98%EA%B8%B0

 

[Android] Project에 Proguard 적용 하기

ProGuard를 적용하는 방법은 쉽습니다. build.gradle 파일 에 아래 소스만 넣어주면 땡입니다. buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'pro..

gogorchg.tistory.com

 

 

 

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

위 코드는 매니페스트에 하나만 있어야한다

그렇지 않으면 앱이 2개가 깔려버린다

 

해당 프로젝트

https://github.com/jaybon1/androidwork/tree/master/serviceCounterApp

 

jaybon1/androidwork

Contribute to jaybon1/androidwork development by creating an account on GitHub.

github.com

 

안드로이드 4대 컴포넌트 알아둬야함 
액티비티
서비스
컨텐트프로바이더 (연락처앱에 접근 하는 등)
브로드캐스팅

 

AIDL을 만들 수 있으면 컨텐트 프로바이더를 만들 수 있다
다른 앱이 원할 때 내 앱의 함수를 실행

책 552페이지

 

--

 

 

뷰 만들기

--

 

 

서비스 생성

--

 

 

1초에 한번씩 count가 증가하도록 세팅

--

 

 

메인액티비티에서 서비스를 실행해본다

--

 

 

로그에 잘 보인다

--

 

 

서비스에서 조건을 건다

--

 

 

멈췄다 실행해보면 아래와같이 나온다

--

 

 

한계 :
메인 액티비티에서 해당 값을 가져올 수 없다(ui갱신을 할수 없다)
값이 보존이 되지 않는다 (일시정지가 안됨)

---------

 

AIDL 생성

 

 

 

ctrl + f9 : 빌드 하면 아래와 같이 BuildConfig와 인터페이스가 만들어진다

--

 

 

서비스에서 아래와 같이 입력( retrun 0을 count로 바꾸자)

--

 

 

서비스에서 onBind를 호출하면 바인더를 리턴 받을 수 있다

--

 

 

멈출때 디스트로이 쓰지 않고 온 언바인드 사용

--

 

 

--

 

 

--

 

바인더는 서비스변수를 참조할 수 있다

--

 

서비스

1. BindService -> onCreate /onBind 실행
2. 스레드 실행

--

 

 

for문 대신 while 문을 사용

--

 

 

서비스를 startService 대신 bindService를 이용해서 실행한다

 

또한 화면에 서비스에서 받아온 값을 입력하기위해 쓰레드를 만들고

핸들러를 이용하여 ui에 접근하여 글자를 변경한다

--

 

 

재실행시 메인에서 count값을 받아온다

--

 

 

테스트

 

 

 

 

 

 

 

 

 

+ Recent posts