Wednesday, April 16, 2014

Android: Show notification example


Show notification:

        Intent intent = new Intent(context, ExampleReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        Notification n;
        Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            n = new Notification.Builder(context)
                    .setContentTitle("title")
                    .setContentText("Short message\nContent message")
                    .setTicker("ticker message")
                    .setSmallIcon(R.drawable.notification_icon)
                    .setLargeIcon(bm)
                    .setStyle(new Notification.BigTextStyle().bigText("Long message.\nTesting..Testing..\nlooooooooooooooooon message"))
                    .setContentIntent(paramIntent)
                    .setAutoCancel(true).build();
        } else {
            n = new Notification.Builder(context)
                    .setContentTitle("title")
                    .setContentText("Short message\nContent message")
                    .setTicker("ticker message")
                    .setSmallIcon(R.drawable.notification_icon)
                    .setLargeIcon(bm)
                    .setContentIntent(paramIntent)
                    .setAutoCancel(true).getNotification();
        }
        n.flags = n.flags | Notification.FLAG_NO_CLEAR;
        notificationManager.notify(0, n);


Show only the ticker and make it go disappear:

        Intent intent = new Intent(context, ExampleReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        Notification n;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            n = new Notification.Builder(context)
                    .setTicker("ticker message")
                    .setSmallIcon(R.drawable.notification_icon)
                    .setAutoCancel(true)
                    .build();
        } else {
            n = new Notification.Builder(context)
                    .setTicker("ticker message")
                    .setSmallIcon(R.drawable.notification_icon)
                    .setAutoCancel(true)
                    .getNotification();
        }
        notificationManager.notify(0, n);
        notificationManager.cancel(0);


No comments:

Post a Comment