Search code examples
javaandroidnotificationsandroid-notificationsnotification-listener

Notification Listener - onNotificationPosted doesn't work


I'have tried all kind of solutions and code but any of this solutions worked for me, and I don't know why. Please help me.

My MainActivity code is:

if(isNotificationServiceEnabled())
    {
        Intent i= new Intent(this,NotificationsService.class);
        i.putExtra("command", "get_status");
        startService(i);
    }
    else
        startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));

Now I'm just tryng to check if the service read a nostification posted, but from log i can only see that it enters in onCreate method but no in onNotificationPosted.

This is the code for my service class:

public class NotificationsService extends NotificationListenerService {

@Override
public void onListenerConnected(){
    Log.d(TAG, "Connected");
}

@Override
public void onNotificationPosted(final StatusBarNotification sbn){

    Log.d(TAG,"got it");

}

I have tried also solutions with broadcast service , but it still doesn't work.

Thanks.


Solution

  • I have found the solutions. In my code I had some problems, but then I tested other code about notification listener in an other project, and It worked. So then I modify my code and now it works.

    About notification lisener You don't need to launch the service, because when you launch the app the service is launched. So I just made this changes to my code:

    Main

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        if(!isNotificationServiceEnabled())
        {
            startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
        }
    
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    } 
    

    And in the service I just put the log code to write in debug the notification package.

    Instead I got that broadcast are just used to exchange the data between service and my activity, for example to write the notifications in a textview.