Notification及桌面小部件的应用(RemoteViews)

最后说一下NotificationManager类的常用方法:

             通过获取系统服务来获取该对象:           

                NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE) ;

      NotificationManager常用方法介绍:

               public  void cancelAll()                                                          移除所有通知 (只是针对当前Context下的Notification)

               public  void cancel(int id)                                                      移除标记为id的通知 (只是针对当前Context下的所有Notification)

               public  void notify(String tag ,int id, Notification notification) 将通知加入状态栏, 标签为tag,标记为id

               public  void notify(int id, Notification notification)                   将通知加入状态栏,,标记为id


可以使用自定义样式和系统默认样式。

默认样式的使用:

1.用Notification的内部类Builder的set方法去设置默认界面的text和image等,还可以设置通知的pendingIntent用于点击通知时启动指定的Activity。

2.使用getSystemService(Context.NOTIFICATION_SERVICE);得到NotificationManager。

3.调用NotificationManager.notify(String tag, int id, Notification notification)。id是本APP中唯一的,tag可以不是唯一的。这样就可以发送一个通知了。


使用自定义样式:

1.首先需要新建一个RemoteViews view = new RemoteView(getPackageName(),int layoutId);  notification.contentView = view;

2.view.setTextView (int textViewId, String text);  view.setImageVIewResource(int viewId, int imageResourceId);

3.设置PendingIntent:notification.contentIntent = pendingIntent;设置点击通知触发的PendingIntent

4.为remotesView中的view设置PendingIntent。就是点击某个view触发的pendingIntent。

    remoteViews.setOnClickPendingIntent(int viewId, PendingIntent intent);

5.notificationManager.notify(String tag, int id, Notification notification)。

6.更新remoteView的内容,不能直接获取layout中的view然后去设置新的内容。只能在把layout弄进remoteView中后,再使用remoteViews.setTextVIewText()。remoteViews.setImageViewResources()去改动。


对于Service,有另外一种发通知的方法,就是Service..startForeground(int id, Notification notification)。用这种方式启动的话,调用Service.stopForeground() 的时候会自动取消掉这个通知。






你可能感兴趣的:(移动开发综合)