理解RemoteViews
1、RemoteViews的应用
RemoteViews表示的是一个View结构,它可以在其他进程中显示,由于它在其他进程中显示,为了能够更新它的界面,RemoteViews提供了一组基础的操作用于跨进程更新它的界面。
RemoteViews在实际开发中,主要用于在通知栏和桌面小部件的开发中。通知栏和桌面小部件的开发过程都会用到RemoteViews,它们在更新界面时无法像在Activity那样去直接更新View,这是因为二者的界面都运行在其他进程中,确切来说是系统的SystemServer进程。
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_2.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(sId, notification);
为了满足个性化需求,我们还可以自定义通知:首先要提供一个布局文件,然后通过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);
intent.putExtra("sid", "" + sId);
PendingIntent pendingIntent = 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);
2
)、RemoteViews在桌面小部件上的应用
AppWidgetProvider是Android中提供的用于实现桌面小部件的类,其本质是一个广播,即BroadcastReceiver。
3)PendingIntent概述
PendingIntent表示一种处于pending状态的意图,而pending状态表示的是一种待定、等待、即将发生的意思,就是说接下来有一个Intent将在某个特定的时刻发生。
PendingIntent是在将来的某个不缺女的时刻发生,而Intent是立刻发生。PendingIntent典型的使用场景是给RemoteViews添加单击事件,因为RemoteViews运行在远程进程中。
PendingIntent支持三种待定意图:启动Activity、启动Service和发送广播,对应着它的三个静态方法getActivity、getService、getBroadcast。
2、RemoteView的内部机制
RemoteViews并不是支持所有的View类型,指支持以下类型的View,无法使用自定义View。
layout:
FramLayout、LinearLayout、RelativeLayout、GridLayout
View:
View:
AnalogClock、Button、Chronometer、ImageBottom、ImageView、ProgressBar、TextView、ViewFlipper、ListView、GridView、StackView、AdapterViewFlipper、ViewStub
3、RemoteView的意义