Android 开发艺术探索笔记之五 -- 理解 RemoteViews

学习内容:

  • RemoteViews 在通知栏和桌面小部件上的应用
  • RemoteViews 的内部机制
  • RemoteViews 的意义

RemoteView 的应用

实际开发中,RemoteViews 主要用在通知栏和桌面小部件的开发过程中。通知栏主要通过 NotificationManager 的 notify 方法实现,桌面小部件则是通过 AppWidgetProvider 来实现,其本质也是一个广播。

通知栏和桌面小部件更新界面时,RemoteView 无法像 View 一样在 Activity 中直接更新,因为界面运行在系统的 SystemServer 进程,需要跨进程更新。

下面简单介绍 RemoteView 的应用

  1. 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。ÿ

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值