从字面可以看出这应该是一种远程view,与远程service概念一样,RemoteViews表示的是一种view结构,这种view能够在其他进程显示。由于需要跨进程显示,RemoteViews结构提供了一组基础功能用于跨进程更新View。RemoteViews在Android中有2种应用场景:Notification以及桌面小部件。
RemoteViews的应用
平时的开发过程中,Notifications主要通过NotificationManager的notify方法实现的,它除了默认效果外,还可以另外定义布局。使用RemoteViews实现通知栏时无法像Activity里面一样直接更新View,这是因为RemoteView界面运行在其他进程中,确切来说是系统的SystemServer进程。使用系统默认的样式弹出一个通知是很简单的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| Notification notification = newNotification(); notification.icon = R.drawable.icon; notification.tickerText = "hello world"; notification.when = System.currentTimeMillis(); notification.flags = Notification.FLAG_AUTO_CANCEL; Intent intent = new Intent(this,DemoActivity_1.class); PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this,"chapter_5","this is notification",pendingIntent); NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(1,notification);
RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.layout_notification); remoteViews.setTextViewText(R.id.msg,"chapter_5"); 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(2,notification);
|
以上代码展示只要提供当前应用的包名以及布局文件的id即可创建一个RemoteViews对象,而更新RemoteViews,由于无法直接访问里面的view,因而只能通过RemoteViews提供的一系列方法来更新,比如设置文本,需要采用 remoteViews.setTextViewText(R.id.msg,”chapter_5”) ,而更新图片则采用 remoteViews.setImageViewResource(R.id.icon,R.drawable.icon1),如果要给一个控件添加click事件,则要使用PendingIntent并且通过setOnclickPendingIntent。关于PendingIntent,它表示一种待定的Intent,这个Intent中所包含的意图必须由用户来出发。
RemoteViews在桌面小部件上的应用、PendingIntent概述、RemoteViews的内部机制等内容 待后续有集中的时间再添加