理解RemoteViews

RemoteViews的应用

RemoteViews的作用是在其他进程中显示并且更新界面。
RemoteViews的常用场景有两个:1、通知栏;2、桌面小部件

RemoteViews在通知栏上的应用

/**
1,构造一个Notification;
2,RemoteViews布局一个界面;
3,使用一个PendingIntent监听点击事件
4,PendingIntent中的Intent可以启动一个新的Activity
*/
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.getActivity(this,
        0, intent, 
        PendingIntent.FLAG_UPDATE_CURRENT);
System.out.println(pendingIntent);
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在桌面小部件上的应用 /

/**
1,构造一个桌面小部件AppWidgetProvider
(AppWidgetProvider它其实是BroadcastReceiver因为AppWidgetProvider extends BroadcastReceiver);
2,RemoteViews布局一个界面;
3,使用一个PendingIntent监听点击事件
4,PendingIntent中的Intent可以发送广播更新桌面小部件;
*/
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget);

// "窗口小部件"点击事件发送的Intent广播
Intent intentClick = new Intent();
intentClick.setAction(CLICK_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intentClick, 0);
remoteViews.setOnClickPendingIntent(R.id.imageView1, pendingIntent);
appWidgeManger.updateAppWidget(appWidgetId, remoteViews);

RemoteViews的内部机制

通知栏和桌面小部件分别由NotificationManager和AppWidgetManger管理。而NotificationManager和AppWidgetManger通过Binder分别和SystemServer中的NotificationManagerService和AppWidgetService进行 通信。通知栏和桌面小部件的布局文件是在NotificationManagerService以及AppWidgetService中被加载的。
首先RemoteViews会通过Binder传递到SystemServer进程。RemoteViews实现了Parcelable接口,因此它可以跨进程传输。系统会根据RemoteViews中的包名信息去得到应用的资源,然后通过LayoutInflater去加载RemoteViews中的布局文件。接着系统会对View进行一系列的更新操作。
这里写图片描述

RemoteViews的意义

一个应用需要更新另外一个应用中的某个界面,这时候可以采用AIDL去实现。但是如果界面更新太频繁,这个时候就有效率的问题,同时 AIDL接口也会变的复杂。这个时候可以采用RemoteViews来实现。不过RemoteViews只支持一些常见的View。

参考文章

1,Android中pendingIntent的深入理解
http://blog.csdn.net/yuzhiboyi/article/details/8484771

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值