青玄 发表于 2014-11-19 17:04:42

[原创]android学习之在状态栏上显示消息通知

要想实现在状态栏上显示消息通知的话,首先我们得先得到一个通知管理器:NotificationManager
然后获得一个Builder对象,在这个对象里面设置消息的信息,设置好之后,通过builder.build()方法获得
通知对象:Notification.然后调用通知管理器:notificationManager.notify(1, notification);将通知对象以参数的形式传递进去就可以了;
其主要实现的代码如下:

public void sendNotification(View v)
        {
                //new Notification();
//                Notification notification = new Notification();
//                notification.icon = R.drawable.ic_launcher;
//                notification.tickerText = "有商品更新";
//               
//                Intent intent = new Intent();
//                intent.setClassName("com.example.video", "com.example.video.MainActivity");
//                PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, 0);
//               
//                notification.setLatestEventInfo(this, "莫惹秋风断残雪", "清凌河月九江照,落日挥洒玉门口", pendingIntent);
               
                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                Intent intent = new Intent();    //这里是一个意图对象
                intent.setClassName("com.example.video", "com.example.video.MainActivity");   这个是设置点击一个消息会跳转到那个页面
                PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, 0);   //将意图以参数的形式设置到////这个对象里面
               
                Notification.Builder builder = new Notification.Builder(this);
                builder.setAutoCancel(true);
                builder.setContentTitle("莫惹秋风断残雪");
                builder.setContentText("清凌河月九江照,落日挥洒玉门口");
                builder.setContentIntent(pendingIntent);   //将pendingIntent加入到里面,这个是设置意图内容的
                builder.setSmallIcon(R.drawable.ic_launcher);
                builder.setWhen(System.currentTimeMillis());
                Notification notification = builder.build();
                notificationManager.notify(i++,notification);   //将通知对象加到通知管理器里面
               
        }



小人 发表于 2014-11-19 18:38:11

厉害,支持楼主{:9_236:}
页: [1]
查看完整版本: [原创]android学习之在状态栏上显示消息通知