关键词:RemoteViews / 通知栏 / 桌面小部件 /
RemoteViews 是一种远程 View,是一种远程服务,实际上和远程 Service 是一样的,RemoteViews 是一个 View 结构,可以在其它进程中显示,提供了一组操作用于跨进程更新它的界面。RemoteViews 在 Android 中的使用场景有两种:通知栏 和 桌面小部件。
通知栏和桌面小部件的开发过程都需要用到 RemoteViews,在更新界面时无法像在 Activity 里面那样去直接更新 View,因为二者的界面都运行在其它进程中,即系统的 SystemServer 进程;为了跨进程更新界面,RemoteViews 提供了一系列 set 方法,并且这些方法只是 View 全部方法的子集,RemoteViews 中所支持的 View 类型也是有限的
通知栏主要是通过 NotificationManager 的 notify 方法来实现,除了默认效果还可以自定义。
系统默认的样式很简单:
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);
notification.setLatestEventInfo(this, "hello", "this is a notification.", pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, 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.class);
/ 'PendingIntent 表示的是一种待定的 Intent,这个 Intent 中所包含的意图必须由用户来触发'
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification);
remoteViews.setTextViewText(R.id.msg, "hello");
remoteViews.setImageResource(R.id.icon, R.drawable.icon);
PendingIntent openActivity2PendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, DemoActivity.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(2, notification);
桌面小部件通过 AppWidgetProvider 来实现,本质上是一个广播组件,,因此必须要注册;
".MyAppWidgetProvider" >
"android.appwidget.provider"
android:name="@xml/appwidget_provider_info" >
"io.github.isayes.action.CLICK" />
"android.appwidget.action.APPWIDGET_UPDATE" />
开发步骤;
- 定义小部件界面
- 定义小部件配置信息
- 定义小部件的实现类
- 在 Manifest 文件中声明小部件
Not End.