posite 2026. 2. 20. 13:50

Intent

  • 4대 컴포넌트 간의 통신을 위한 작업 수행을 위한 정보를 전달하는 역할
  • 명시적, 암시적 Intent가 있음
  • 명시적 Intent
    • 직접 실행하고자 하는 컴포넌트 class를 지정해주는 방식의 Intent이다.
    • 주로 동일 App에서 다른 Component를 실행시킬때 사용한다.
      val intent = Intent(this, DetailActivity::class.java)
      startActivity(intent)
      
  • 암시적 Intent
    • 클래스명이 아닌 Intent Filter 정보를 활용하는 방식이다.
    • 주로 클래스명을 알 수 없는 외부 앱 혹은 다른 앱의 컴포넌트를 실행할 때 주로 사용한다.
      val intent = Intent(Intent.ACTION_VIEW, Uri.parse("<http://m.naver.com>"))
      startActivity(intent)

Bundle

  • 여러가지 type의 값을 저장하는 Map이다. 따라서 key, value 형태이며 기본 type과 Parcelable타입등을 전달할 수 있다. Android에서는 Activity의 상태 저장 및 복구에 쓰인다.
  • bundle에 데이터를 저장하고 해당 bundle을 intent에 putExtra에 넣어서 전달하면 intent.getExtras()를 통하여 bundle의 데이터를 받을 수 있다.
    val bundle = Bundle() 
    bundle.putInt("age", 123)
    bundle.putString("name", "Loopy")
    intent.putExtras(bundle)
    
    val intent = intent
    val bundle: Bundle = intent.getExtras();
    val age: Int = bundle.getInt("age");
    val name: String = bundle.getString("name);
    ​

Activity 간 데이터 전달

  • registerForActivityResult를 이용해 이전 Activity에 ActivityResultLauncher를 초기화 하고 activityResultLauncher로 새 Activity로 전환했다가 돌아올 때 intent에 데이터를 넣고 setResult를 설정하여 resultCode를 통해 이전 Activity의 registerForActivityResult에서 값을 받을 수 있다.

 

Activity, Fragment 간 데이터 전달

  • Activity → Fragment
    • bundle에 전달 할 데이터를 넣는다
    • supportFragmentManager를 통하여 beginTransaction을 하고 bundle을 setArguments를 통하여 넘겨주고 commit을 통해 수행하게 한다
  • Fragment → Activity
    • Host Activity에서는 supportFragmentManager를 통하여 fragmentResultListener를 연결하고 대기한다
    • Fragment에서는 데이터를 bundle로 만들고 setFragmentResult를 통하여 Host Activity에 전송한다