Friday, March 5, 2010

Sending libnotify Notification through C

Libnotify is the nice way to notify users of the important events occurred.
Following is the code to send libnotify notifications through C..

#include <libnotify/notify.h>
#include <glib.h>
#include <unistd.h>
int main(int argc, char** argv)
{
    if(argc == 3)
    {
        NotifyNotification *n;
        notify_init("Test");
        n = notify_notification_new (argv[1],argv[2], NULL, NULL);
        notify_notification_set_timeout(n, 3000); //3 seconds
        if (!notify_notification_show (n, NULL)) {
            g_error("Failed to send notification.\n");
            return 1;
        }
        g_object_unref(G_OBJECT(n));
    }else{
        g_print("Too few arguments (%d), 2 needed.\n", argc-1);
    }
    return 0;
}

NOTE: As Eugene MechanisM pointed out, recent version has changed the API. See his comment for details.


While compiling the program, you need to link libraries... So, to compile and run....

shadyabhi@shadyabhi-desktop:~/c$ vim libnotify.c
shadyabhi@shadyabhi-desktop:~/c$ gcc -Wall -o test libnotify.c `pkg-config --libs --cflags glib-2.0 gtk+-2.0` -lnotify
shadyabhi@shadyabhi-desktop:~/c$ ./test "Heading" "Body of the notification"
shadyabhi@shadyabhi-desktop:~/c$

6 comments:

  1. Thanks!

    a question: where can I find decent documentation for libnotify? If you could help me out I'd really appreciate it.

    ReplyDelete
  2. Install the libnotify-doc and devhelp package..

    sudo apt-get install libnotify-doc devhelp

    Then search in devhelp for "libnotify"

    ReplyDelete
  3. Tried this in Ubuntu 11.10 and got error while compiling:
    eugene@MechanisM:~/BUILD$ gcc -Wall -o test libnotify.c `pkg-config --libs --cflags glib-2.0 gtk+-2.0` -lnotify
    libnotify.c: In function «main»:
    libnotify.c:10:9: error: too much arguments given in calling function «notify_notification_new»
    changed a bit of code to:
    n = notify_notification_new (argv[1],argv[2], NULL);
    And now it's compiling\works perfectly!
    Btw thank you for example now I'll add notifications for my home NGINX server, it will be notify me about new wisitors and where they came from(Via GeoIP) which OS/Browser etc

    ReplyDelete
  4. yeah! I just checked; API has changed a bit. It was an old post. Thanks for informing. Updated the post.

    ReplyDelete
  5. it will be great if you update the code as its always giving same error of argumennts

    ReplyDelete