[android] Get text from StatusBarNotification

android os version >= 4.3

public static boolean isContainedInNotificationListeners(Context $context)
{
  String enabledListeners = Settings.Secure.getString($context.getContentResolver(), "enabled_notification_listeners");
  return !TextUtils.isEmpty(enabledListeners) && enabledListeners.contains($context.getPackageName());
}

 

if (!isContainedInNotificationListeners(getApplicationContext()))
{
  Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
  startActivityForResult(intent, 2222);
}

 

 

@SuppressLint("NewApi")
public class NotificationServiceForAfterJellybeanMR2 extends NotificationListenerService
{
  @Override
  public void onNotificationPosted(StatusBarNotification event)
  {
    String msg = null;

    String packageName = event.getPackageName().toString();

    if (TextUtils.isEmpty(event.getNotification().tickerText))
      msg = getText(event);
    else
      msg = event.getNotification().tickerText.toString();

    Log.i("###", "msg = " + msg);
  }

  private String getText(StatusBarNotification event)
  {
    String result = null;
    try
    {
      Notification notification = event.getNotification();
      RemoteViews views = notification.contentView;
      Class<?> secretClass = views.getClass();

      Field outerFields[] = secretClass.getDeclaredFields();
      for (int i = 0; i < outerFields.length; i++)
      {
        if (!outerFields[i].getName().equals("mActions"))
          continue;

        outerFields[i].setAccessible(true);

        @SuppressWarnings("unchecked")
        ArrayList<Object> actions = (ArrayList<Object>) outerFields[i].get(views);
        for (Object action : actions)
        {
          Field innerFields[] = action.getClass().getDeclaredFields();

          Object value = null;
          Integer type = null;
          for (Field field : innerFields)
          {
            field.setAccessible(true);
            if (field.getName().equals("value"))
              value = field.get(action);
            else if (field.getName().equals("type"))
              type = field.getInt(action);
          }

          if (type != null && type == 10)
            result = value.toString();
        }
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }

    return result;
  }

  @Override
  public void onNotificationRemoved(StatusBarNotification arg0)
  {

  }
}

 

 

<service
    android:name="kr.mint.test.services.NotificationServiceForAfterJellybeanMR2"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" >
        </action>
    </intent-filter>
</service>