public class Activity_02 extends Activity {
Button btn;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_02);
btn = findViewById(R.id.myButton);
btn.setOnClickListener(v -> {
Intent intent = new Intent();
intent.putExtra("testIntent", "123"); // 傳字串
intent.setClass(this, OtherActivity.class); // 顯式 Intent
startActivity(intent);
});
}
}
public class OtherActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
TextView tv = findViewById(R.id.myTextView);
String val = getIntent().getStringExtra("testIntent");
tv.setText(val); // 顯示 "123"
}
}
// 基本型別
intent.putExtra("int", 100);
intent.putExtra("bool", true);
intent.putExtra("long", 123L);
// 陣列
intent.putExtra("strArr", new String[]{"a","b"});
intent.putExtra("intArr", new int[]{1,2,3});
// Bundle 打包
Bundle b = new Bundle(); b.putString("k", "v");
intent.putExtras(b);
// Parcelable / Serializable 物件
intent.putExtra("obj", myParcelableObj);
// 舊 API (棄用但仍通用)
startActivityForResult(intent, REQUEST_CODE);
// 子頁面
setResult(RESULT_OK, new Intent().putExtra("back", "data"));
finish();
// 新 API (Activity 1.2+ / Fragment 1.3+)
ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> { if (result.getResultCode() == RESULT_OK) { /* handle */ } }
);
launcher.launch(intent);
// 撥打電話
Intent dial = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:0800123456"));
startActivity(dial);
// 發送簡訊
Intent sms = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:0912345678"));
sms.putExtra("sms_body", "Hello");
startActivity(sms);
Intent 是 Android 組件通訊核心,掌握 Extras 傳值、顯式/隱式啟動、回傳結果三大模式,即可靈活串聯 Activity。