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