Thursday, May 3, 2012

Statusbar notification for android mobiles

Statusbar notification for Android  - API Level upto 10 (upto Android 2.3)

                String ns = Context.NOTIFICATION_SERVICE;
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
               
                int icon = R.drawable.ic_launcher;
                CharSequence tickerText = "Hello";
                long when = System.currentTimeMillis();
                Notification notification = new Notification(icon, tickerText, when);
               
                Context context = getApplicationContext();
                CharSequence contentTitle = "My notification";
                CharSequence contentText = "Hello World!";
                Intent notificationIntent = new Intent(context,AlarmNotificationActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
                notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
               
                final int HELLO_ID = 1;

                mNotificationManager.notify(HELLO_ID, notification);

Notification Builder for Android - API Level 11 and above (Android 3.0 and up)

 

                Context ctx = getApplicationContext();
                Toast toast = Toast.makeText(ctx, "Visual notification", Toast.LENGTH_LONG);
                toast.show();
               
                Intent notificationIntent = new Intent(ctx, NotificationBuilderActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(ctx,
                        0, notificationIntent,PendingIntent.FLAG_CANCEL_CURRENT);
                NotificationManager nm = (NotificationManager) ctx.getSystemService(
                        Context.NOTIFICATION_SERVICE);
                Resources res = ctx.getResources();
                Notification.Builder builder = new Notification.Builder(ctx);
                builder.setContentIntent(contentIntent)
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
                .setTicker("ticker string is here")
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setContentTitle("Title")
                .setContentText("Notification text");
                Notification n = builder.getNotification();
                nm.notify(0, n);


No comments: