Web.11
Web.11

Reputation: 416

Read incoming notifications in real-time android

I'm trying to read all incoming notifications in a text view...

I want to look something like this

I found some codes, but all mixed up and does not work, any help will be very appreciated.

enter image description here

Upvotes: 0

Views: 6046

Answers (1)

motis10
motis10

Reputation: 2596

It will work from: Android 4.3 (JELLY_BEAN_MR2).

  1. Add to your manifest new permission android.permission.BIND_NOTIFICATION_LISTENER_SERVICE.

  2. Create NotificationListenerService class and add to the manifest.
    From Google Developer:

Must be required by an NotificationListenerService, to ensure that only the system can bind to it.

AndroidManifest.xml:

<service android:name=".NotificationListener"
         android:label="@string/service_name"
      android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>
  1. Override the onNotificationPosted().

NotificationListenerService Class:

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class NotificationListenerService extends NotificationListenerService {

@Override
public void onNotificationPosted(final StatusBarNotification sbn) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// Here you need to play with the sbn object and get the data that you want from it.

        //sbn.getPackageName()
        Notification notification = sbn.getNotification();
        Bundle extras = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            extras = notification.extras;
        }

        if (extras != null) {
            extras.get("android.title");
        }
    }
}

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
    }

    @Override
    @TargetApi(Build.VERSION_CODES.N)
    public void onListenerDisconnected() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // Notification listener disconnected - requesting rebind
            requestRebind(new ComponentName(this, NotificationListenerService2.class));
        }
    }
}

Developer reference: https://developer.android.com/reference/android/service/notification/NotificationListenerService.html

Simple example application for implementation: https://github.com/kpbird/NotificationListenerService-Example/

Upvotes: 3

Related Questions