1.在Manifest中加入以下內容
<service
android:name="com.example.watch.NotificationCollectorService"
android:label="通知欄監聽"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
其中com.example.watch.NotificationCollectorService爲自定義的服務名
2.繼承NotificationListenerService
public class NotificationCollectorService extends NotificationListenerService {
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i("123", "open" + "-----" + sbn.toString());
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("123", "shut" + "-----" + sbn.toString());
}
}
3.讓用戶在手機中勾選我們的APP(首次使用要求用戶勾選,否則service無效)
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);