코딩하는 일용직 노동자

registerForActivityResult 를 알아보자 본문

안드로이드

registerForActivityResult 를 알아보자

bacass 2020. 11. 28. 16:16

startActivityForResult(), onActivityResult() 가 deprecated 되었습니다.
당장은 쓸 수 있지만 나중을 위해 새로운 방법을 알아보도록 하겠습니다.

최신 버전으로 dependencies 를 사용하면 확인할 수 있다.
의사양반 이게 무슨소리요~ startActivityForResult 가 고자라니 ㅠ.ㅠ


일단 간단한 테스트 액티비티를 만들겠습니다.
MainActivity 와 이동할 SubActivity를 만들겠습니다.

- MainActivity.java
package com.lee.starttest;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private final String TAG = "Test";

    private final int REQUEST_CODE = 1102;

    private Button mButton;

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

        mButton = (Button) findViewById(R.id.button);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                moveSubActivity();
            }
        });
    }

    private void moveSubActivity() {
        Intent intent = new Intent(MainActivity.this, SubActivity.class);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE) {
            Log.d(TAG, "MainActivity로 돌아왔다. " + resultCode);
        }
    }
}
- activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Main Activity"
        android:textColor="@color/black"
        android:textSize="25dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="170dp"
        android:layout_height="50dp"
        android:text="서브화면으로 이동"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>
- SubActivity.java
package com.lee.starttest;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class SubActivity extends AppCompatActivity {

    private Button mButton;

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

        mButton = (Button) findViewById(R.id.button);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backMainActivity();
            }
        });
    }

    private void backMainActivity() {
        setResult(Activity.RESULT_OK);
        finish();
    }
}
- activity_sub.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SubActivity">


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sub Activity"
        android:textSize="25dp"
        android:textColor="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="130dp"
        android:layout_height="50dp"
        android:text="돌아가기"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

SubActivity에서 MainActivity로 정상적으로 돌아왔다.

 

AndroidX의 androidx.activity:activity:1.2.0-alpha02 부터는 새로운 방식의 API를 제공합니다.
만들어진 테스트용 프로젝트에 새로운 방식을 테스트해보겠습니다.

private void moveSubActivity() {
    Intent intent = new Intent(MainActivity.this, SubActivity.class);
    startActivityResult.launch(intent);
}

ActivityResultLauncher<Intent> startActivityResult = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == Activity.RESULT_OK) {
                Log.d(TAG, "MainActivity로 돌아왔다. ");
            }
        }
    });

이런 방식도 정상적으로 돌아온다.

java 소스를 보니 전보다 불편해진것 같은 기분이....

코틀린 ( Kotlin ) 은 아래처럼 사용하시면 됩니다.

fun openActivityForResult() {
    startForResult.launch(Intent(this, SubActivity::class.java))
}

val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { 
result: ActivityResult ->
    if (result.resultCode == Activity.RESULT_OK) {
        val intent = result.data
        // Handle the Intent
        //do stuff here
    }
}