startActivityForResult过时变为ActivityResultLauncher,下面只做了简单的跳转和弹出返回数据,有其他的使用不定时更新
public class MainActivity extends AppCompatActivity { ActivityResultLauncher<Intent> launcher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == RESULT_OK) { //拿到返回的数据 String str = result.getData().getStringExtra("data"); Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show(); } }); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.go).setOnClickListener(view -> { //使用 launcher.launch(new Intent(this, MainActivity2.class)); }); } }
返回的用法是一样的
public class MainActivity2 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); Intent intent = new Intent(); intent.putExtra("data", "132456789"); setResult(RESULT_OK, intent); finish(); } }