티스토리 뷰

728x90

기존 코드

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

    btn = findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, SecondActivity.class);

        startActivityForResult(intent, 0); // deprecated
      }
    });
  }

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

    if(resultCode == 0) {
      int total = data.getIntExtra("result", 0);
      Toast.makeText(this, "결과 : " + total, Toast.LENGTH_SHORT).show();
    }
  }

 

변경 코드

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

    btn = findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, SecondActivity.class);

        startActivityResult.launch(intent);
      }
    });
  }

  ActivityResultLauncher<Intent> startActivityResult = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    new ActivityResultCallback<ActivityResult>() {
      @Override
      public void onActivityResult(ActivityResult o) {
        int resultCode = o.getResultCode();
        Intent data = o.getData();
        if(resultCode == 0) {
          int total = data.getIntExtra("result", 0);
          Toast.makeText(MainActivity.this, "결과333 : " + total, Toast.LENGTH_SHORT).show();
        }
      }
    }
  );