Android Code Snippet NotificationListener get small icon

I have been using notificationListener for a while now and could not find the way on how to get the small icon, so I'm sharing this code that works for me, it gets the small icon but not the background color (don't know how to get it).
First we need to get the android.icon int and package name from the service
B4X:
Sub Listener_NotificationPosted (SBN As StatusBarNotification)
    Dim Extras As JavaObject = GetExtras(SBN)
    Dim smallIcon As int = Extras.RunMethod("getInt", Array As Object("android.icon"))
    Dim PackageName As string = SBN.PackageName
End Sub

Public Sub GetExtras(SBN As StatusBarNotification) As JavaObject
    Dim p As Phone
      If p.SDKversion >= 19 And SBN.IsInitialized Then
        Dim jno As JavaObject = SBN.Notification
        If jno.IsInitialized Then
              Dim Extras As JavaObject = jno.GetField("extras")
              Extras.RunMethod("size", Null)
          Return Extras
     End If
      End If
End Sub
Save smallIcon int and PackageName string in a public variable or file so you can use it later in your activity module and run this code.
B4X:
Try
    Dim r As Reflector
    r.Target = r.GetContext
    r.Target = r.RunPublicmethod("createPackageContext",Array(PackageName,0),Array As String("java.lang.String","java.lang.int")) 'PackageName obtained in the service
    r.Target = r.RunMethod("getResources")
    r.Target = r.RunMethod2("getDrawable",smallIcon,"java.lang.int") 'smallIcon obtained in the service
    Dim icon As BitmapDrawable = r.Target
    Dim ic As Bitmap 'THIS IS THE SMALL ICON
    ic.Initialize3(icon.Bitmap)
    lblimg.SetBackgroundImage(ic)   'set it to a label or save it in a file
Catch
    Log(LastException)
End Try
If I forgot something, let me know.
 
Last edited:

GeoT

Active Member
Licensed User
Longtime User
Hi.
I just wanted to note that with new Android versions this line always returns zero
B4X:
Dim smallIcon As int = Extras.RunMethod("getInt", Array As Object("android.icon"))


It is necessary to add, for those versions, the code
B4X:
        If smallIcon = 0 Then
            Dim jno1 As JavaObject = SBN.Notification
            smallIcon = jno1.GetField("icon")
        End If
 
Last edited:
Top