萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android Activity 間互動:Intent 傳值、startActivity、getIntent 完整範例

Intent 核心組成

  • ComponentName:目標類別 (setClass / setComponent)。
  • Action:標準動作 (ACTION_VIEW, ACTION_SEND...)。
  • Data:Uri 資料。
  • Extras:Key-Value 附加資料 (putExtra / getStringExtra)。

啟動端 (Activity_02)

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);
        });
    }
}

接收端 (OtherActivity)

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);

返回結果 (startActivityForResult / Activity Result API)

// 舊 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 啟動系統功能

// 撥打電話
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。

copyright © 萬盛學電腦網 all rights reserved