RemoteView应该是一种远程View,表示的是一个View结构,他可以在其它进程中显示.
在android中使用场景有两种:通知栏和桌面小部件
5.1 RemoteView的应用
5.1.1 RemoteView在通知栏上的应用
使用系统默认的样式弹出一个通知
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, Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatesEventInfo(this, "hello", "this is 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, Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification);
remoteViews.setTextView(R.id.msg, "hello");
remoteViews.setImageViewResource(R.id.icon, R.drawable,icon1);
PendingIntent openActivity2PendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, Activity.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);
需要提供包名和布局文件的资源id即可创建一个RemoteViews对象.
5.1.2 RemoteViews在桌面小部件上的应用
AppWidgetProvider是android中提供的用于实现桌面小部件的类,本质上是一个广播,即BroadcastReceiver.
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/widget"//初始化布局
android:minHeight="84dp" //最小尺寸
android:minWidth="84dp"
android:updatePeriodMillis="8640000">//自动更新的周期
3.定义小部件的实现类(需要继承AppwidgetProvider)
4.在AndroidManifest.xml中声明小部件
<receiver
android:name=".MyAppWidgetProvider">
<meta-date
android:name="android:appwidget.provider"
android:resource="@xml/appwidget_provider_info">
5.1.3 PendingIntent概述
一种处于pending状态的意图,而pending状态表示的是一种待定,等待,即将发生的意思.
PendingIntent是在将来某个不确定的时刻发生,而Intent是立刻发生的.
PendingIntent支持三种待定意图:启动Activity,启动Service和发送广播.
PendingIntent的匹配规则:如果两个PendingIntent他们内部的Intent相同并且requestCode也相同,那么这两个PendingIntent就是相同的.
5.2 RemoteViews的内部机制
RemoteViews的作用是在其他进程中显示并更新View界面.
最常用的构造方法:public ReoteViews(String packageName, int layoutId);
RemoteViews没有提供findViewById方法,因此无法直接访问里面的View元素,而必须通过RemoteViews所提供的一些列set方法.
RemoteViews的内部机制图:
手机扫一扫
移动阅读更方便
你可能感兴趣的文章