ภาพรวม
ตัวอย่างนี้สาธิตการใช้ NotificationListenerService เพื่อตรวจจับการแจ้งเตือนทั้งหมดที่ปรากฏบนอุปกรณ์ (รวมถึงจากแอปอื่น) และส่งข้อมูลกลับไปยัง Activity ผ่าน Interface
ขั้นตอนที่ 1: สร้างโปรเจกต์
Android Studio → File → New Project
ขั้นตอนที่ 2: สร้าง Interface (src/MyListener.java)
package app.tutorialspoint.com.notifyme;
public interface MyListener {
void setValue(String packageName);
}
ขั้นตอนที่ 3: NotificationListenerService (src/NotificationService.java)
package app.tutorialspoint.com.notifyme;
import android.content.Context;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
public class NotificationService extends NotificationListenerService {
private String TAG = getClass().getSimpleName();
private Context context;
private static MyListener myListener;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i(TAG, "********** onNotificationPosted");
Log.i(TAG, "ID: " + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
if (myListener != null) {
myListener.setValue("Posted: " + sbn.getPackageName());
}
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i(TAG, "********** onNotificationRemoved");
Log.i(TAG, "ID: " + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
if (myListener != null) {
myListener.setValue("Removed: " + sbn.getPackageName());
}
}
public static void setListener(MyListener listener) {
myListener = listener;
}
}
ขั้นตอนที่ 4: Menu (res/menu/menu_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<menu 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"
tools:context=".MainActivity">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="Settings"
app:showAsAction="never" />
</menu>
ขั้นตอนที่ 5: Layout (res/layout/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="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/btnCreateNotification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:text="Create Notification" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/btnCreateNotification"
android:layout_alignStart="@id/btnCreateNotification"
android:layout_alignEnd="@id/btnCreateNotification"
android:layout_alignParentBottom="true">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="NotificationListenerService Example"
android:textAppearance="?android:attr/textAppearanceMedium" />
</ScrollView>
</RelativeLayout>
ขั้นตอนที่ 6: MainActivity.java
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
public class MainActivity extends AppCompatActivity implements MyListener {
private TextView txtView;
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ลงทะเบียน Listener
new NotificationService().setListener(this);
txtView = findViewById(R.id.textView);
Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
btnCreateNotification.setOnClickListener(v -> {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
MainActivity.this, default_notification_channel_id)
.setContentTitle("My Notification")
.setContentText("Notification Listener Service Example")
.setTicker("Notification Listener Service Example")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setAutoCancel(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "Channel", importance);
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
assert manager != null;
manager.createNotificationChannel(channel);
}
assert manager != null;
manager.notify((int) System.currentTimeMillis(), builder.build());
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
// เปิดหน้าตั้งค่า Notification Access
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void setValue(String packageName) {
txtView.append("\n" + packageName);
}
}
ขั้นตอนที่ 7: AndroidManifest.xml - สิทธิ์และประกาศ Service
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.notifyme">
<uses-permission android:name="android.permission.VIBRATE" />
<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>
<!-- NotificationListenerService ต้องมี Permission นี้ -->
<service
android:name=".NotificationService"
android:label="@string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
</manifest>
วิธีใช้งาน
- รันแอปบนอุปกรณ์
- ไปที่ Settings → Apps & notifications → Special app access → Notification access
- เปิดสิทธิ์สำหรับแอปนี้
- กลับมาแอป กด "Create Notification" ทดสอบ
- ลองสร้างการแจ้งเตือนจากแอปอื่น (เช่น SMS, Email) จะเห็น Log ใน TextView
ข้อควรระวัง
- ต้องขออนุญาตจากผู้ใช้ผ่านหน้าตั้งค่าระบบ
- ไม่ทำงานบน Emulator บางรุ่น ต้องทดสอบบนเครื่องจริง
- Android 13+ ต้องขอ Permission POST_NOTIFICATIONS แยกต่างหาก