安开发卓之Notification(一)代码直接能用

  Notification是Android中很理想的一种显示提示信息的方法,它能够将应用程序的信息传递到咱们的Android桌面状态栏,采用这种消息传递方式不会影响到用户对手机的正常使用。并且Notification不单单能够传递文字信息,还能够传递图片信息,甚至能够将咱们的控件追加到上面,只要用户不对其进行清空,那么消息将一直保存在用户桌面的状态栏当中。android

Notification一般用来进行对用户的更新提醒等消息的传递。spa

  Notification须要使用到NotificationManager(消息通知管理类)对消息进行管理,其建立须要五个步骤:对象

(1)经过getSystemService获取Notification对象图片

(2)建立一个Notification,每个notification对应一个notification对象。资源

(3)建立一个PendingIntent对象get

(4)使用notification类的setLatestEventInfo方法设置Notification对象的详细信息it

(5)使用NotificationManager对象的notify方法显示消息io

 

在第二步时应当注意须要设置显示在屏幕上方状态栏的通知消息、通知消息前方的图像资源ID和放出通知的时间,通常为当前时间ast

(3)建立PendingIntent对象:test

因为notification能够与应用程序脱离,也就是说你的应用程序已经关闭,消息仍然显示在状态栏之中,当应用程序再次启动后,又能够从新控制这些notification,如清除、替换等工做。所以须要PendingIntent对象,该对象由安卓系统维护,所以,应用程序关闭后,消息仍然不会被释放。

(4)在使用notify方法时须要指定Notification对象的惟一ID,这个ID必须相对于一个Notificationmanager对象来讲是惟一的,不然就会覆盖相同ID的

Notification

NotificationManager manager  = (NotificationManager)

    getSystemService(NOTIFICATION_SERVICE);

    String notice = "您有短消息了!";

    Notification notification = new Notification(R.drawable.ic_launcher, notice,System.currentTimeMillis());

    PendingIntent contentIntent = PendingIntent.getActivity

    (getApplicationContext(), 0, getIntent(), 0);

    notification.setLatestEventInfo

    (getApplicationContext(), "小搬运工又变帅了", "华中软件龙头企业", contentIntent);

    notification.defaults = Notification.DEFAULT_SOUND;

    notification.defaults = Notification.DEFAULT_LIGHTS;

    notification.defaults = Notification.DEFAULT_VIBRATE;

    notification.defaults = Notification.DEFAULT_ALL;

    manager.notify(R.drawable.ic_launcher,notification);

一、若是要调取声音,需用使用到:android:name=“android.permission.VIBRATE”权限

  NotificationManager.cancel(resId)清除某个数据 NotificationManager.cancelAll()清除某个NotificationManager对象中的全部消息。
在清除完消息后,须要作一些善后工做,须要经过notification,deleteIntent来完成,deleteIntent也须要一个pendingIntent类型的变量,用于在清除所用的notification对象时调用。这个动做能够与Activity、Service、Broadcast关联。

若是想永久保存推送的通知,须要增长代码:

•notification.flags = Notification.FLAG_NO_CLEAR;
相关文章
相关标签/搜索