最近项目中要用到notification,但要想实现功能需要自定义一个layout布局,然后存进 RemoteViews视图,同步显示在statue bar。
http://developer.android.com/guide/topics/ui/notifiers/notifications.html
以上API中,详细的描述了status bar notifications创建的步骤,经过初步分析,默认的notification布局显然不能满足项目需求。
于是自定义notification便因运而生。
Figure 1:创建一个xml布局文件,
custom_notification_demo.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_marginRight="10dp"
/>
<TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/image" style="@style/NotificationTitle"
/>
<!--自定义布局控件-->
<ProgressBar
/> </RelativeLayout>
Figure 2:NotificationManage 管理notification的生命周期,所以应该过滤系统中的systemservice,用来监听notification_service
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout); contentView.setImageViewResource(R.id.image, R.drawable.notification_image); contentView.setTextViewText(R.id.title, "Custom notification"); contentView.setTextViewText(R.id.text, "This is a custom layout"); notification.contentView = contentView;Figure 3:如果想监听notification点击事件,需要定义intent,封装一个pendingIntent对象跳转到指定的activity
Intent notificationIntent = new Intent(this, MyClass.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.contentIntent = contentIntent;此时注意notification要想自动取消需要配置notification.flags |= Notification.FLAG_AUTO_CANCEL;Figure4:开启通知 CUSTOM_VIEW_ID为通知ID,单个取消通知时会用到.mNotificationManager.notify(CUSTOM_VIEW_ID, notification);notificationManager.cancel(notification_id);
android SDK 文档中描述得不是很详细,做自定义notification的时候遇到许多问题,虽然最后都一一解决了,但浪费了不少时间,第一次写技术博客,希望大家多多批评指教。