บทนำ
ตัวอย่างนี้สาธิตวิธีตรวจจับว่าอุปกรณ์กำลังเสียบชาร์จเจอร์หรือไม่ โดยใช้ BroadcastReceiver ฟัง Event Intent.ACTION_POWER_CONNECTED
ขั้นตอนที่ 1: สร้างโปรเจกต์
Android Studio → File → New Project → Empty Activity
ขั้นตอนที่ 2: Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp" />
</LinearLayout>
ขั้นตอนที่ 3: โค้ดหลัก (MainActivity.java)
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
private BroadcastReceiver mMessageReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
// สร้าง BroadcastReceiver
mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
textView.setText("Device power is connected");
}
};
}
@Override
protected void onResume() {
super.onResume();
// ลงทะเบียน Receiver เมื่อ Activity Resume
registerReceiver(mMessageReceiver, new IntentFilter(Intent.ACTION_POWER_CONNECTED));
}
@Override
protected void onStop() {
super.onStop();
// ยกเลิกการลงทะเบียนเมื่อหยุดทำงาน
unregisterReceiver(mMessageReceiver);
}
}
ผลลัพธ์

ข้อควรระวังและ Best Practices
- Android 8.0 (API 26) ขึ้นไป: ไม่สามารถลงทะเบียน Implicit Broadcast (เช่น ACTION_POWER_CONNECTED) ใน Manifest ได้แล้ว ต้องลงทะเบียนแบบ Dynamic (Runtime) ใน onResume/onPause เท่านั้น
- Intent.ACTION_POWER_DISCONNECTED: ใช้สำหรับตรวจจับการถอดชาร์จเจอร์
- BatteryManager: สำหรับดูรายละเอียดแบตเตอรี่ (ระดับ, สถานะ, อุณหภูมิ) ใช้
Intent.ACTION_BATTERY_CHANGED(Sticky Broadcast) - Memory Leak: ต้อง
unregisterReceiver()ใน onStop/onDestroy เสมอ
ตัวอย่างเพิ่มเติม: ตรวจสอบสถานะแบตเตอรี่แบบเรียลไทม์
// ดึงสถานะแบตเตอรี่ปัจจุบัน
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, filter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float) scale * 100;
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;