OnActivityResult method is deprecated, what is the alternative?

시코·2022년 9월 1일

[Android] startActivityForResult Deprecated된 이유와 해결책
https://kimyunseok.tistory.com/40

A 액티비티와 B 액티비티가 있을 때,

startActivityResult메서드와 onActivityResult메서드를 사용해서 구현할 경우

A -> B 실행, 메모리가 부족해서 A가 소멸됨.
B 액티비티 종료 후 setResult() 메서드로 결과값 넘김
A가 소멸됐다가 다시 생성돼서 B에게 결과값을 요청한 줄 모름.
ActivityResultLauncher객체와 registerForActivityResult()를 사용한 경우

A -> B 실행, 메모리가 부족해서 A가 소멸됨.
B 액티비티 종료 후 setResult() 메서드로 결과값 넘김
A가 다시 생성돼도 registerForActivityResult() 메서드가 다시 콜백을 등록해 줘서 결과값을 받아온다.

∴ ActivityResultLauncher객체와 registerForActivityResult()로 구현하면 된다 !


OnActivityResult method is deprecated, what is the alternative?

https://stackoverflow.com/questions/62671106/onactivityresult-method-is-deprecated-what-is-the-alternative

the old way:

public void openSomeActivityForResult() {
    Intent intent = new Intent(this, SomeActivity.class);
    startActivityForResult(intent, 123);
}

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK && requestCode == 123) {
        doSomeOperations();
    }
}

the new way:

fun openSomeActivityForResult() {
    val intent = Intent(this, SomeActivity::class.java)
    resultLauncher.launch(intent)
}

var resultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
    if (result.resultCode == Activity.RESULT_OK) {
        // There are no request codes
        val data: Intent? = result.data
        doSomeOperations()
    }
}

[안드로이드] startActivityForResult ,onActivityResult 사용법
https://kiwinam.com/posts/23/android-start-activity-for-result/

0개의 댓글