Context란?
- android 시스템에 대한 핸들, 참조
- 리소스, 서비스, 어플리케이션별 정보에 대한 액세스 제공
Context가 여러개인 이유
- 개발자가 필요에 따라 적절한 수준의 액세스 및 범위를 갖도록 하기 위함
- 수명주기와 리소스를 효율적으로 관리하기 위함
Context의 종류

→ no에 할당된 숫자의 의미
- activity를 시작할 수 있으나 새로운 task를 생성해야함. 일반적으로 권장되지않으며, 좋은 방법 아님
- legal하나 실행중이 시스템의 기본 테마로 실행
- receiver가 null인 경우 허용됨.
Context example
- 리소스 접근
val appName = context.getString(R.string.app_name)
val textColor = context.getColor(R.color.text_color)
val icon = context.getDrawable(R.drawable.app_icon)
- 액티비티 시작
val intent = Intent(context, TargetActivity::class.java)
context.startActivity(intent)
- 시스템 서비스 접근
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
- 뷰 생성
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.layout_file, parent, false)
val textView = view.findViewById<TextView>(R.id.text_view)
- 앱의 특정 정보에 접근할 때
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.layout_file, parent, false)
val textView = view.findViewById<TextView>(R.id.text_view)
- 디바이스 display metrics에 접근
val displayMetrics = context.resources.displayMetrics
val screenWidth = displayMetrics.widthPixels
val screenHeight = displayMetrics.heightPixels
- assets로드
val assetManager = context.assets
val inputStream: InputStream = assetManager. open ( "file.txt" )
val text = inputStream.bufferedReader().use { it.readText() }
- 다른 패키지의 리소스에 액세스
val otherPackageContext = context.createPackageContext( "com.example.otherpackage" , Context.CONTEXT_IGNORE_SECURITY)
val otherPackageName = otherPackageContext.packageName
val otherStringRes = otherPackageContext.getString(R.string.some_string)
Uploaded by N2T