ภาพรวม
ตัวอย่างนี้สาธิตการใช้ NotificationListenerService เพื่อฟังการแจ้งเตือนทั้งหมดที่ปรากฏบนระบบ (System-wide) รวมถึงจากแอปอื่น และส่งข้อมูลกลับมาแสดงในแอป
ขั้นตอนที่ 1: สร้างโปรเจกต์
Android Studio → File → New Project
ขั้นตอนที่ 2: Interface (src/MyListener.java)
package app.tutorialspoint.com.notifyme;
public interface MyListener {
void onNotificationReceived(String packageName, String text);
}
ขั้นตอนที่ 3: NotificationListenerService (src/NotificationListenerService.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 NotificationListenerService extends NotificationListenerService {
private static final String TAG = "NotifListener";
private static MyListener listener;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pkg = sbn.getPackageName();
String text = "";
if (sbn.getNotification().extras != null) {
text = sbn.getNotification().extras.getString(Notification.EXTRA_TEXT, "");
}
Log.i(TAG, "Posted: " + pkg + " - " + text);
if (listener != null) {
listener.onNotificationReceived(pkg, text);
}
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i(TAG, "Removed: " + sbn.getPackageName());
if (listener != null) {
listener.onNotificationReceived("REMOVED: " + sbn.getPackageName(), "");
}
}
public static void setListener(MyListener l) {
listener = l;
}
}
ขั้นตอนที่ 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">
<item
android:id="@+id/action_settings"
android:title="Notification Access 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="match_parent"
android:layout_height="wrap_content"
android:text="Create Test Notification" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/btnCreateNotification"
android:layout_marginTop="16dp">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Detected Notifications:\n"
android:textSize="14sp" />
</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 textView;
public static final String CHANNEL_ID = "10001";
private static final String DEFAULT_CHANNEL = "default";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
Button btn = findViewById(R.id.btnCreateNotification);
// ลงทะเบียน Listener
NotificationListenerService.setListener(this);
btn.setOnClickListener(v -> showTestNotification());
}
private void showTestNotification() {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL)
.setContentTitle("Test Notification")
.setContentText("This will be detected by ListenerService")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setAutoCancel(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Test", NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
builder.setChannelId(CHANNEL_ID);
}
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
startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onNotificationReceived(String packageName, String text) {
runOnUiThread(() -> textView.append("\n[" + packageName + "] " + text));
}
}
ขั้นตอนที่ 7: AndroidManifest.xml
<?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>
<service
android:name=".NotificationListenerService"
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>
วิธีทดสอบ
- รันแอป → กดเมนู "Notification Access Settings"
- เปิด Toggle ให้แอปนี้ (Notification access)
- กลับมาแอป → กด "Create Test Notification"
- ลองรับ SMS, Email, หรือ Notification จากแอปอื่น → จะปรากฏใน TextView
ข้อจำกัดและข้อควรระวัง
- ต้องขออนุญาตจากผู้ใช้โดยตรง (ไม่ใช่ Runtime Permission ปกติ)
- ไม่ทำงานบน Emulator หลายรุ่น ต้องเครื่องจริง
- Android 13+ ต้องการ Permission
POST_NOTIFICATIONSแยกต่างหาก - Service อาจถูกระบบฆ่า ต้องใช้
START_STICKYหรือ Foreground Service