第五章 理解 RemoteViews.md

1059

第五章 理解 RemoteViews

RemoteViews 是一种跨进程的 View,通过 RemoteViews 对象,我们可以在其他进程显示自己的 View 同时进行一些更新,本章将会介绍一下 RemoteViews 。

5.1 RemoteViews 的应用

RemoteViews 主要的应用有两点,一是在通知栏中的应用,二是在桌面小部件上的作用。

5.1.1 RemoteViews 在通知栏上的应用

以下代码实现使用系统默认的样式弹出一个通知:

Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.tickerText = "HelloWorld";
notification.when = System.currentTimeMillis();
nofification.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, DemoActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
    this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
nofification.setLatestEventInfo(this, "chapter_5", "this is notification.", pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, notification);

以上是默认样式的 通知,点击后会跳转到 DemoActivity 。

当然我们也可以使用自定义布局,自定义时我们需要提供一个布局文件,然后通过 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.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
    this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteVies remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification);
remoteViews.setTextViewText(R.id.msg, "chapter_5");
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_activity, openActivity2PendingIntent);
notification.contentView = remoteVies;
notification.contentIntent = pendingIntent;
NotificationManager manager = (NotificationManager) getSystemService(Content.NOTIFICATION_SERVICE);
manager.notify(2, notification);

5.1.2 RemoteViews 在桌面小部件上的作用

5.1.3 PendingIntent 概述

5.2 RemoteViews 的内部机制

5.3 RemoteViews 的意义