多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
#### 5.1.1 RemoteViews在通知栏上的应用 首先我们看一下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); 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); 上述代码会弹出一个系统默认样式的通知,单击通知后会打开DemoActivity_1同时会清除本身。为了满足个性化需求,我们还可能会用到自定义通知。自定义通知也很简单,首先我们要提供一个布局文件,然后通过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); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 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, openActivity2- PendingIntent); notification.contentView = remoteViews; notification.contentIntent = pendingIntent; NotificationManager manager = (NotificationManager)getSystemService (Context.NOTIFICATION_SERVICE); manager.notify(2, notification); 从上述内容来看,自定义通知的效果需要用到RemoteViews,自定义通知的效果如图5-1所示。 :-: ![](https://img.kancloud.cn/03/ae/03aea407cf1232d5cdf20ba03cb96704_535x609.png) 图5-1 自定义通知栏样式 RemoteViews的使用也很简单,只要提供当前应用的包名和布局文件的资源id即可创建一个RemoteViews对象。如何更新RemoteViews呢?这一点和更新View有很大的不同,更新RemoteViews时,无法直接访问里面的View,而必须通过RemoteViews所提供的一系列方法来更新View。比如设置TextView的文本,要采用如下方式:remoteViews. setTextViewText(R.id.msg, "chapter_5"),其中setTextViewText的两个参数分别为TextView的id和要设置的文本。而设置ImageView的图片也不能直接访问ImageView,必须通过如下方式:remoteViews.setImageViewResource(R.id.icon, R.drawable.icon1), setImageViewResource的两个参数分别为ImageView的id和要设置的图片资源的id。如果要给一个控件加单击事件,则要使用PendingIntent并通过setOnClickPendingIntent方法来实现,比如remoteViews.setOnClickPendingIntent(R.id.open_activity2, openActivity2Pending- Intent)这句代码会给id为open_activity2的View加上单击事件。关于PendingIntent,它表示的是一种待定的Intent,这个Intent中所包含的意图必须由用户来触发。为什么更新RemoteViews如此复杂呢?直观原因是因为RemoteViews并没有提供和View类似的findViewById这个方法,因此我们无法获取到RemoteViews中的子View,当然实际原因绝非如此,具体会在5.2节中进行详细介绍。