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

[JAVA][Android] registerForActivityResult() 사용하기

by teamnova 2021. 8. 4.
728x90

기존에 안드로이드에서 사용하던

 

startActivityForResult()

onActivityResult()

기억 나시나요?

 

근데 지금 그 메소드가 Deprecated가 되었습니다.

 

그러면 어떤 방법을 이용해야 할까요?

 

http:// developer.android.com/training/basics/intents/result

 

https://stickode.com/mainlogin.html

 

STICKODE

 

stickode.com

먼저 최신 버전으로 dependencies를 체크해 줍니다.

 

implementation 'androidx.appcompat:appcompat:1.3.0-alpha02'

 

기본적인 구현 방법은 기존의 startActivityForResult(), onAcitivityResult() 처럼 크게 2가지로 나뉩니다.

 

 

1. Activity Result에 콜백 등록 (Registering a callback for an Activity Result)

 

2. 결과를 위한 활동 실행 (Launching an activity for result)

 

 

기존의 코드를 먼저 실행해 보고 

수정을 해보는 과정을 해보겠습니다.

 

 

MainActivity.java

package com.example.stickode;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
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);
        }
    }
}

Deprecated 된 startActivityForResult

 

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.example.stickode;

import androidx.appcompat.app.AppCompatActivity;

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

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>

 

 

이제 기존의 MainAcitivity를 수정해 보겠습니다.

 

1. Activity Result에 콜백 등록 (Registering a callback for an Activity Result)

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로 돌아왔다. ");
            }
        }
    });

 

2. 결과를 위한 활동 실행 (Launching an activity for result)

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