본문 바로가기
안드로이드 자바

[Java][Android] LifecycleOwner 활용 예시 만들기

by teamnova 2025. 5. 23.
728x90

오늘은 LifecycleOwner를 활용해 여러 옵저버 클래스 구현체들에 의해 LifecycleOwner의 구현체의 상태 정보 변경을 관찰 당하는 예시를 만들어 보겠습니다.

 

 

 

 

 

레이아웃 xml 파일 코드(activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LifecycleOwner 활용 예시"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_marginBottom="32dp" />

    <Button
        android:id="@+id/btnStart"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="시작"
        android:textSize="16sp"
        android:layout_marginBottom="16dp" />

    <Button
        android:id="@+id/btnStop"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="중지"
        android:textSize="16sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="로그를 확인해보세요!"
        android:textSize="14sp"
        android:layout_marginTop="32dp"
        android:textColor="#666666" />

</LinearLayout>



 

액티비티 자바 코드(MainActivity.java)

public class MainActivity extends AppCompatActivity {

    private MyLifecycleOwner myLifecycleOwner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 1. 커스텀 LifecycleOwner 생성
        myLifecycleOwner = new MyLifecycleOwner();

        // 2. Observer 등록 (하나의 주체를 여러 관찰자가 감시)
        myLifecycleOwner.getLifecycle().addObserver(new FirstObserver());
        myLifecycleOwner.getLifecycle().addObserver(new SecondObserver());

        // 3. 버튼 설정
        findViewById(R.id.btnStart).setOnClickListener(v -> {
            Log.d("MainActivity", "=== 시작 버튼 클릭 ===");
            myLifecycleOwner.start();
        });

        findViewById(R.id.btnStop).setOnClickListener(v -> {
            Log.d("MainActivity", "=== 중지 버튼 클릭 ===");
            myLifecycleOwner.stop();
        });
    }
}

 



 

LifecycleOwner 구현체 자바 코드(MyLifecycleOwner.java)

public class MyLifecycleOwner implements LifecycleOwner {

    private LifecycleRegistry lifecycleRegistry;

    public MyLifecycleOwner() {
        lifecycleRegistry = new LifecycleRegistry(this);
        lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
        Log.d("MyLifecycleOwner", "주체 생성됨 - 초기 상태: CREATED");
    }

    @Override
    public Lifecycle getLifecycle() {
        return lifecycleRegistry;
    }

    public void start() {
        // 이미 STARTED 상태라면 아무것도 안함
        if (lifecycleRegistry.getCurrentState() == Lifecycle.State.STARTED) {
            Log.d("MyLifecycleOwner", "이미 STARTED 상태입니다!");
            return;
        }

        // CREATED → STARTED로 변경
        lifecycleRegistry.setCurrentState(Lifecycle.State.STARTED);
        Log.d("MyLifecycleOwner", "상태 변경: STARTED");
    }

    public void stop() {
        // STARTED → CREATED로 되돌리기 (재시작 가능하게)
        lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
        Log.d("MyLifecycleOwner", "상태 변경: CREATED (중지됨)");
    }
}




 

DefaultLifecycleObserver 구현체 1 자바 코드(FirstObserver.java)

public class FirstObserver implements DefaultLifecycleObserver {

    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
        Log.d("FirstObserver", "첫 번째 관찰자: onStart 감지!");
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
        Log.d("FirstObserver", "첫 번째 관찰자: onStop 감지!");
    }
}




 

DefaultLifecycleObserver 구현체 2 자바 코드(SecondObserver.java)

public class SecondObserver implements DefaultLifecycleObserver {

    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
        Log.d("SecondObserver", "두 번째 관찰자: onStart 감지!");
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
        Log.d("SecondObserver", "두 번째 관찰자: onStop 감지!");
    }
}



 

 

실행 결과

 

LifecycleOwner의 상태 변화를 여러 Observer 들이 인식하는 것을 확인할 수 있습니다.