개발 일지

07.19 안드로이드 스튜디오 (Resource, Context, Thread, .. )

HANBEEN 2021. 7. 19. 19:36
반응형

1. resource

resource 파일내 Colors.xml과 String.xml 에서 데이터를 가져오는 실습 중

getColor() 를 바로 사용하게 되면 에러가 발생한다.

 

이유는 resource 없이 하는 것은 API level 23 이상이여야 하기 때문이다.

  • Call requires API level 23 (current min is 16): android.content.Context#getColor

 

때문에 아래와 같이 if문을 이용하여 버전에 따라 다른 명령어가 수행되도록 한다.

val color =if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M) {
    button.setBackgroundColor(getColor(R.color.textview_color))
}else{
    button.setBackgroundColor(resources.getColor(R.color.textview_color))
}

하지만 이렇게 작성을 하여도 resource.getColor 부분에 취소선이 생긴다.

 

 

마우스를 가져다 보면 'getColor(Int): Int' is deprecated. Deprecated in Java 라는 메시지가 뜬다.

Deprecated 단어 그대로 더 이상 사용되지 않는다는 뜻이다.

그렇다면 어떻게 써야할까?

 

찾아보면 ContextCompat 함수에도 getColor() 라는 함수가 있다 이것을 이용해서 고치면 이와같이 된다.

val color =if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M) {
    button.setBackgroundColor(getColor(R.color.textview_color))
}else{
    button.setBackgroundColor(ContextCompat.getColor(this, R.color.textview_color))
}

2. Context

역할

- > ActivityManagerService에 접근 하도록 해주는 역할

( ActivityManagerService : 개발하기 편하도록 미리 구현 해놓은 기능 )

 

안드로이드는 이미 많은 부분들이 만들어져 있다 → 이런것을 사용하기 위해서는 Context가 필요한 경우가 많다

 

종류

  • Activity Context
  • Application Context

 

사용

val context : Context =this
val applicationContext = getApplicationContext()

영상에서는 위와 같이 사용했는데, 현재는 버전이 바뀌면서 사용을 못하는지

getApplicationContext() 부분은 자동완성이 채워지지 않는다..

찾아봐도 이유를 딱히 못찾겠고,, 이해가 안가는 부분도 많다 좀 더 공부를 해봐야겠다!!

 

3. Thread

 

작업 흐름 예시)

앱 실행 ——> launcher Activity ——> , ———→ , ——> 작업 흐름

 

안드로이드의 쓰레드

→ MainThread

 

안드로이드 MainThread의 특징

→ UI Thread → 사용자의 input을 받는 쓰레드

→ 절대 정지시킬 수 없다 !

왜냐하면 정지시키거나 종료시키면 더 이상 사용자의 input을 받을수 없기 때문에

예시 코드

val runnable : Runnable = object:Runnable{
override funrun() {
    }
}

val thread : Thread = Thread(runnable)

button.setOnClickListener{
thread.start()
}

위 코드는 버튼을 눌렀을 때 스레드가 실행된다.

Thread(Runnable{
	
}).start()

위처럼 짧게 줄여쓸 수 있다.

 

* 만약 스레드를 이용하여 배경색을 바꾼다던지, 하는 경우 스레드 내에서 코드를 추가하면 오류가 난다.

그럴 때는 아래와 같이 스레드 내에 runOnUiThread{} 를 넣고 실행해주면 된다.

runOnUiThread{
button.setBackgroundColor(getColor(R.color.textview_color))
}

 

 

반응형