Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

Intent ใน Android คืออะไร? ตัวอย่างการใช้งานเริ่ม Activity ใหม่

Intent ใน Android: กลไกการสื่อสารระหว่าง Components

Intent คือ Object ที่ใช้ Request Action: Start Activity, Start Service, Send Broadcast, หรือส่งข้อมูลระหว่าง Components

ประเภทของ Intent

  • Explicit Intent: ระบุ Target Class โดยตรง (Internal)
  • Implicit Intent: ระบุ Action/Data ให้ System หา Component (Cross-app)

ตัวอย่าง: Explicit Intent - Start New Activity

1. Layout: MainActivity (activity_main.xml)

<Button
    android:id="@+id/btnSend"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Go to Second Activity"
    android:layout_gravity="center" />

2. Layout: SecondActivity (activity_second.xml)

<TextView
    android:id="@+id/tvData"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:layout_gravity="center" />

3. MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button btnSend = findViewById(R.id.btnSend);
        btnSend.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            intent.putExtra("message", "Hello from MainActivity!");
            startActivity(intent);
        });
    }
}

4. SecondActivity.java

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        
        TextView tvData = findViewById(R.id.tvData);
        String message = getIntent().getStringExtra("message");
        tvData.setText(message != null ? message : "No data received");
    }
}

5. AndroidManifest.xml

<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<activity android:name=".SecondActivity" />

คำอธิบายโค้ดสำคัญ

  • new Intent(Context, TargetClass.class): สร้าง Explicit Intent
  • putExtra(key, value): ส่งข้อมูล (Primitive, String, Parcelable, Serializable)
  • startActivity(intent): ขอให้ System เริ่ม Activity
  • getIntent(): ดึง Intent ที่เริ่ม Activity นี้
  • getStringExtra(key): อ่านข้อมูลกลับ (คืนค่า null หากไม่มี)

รันทดสอบ

  1. Run App → หน้า Main แสดงปุ่ม
  2. กดปุ่ม → ไปหน้า SecondActivity แสดงข้อความ "Hello from MainActivity!"
  3. กด Back → กลับมาหน้า Main

Intent Flags (ควบคุม Behavior)

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

ส่งข้อมูลกลับ (StartActivityForResult - Deprecated API 30+)

Modern Way: Activity Result APIs (ActivityResultContracts)

// In MainActivity (ComponentActivity/FragmentActivity)
ActivityResultLauncher<Intent> launcher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == RESULT_OK && result.getData() != null) {
            String returnData = result.getData().getStringExtra("return_key");
            // Handle return data
        }
    }
);

launcher.launch(new Intent(this, SecondActivity.class));

สรุป

Intent เป็นหัวใจของ Android Component Communication ใช้ Explicit สำหรับ Internal Navigation, Implicit สำหรับ System Actions (Share, View, Dial, Pick) และ Activity Result APIs สำหรับ Receive Data Back

Flagคำอธิบาย
FLAG_ACTIVITY_NEW_TASKเริ่ม Task ใหม่ (ใช้จาก Service/Notification)
FLAG_ACTIVITY_CLEAR_TOPถ้า Activity อยู่ใน Stack แล้ว ให้ Clear ทุกอย่างด้านบน และ Resume อันเดิม
FLAG_ACTIVITY_SINGLE_TOPถ้าอยู่บน Top Stack อยู่แล้ว ไม่สร้างใหม่ (ใช้ onNewIntent)
FLAG_ACTIVITY_NO_HISTORYไม่เก็บใน Back Stack (Finish ทันทีเมื่อออก)