学习内容:
- RemoteViews 在通知栏和桌面小部件上的应用
- RemoteViews 的内部机制
- RemoteViews 的意义
RemoteView 的应用
实际开发中,RemoteViews 主要用在通知栏和桌面小部件的开发过程中。通知栏主要通过 NotificationManager 的 notify 方法实现,桌面小部件则是通过 AppWidgetProvider 来实现,其本质也是一个广播。
通知栏和桌面小部件更新界面时,RemoteView 无法像 View 一样在 Activity 中直接更新,因为界面运行在系统的 SystemServer 进程,需要跨进程更新。
下面简单介绍 RemoteView 的应用
RemoteView 在通知栏上的应用(主要为 自定义布局)
(适配 Android 8.0)
//创建NotificationManager实例 NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); //创建NotificationChannel实例 //参数说明: //id:NotificationChannel的唯一标识 //name:NotificationChannel的名称,在Settings可看到 //importance:对channel设置重要性,更改见后续表格 NotificationChannel mChannel = new NotificationChannel("id","name",NotificationManager.IMPORTANCE_DEFAULT); mManager.createNotificationChannel(mChannel); //创建PendingIntent Intent intent = new Intent(this,SecondActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT); //创建RemoteView RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.layout_notification); remoteViews.setTextViewText(R.id.msg,"xx"); remoteViews.setImageViewResource(R.id.icon,R.drawable.icon); remoteViews.setOnclidePendingIntent(R.id.clickable,pendingIntent); //创建builder,并设置一系列属性 Notification.Builder builder = new Notification.Builder(this,"id"); builder.setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle("title") .setContentText("text") //以上三个为必需的属性 .setAutoCancel(true); //Android 7.0 之后需要通过Notification.Builder设置contentView builder.setCustomContentView(remoteViews). //创建通知 Notification notification = builder.build(); //推送通知 mManager.notify(1,notification);
RemoteViews 和 View 不同,每个方法中几乎都要求传入一个 id 参数,比如 setTextViewText(int viewId, CharSequence text),需要传入TextView 的 id。
直观原因 是因为 RemoteViews 没有提供和 View 类似的 findViewById 这个方法,因此我们无法获取到 RemoteView 中的子 View。ÿ