5.1、remoteViews的应用(主要用于通知栏和桌面小部件)
通知栏和桌面小部件不能直接去更新view,因为2者的页面都运行在其他进程中,确切来说是系统的SystemServer进程,为了跨进程更新页面,RemoteViews提供了一系列的set方法进行更新。
5.1.1、在通知栏的应用:
通知栏除了默认的效果还可以自定义布局,下面分别说明这2种情况:
默认的布局:
Notification notification = new Notification();
//设置图标
notification.icon = R.drawable.ic_launcher;
//设置内容
notification.tickerText = "hello world";
//要显示的时间,一般是当即显示,故填入系统当前时间。
notification.when = System.currentTimeMillis();
//// FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被自动清除。
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, DemoActivity_2.class);
////该语句的作用是定义了一个不是当即显示的activity,
// 只有当用户拉下notify显示列表,并且单击对应的项的时候,才会触发系统跳转到该activity.
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//在此处设置在nority列表里的该norifycation得显示情况。
notification.setLatestEventInfo(this, "chapter_5", "this is notification.", pendingIntent);
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
// 通过通知管理器来发起通知。如果id不同,则每click,在statu那里增加一个提示
manager.notify(sId, notification);
自定义的布局(使用了remoteViews来加载):
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.tickerText = "hello world";
notification.when = System.currentTimeMillis();
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, DemoActivity_1.class);
intent.putExtra("sid", "" + sId);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
System.out.println(pendingIntent);
//包名和资源ID
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification);
remoteViews.setTextViewText(R.id.msg, "chapter_5: " + sId);
remoteViews.setImageViewResource(R.id.icon, R.drawable.icon1);
PendingIntent openActivity2PendingIntent = PendingIntent.getActivity(this,
0, new Intent(this, DemoActivity_2.class), PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.open_activity2, openActivity2PendingIntent);
notification.contentView = remoteViews;
notification.contentIntent = pendingIntent;
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(sId, notification);
remoteViews使用起来很简单,2个参数即可创建,包名和资源id
更新remoteViews无法直接访问里面的view,必须通过remoteViews提供的方法进行更新
比如: