理解RemoteViews

理解RemoteViews

什么是remoteViews?按照字面意思是远程View,但RemoteViews并没有继承View,而是继承Object。它的作用是可以跨进程更新界面,听起来有点神奇。RemoteViews在Android中的使用场景有两种:通知栏和桌面小部件

  • RemoteViews的应用
    1.在通知栏上的应用
    ①使用系统默认的样式弹出通知
Notification notification= new Notification();
notification.icon = R.drawable.notify;
notification.when = System.currentTimeMillis();
notification.tickerText = "通知";
notification.flags = Notification.FLAG_AUTO_CANCEL;
//创建延时意图
Intent intent = new Intent(this, OtherActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 
                                  PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this,"通知", "具体内容", pendingIntent):
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, notification);

②使用RemoteViews可以自定义布局,通过RemoteViews来加载布局文件即可改变通知的样式,具体代码如下

Notification notification= new Notification();
notification.icon = R.drawable.notify;
notification.when = System.currentTimeMillis();
notification.tickerText = "通知";
notification.flags = Notification.FLAG_AUTO_CANCEL;
//创建延时意图
Intent intent = new Intent(this, OtherActivity.class);
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, "自定义通知");
remoteViews.setImageViewResource(R.id.icon, R.drawable.icon);
PendingIntent pendingIntent2 = PendingIntent.getActivity(this, 0, 
                       new Intent(this, SecondActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.btn, pendingIntent2);
notification.contentView = remoteViews;
notification.contentIntent = pendingIntent;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(1, notification);

2.在桌面小部件上的应用
AppWidgetProvider是Android中提供的用于实现桌面小部件的类,实际上是一个广播。具体实现步骤如下
①定义小部件界面
自定义xml布局文件,具体布局样式根据实际开发需要,如widget.xml
②定义小部件配置信息
在res/xml下新建appwidget_provider_info.xml,名称任意

<xml version="1.0" encoding="utf-8">
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
      android:initialLayout="@layout/widget"
      android:minHeght="84dp"
      android:minWidth="84dp"
      android:updatePeriodMillis="86400000" >
</appwidget-provider>

③定义小部件的实现类

public class MyAppWidgetProvider extends AppWidgetProvider {
    private static final String CLICK_ACTION = "com.hj.action.click";
    @Override
    public void onReceive(final Context context, Intent intent) {
        super.onReceive(context, intent);
        if (intent.getAction().equals(CLICK_ACTION)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
 R.drawable.ic_launcher_v2);
                    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
                    for (int i = 0; i < 10; i++) {
                        float degree = (i * 10) % 360;
                        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
                        remoteViews.setImageViewBitmap(R.id.container, rotateBitmap(context, bitmap, degree));
                        Intent intent1 = new Intent(CLICK_ACTION);
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent1, 0);
                        remoteViews.setOnClickPendingIntent(R.id.container, pendingIntent);
                        appWidgetManager.updateAppWidget(new ComponentName(context, MyAppWidgetProvider.class), remoteViews);
                        SystemClock.sleep(30);
                    }
                }
            }).start();
        }
    }
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        int count = appWidgetIds.length;    for (int i = 0; i < count; i++) {
            int appWidgetId = appWidgetIds[i];
            onWidgetUpdate(context, appWidgetManager, appWidgetId);
        }
    }
    private void onWidgetUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
        Intent intent = new Intent();
        intent.setAction(CLICK_ACTION);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        remoteViews.setOnClickPendingIntent(R.id.container, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
    }
    private Bitmap rotateBitmap(Context context, Bitmap bitmap, float degree) {
        Matrix matrix = new Matrix();
        matrix.reset();
        matrix.setRotate(degree);
        Bitmap tmpBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), 
    bitmap.getHeight(), matrix, true);
        return tmpBitmap;
    }
}

④在AndroidManifest.xml声明小部件
桌面部件实际上是一个广播组件,必须要注册。APPWIDGET_UPDATE代表该广播是作为小部件的标识存在的

<receiver
      android:name=".MyAppWidgetProvider>
      <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/appwidget_provider_info">

       <intent-filter>
             <action android:name="com.hj.action.click"/>
             <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
       </intent-filter>
</receiver>
  • PendingIntent
    PendingIntent表示一种处于pending状态的意图,而pending状态表示的是一种待定、等待、即将发生的意思。PendingIntent支持三种待定意图:启动Activity、启动Service和发送广播。
    1.PendingIntent的Flag介绍
    FLAG_ONE_SHOT
    PendingIntent只能被使用一次,然后会自动cancel;如果后续还有相同的PendingIntent,那么他们的send方法就会调用失败
    FLAG_NO_CREATE
    PendingIntent不会主动创建,如果当前PendingIntent不存在,那么三种意图方法调用会直接返回null,获取PendingIntent会失败,它无法单独使用
    FLAG_CANCEL_CURRENT
    PendingIntent如果已经存在,那么它们都会被cancle,然后系统会创建一个新的PendingIntent。对于通知栏而言,那些被cancel的消息单击后无法打开
    FLAG_UPDATE_CURRENT
    PendingIntent如果已经存在,那么它们都会被更新

通知栏而言,notify(int, notification)方法中,若id值每次都不同的话,需要考虑到flag参数对应消息接收的情况

  • RemoteViews内部机制
    RemoteViews目前并不能支持所有的View的类型,不能支持自定义View、EditText等,同时没有提供findViewById方法,无法直接访问View元素。RemoteViews会通过Binder传递到SystemServer进程,系统会通过RemoteViews中包名等信息去得到该应用的资源并加载布局文件,当需要更新RemoteViews时,我们需要通过一系列set方法并通过NotificationManager和AppWidgetManager来提交更新任务,具体的更新操作也是在SystemServer进程中完成的。RemoteViews提供一个Action的概念,Action代表一个View操作,系统首先将View操作封装到Action对象并跨进程传输到远程进程,接着在远程进程中执行Action对象中的具体操作
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容