NotificationManager 和Notification的使用总结(转)
文章分类:移动开发
这几天一直在修改twigee的源代码,其中一个要加入的功能是常驻Notification栏,以前写的时候只能出现 在“通知”这一组中,想把它放在“正在运行”组中却不知道怎么放,查了下官方文档,找到了方法,在notification的flags字段中加一下 “FLAG_ONGOING_EVENT”就可以了。同时我也把Notification的使用方法给总结了一下。详见下文:
(
1
)、使用系统定义的Notification
以下是使用示例代码:
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);
int
icon = R.drawable.icon;
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(
this
,Main.
class
);
PendingIntent contentIntent = PendingIntent.getActivity(
this
,
0
,notificationIntent,
0
);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(
0
,notification);
如果想要更新一个通知,只需要在设置好notification之后,再次调用 setLatestEventInfo(),然后重新发送一次通知即可,即再次调用notify()。
(
2
)、使用自定义的 Notification
要创建一个自定义的Notification,可以使用RemoteViews。要定义自己的扩展消息,首先 要初始化一个RemoteViews对象,然后将它传递给Notification的contentView字段,再把PendingIntent传递给 contentIntent字段。以下示例代码是完整步骤:
<?xml version=
"1.0"
encoding=
"utf-8"
?>
android:layout_width=
"fill_parent"
android:layout_height=
"fill_parent"
>
<ImageView android:id=
"@+id/image"
android:layout_width=
"wrap_content"
android:layout_height=
"fill_parent"
android:layout_marginRight=
"10dp"
/>
<TextView android:id=
"@+id/text"
android:layout_width=
"wrap_content"
android:layout_height=
"fill_parent"
android:textColor=
"#000"
/>
</LinearLayout>
RemoteViews contentView =
new
RemoteViews(getPackageName(),R.layout.view);
contentView.setImageViewResource(R.id.image,R.drawable.icon);
contentView.setTextViewText(R.id.text,”Hello,
this
message is in a custom expanded view”);
notification.contentView = contentView;
Intent notificationIntent =
new
Intent(
this
,Main.
class
);
PendingIntent contentIntent = PendingIntent.getActivity(
this
,
0
,notificationIntent,
0
);
notification.contentIntent = contentIntent;
mNotificationManager.notify(
2
,notification);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);
int
icon = R.drawable.icon;
CharSequence tickerText =
"Hello"
;
long
when = System.currentTimeMillis();
Notification notification =
new
Notification(icon,tickerText,when);
RemoteViews contentView =
new
RemoteViews(getPackageName(),R.layout.view);
contentView.setImageViewResource(R.id.image, R.drawable.iconempty);
contentView.setTextViewText(R.id.text,
"Hello,this is JC"
);
notification.contentView = contentView;
Intent notificationIntent =
new
Intent(
this
,Main.
class
);
PendingIntent contentIntent = PendingIntent.getActivity(
this
,
0
,notificationIntent,
0
);
notification.contentIntent = contentIntent;
mNotificationManager.notify(
0
,notification);