ภาพรวม
ตัวอย่างนี้แสดงวิธีการเปิดแอปปฏิทินของระบบเพื่อเพิ่มกิจกรรมใหม่โดยใช้ Intent ACTION_EDIT
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project แล้วกรอกข้อมูลที่จำเป็น
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="AddCalendarEvent"
android:text="Add Calendar Event" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Calendar Event In Android"
android:textSize="18sp"
android:textStyle="bold" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (MainActivity.java)
package com.example.calendarevent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void AddCalendarEvent(View view) {
Calendar calendarEvent = Calendar.getInstance();
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", calendarEvent.getTimeInMillis());
intent.putExtra("allDay", true);
intent.putExtra("rule", "FREQ=YEARLY"); // ทุกปี
intent.putExtra("endTime", calendarEvent.getTimeInMillis() + 60 * 60 * 1000); // +1 ชั่วโมง
intent.putExtra("title", "Calendar Event");
// ตรวจสอบว่ามีแอปปฏิทินรองรับหรือไม่
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
}
ขั้นตอนที่ 4: ตั้งค่า Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.calendarevent">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
การทดสอบ
รันแอปพลิเคชันบนอุปกรณ์จริง กดปุ่ม "Add Calendar Event" จะเปิดแอปปฏิทินพร้อมฟอร์มเพิ่มกิจกรรม

ข้อมูลเพิ่มเติม
- ใช้
Intent.ACTION_INSERTกับCalendarContract.Events.CONTENT_URIสำหรับการเพิ่มโดยตรง (ต้องขอ Permission) - วิธีนี้ (ACTION_EDIT) ไม่ต้องขอ Permission แต่ต้องการให้ผู้ใช้กดยืนยันเอง
- รองรับ Extra fields อื่นๆ เช่น description, eventLocation, availability