前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >探究RemoteViews的作用和原理

探究RemoteViews的作用和原理

作者头像
用户1269200
发布2018-10-08 16:09:25
1.4K0
发布2018-10-08 16:09:25
举报
文章被收录于专栏:刘望舒刘望舒

作者:猪_队友 https://www.jianshu.com/p/9bdf7c9efca5 本文已获得作者原创首发授权

什么是RemoteViews?
代码语言:javascript
复制
/**
 * A class that describes a view hierarchy that can be displayed in
 * another process. The hierarchy is inflated from a layout resource
 * file, and this class provides some basic operations for modifying
 * the content of the inflated hierarchy.
 */

翻译成自己的话就是:

RmoteViews是一个能显示在其他进程的视图。同样也提供了一些基本的操作方法来修改视图的内容。

从这段描述来看,我们感觉他和普通的View没有什么区别,只不过可以在远程进程中进行更新修改View。那么事实是不是这样呢?我们慢慢往下探究。

我们平时使用RemoteViews无非就两种:通知栏和桌面小部件。那我们就一个一个来探究一番。

通知栏

我们先写一个系统默认的通知栏:

代码语言:javascript
复制
  void sendNotify() {

        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this);

        builder.setTicker("通知:您有30亿要继承")
                .setContentTitle("西红柿首富")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentText("只有在3天时间花完3亿,才可以继承30亿,加油吧骚年")
                .setAutoCancel(true)
                .setWhen(SystemClock.currentThreadTimeMillis());


        //设置点击通知后执行的动作
        Intent intent = new Intent(this, DetailActivity.class);
        intent.putExtra("message", "只有在3天时间花完3亿,才可以继承30亿,加油吧骚年\n西红柿首富剧组通知你带薪入组\n时间:" + sdf.format(new Date()));
        //用当前时间充当通知的id,这里是为了区分不同的通知,如果是同一个id,前者就会被后者覆盖
        int requestId = (int) new Date().getTime();
        //第一个参数连接上下文的context ¬
        // 第二个参数是对PendingIntent的描述,请求值不同Intent就不同
        // 第三个参数是一个Intent对象,包含跳转目标
        // 第四个参数有4种状态
        PendingIntent pendingIntent = PendingIntent.getActivity(this, requestId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);

        //发出通知,参数是(通知栏的id,设置内容的对象)
        manager.notify(requestId, builder.build());


    }

下载进度条的代码:

代码语言:javascript
复制
  //模拟正在执行下载
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=1;i<=100;i++){
                    builder.setProgress(100, i, false);
                    if(i==100)
                        builder.setContentText("文件下载完毕!");
                    manager.notify(1, builder.build());
                    SystemClock.sleep(100);//模拟下载
                }
                manager.cancel(1);
            }
        }).start();

效果很直观,也很简单。

那我们需要自定义布局呢?默认的样式太丑,如何自定义布局呢?让我们的布局更丑的清新脱俗呢?

代码语言:javascript
复制
  RemoteViews views = new RemoteViews(getPackageName(),R.layout.notify_layout);
        views.setImageViewResource(R.id.img_1,R.drawable.rect_yellow);
        views.setImageViewResource(R.id.img_2,R.drawable.rect_white);
        views.setImageViewResource(R.id.img_3_1,R.drawable.rect_yellow);
        views.setImageViewResource(R.id.img_3_2,R.drawable.rect_white);
        views.setImageViewResource(R.id.img_3_3,R.drawable.rect_yellow);
        views.setTextViewText(R.id.text_context,"只有在3天时间花完3亿,才可以继承30亿,加油吧骚年");
        views.setTextColor(R.id.text_context,Color.YELLOW);
        views.setProgressBar(R.id.progerssbar,100,50,false);
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        final Notification.Builder builder = new Notification.Builder(this);

        builder.setContent(views)
                .setTicker("通知:您有30亿要继承")
                .setContentTitle("西红柿首富")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
             //   .setContentText("只有在3天时间花完3亿,才可以继承30亿,加油吧骚年")
                .setAutoCancel(true)
                .setWhen(System.currentTimeMillis());
 //设置点击通知后执行的动作
        Intent intent = new Intent(this, DetailActivity.class);
        intent.putExtra("message", "只有在3天时间花完3亿,才可以继承30亿,加油吧骚年\n西红柿首富剧组通知你带薪入组\n时间:" + sdf.format(new Date()));
        //用当前时间充当通知的id,这里是为了区分不同的通知,如果是同一个id,前者就会被后者覆盖
        int requestId = (int) new Date().getTime();
        //第一个参数连接上下文的context ¬
        // 第二个参数是对PendingIntent的描述,请求值不同Intent就不同
        // 第三个参数是一个Intent对象,包含跳转目标
        // 第四个参数有4种状态
        PendingIntent pendingIntent = PendingIntent.getActivity(this, requestId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);

        //发出通知,参数是(通知栏的id,设置内容的对象)
        manager.notify(requestId, builder.build());
代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_vertical">
    <ImageView
        android:id="@+id/img_1"
        android:layout_width="40dp"
        android:layout_height="40dp" />
    <ImageView
        android:id="@+id/img_2"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_toRightOf="@id/img_1" />

    <LinearLayout
        android:id="@+id/li_1"
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:layout_toRightOf="@id/img_2"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/img_3_1"
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_toRightOf="@id/img_1" />
        <ImageView
            android:id="@+id/img_3_2"
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_toRightOf="@id/img_1" />
        <ImageView
            android:id="@+id/img_3_3"
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_toRightOf="@id/img_1" />
    </LinearLayout>
    <TextView
        android:layout_below="@+id/progerssbar"
        android:layout_toRightOf="@id/img_2"
        android:id="@+id/text_context"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ProgressBar
        android:layout_below="@+id/li_1"
        android:layout_toRightOf="@+id/img_2"
        android:id="@+id/progerssbar"
        style="?android:progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

我们可以布局文件里设置TextView,ImageView,ProgressBar等等 一下是支持的view和layout ,其他的都不支持(自定义布局就不要想了)。至于原因和原理我们下面会探究。

桌面小部件

AppWidgetProvider 继承自 BroadcastReceiver,它能接收 widget 相关的广播,例如 widget 的更新、删除、开启和禁用等。

第一步:创建一个AppWidgetProvider

代码语言:javascript
复制
public class MyWidgetProvider extends AppWidgetProvider {
    // 点击事件的广播ACTION
    public static final String CLICK_ACTION = "com.ssy.mywidgettest.action.CLICK";

    public MyWidgetProvider() {
        super();
    }
    /**
     * 接收窗口小部件点击时发送的广播
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);

        if (CLICK_ACTION.equals(intent.getAction())) {
            Toast.makeText(context, "点击了天气", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);


        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
        Date day=new Date();

        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");

        remoteViews.setTextViewText(R.id.text_time, df.format(day));
        Intent intent = new Intent(CLICK_ACTION);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, R.id.rel_all, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.rel_all, pendingIntent);

        for (int appWidgetId : appWidgetIds) {
            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        }
    }
    /**
     * 当小部件大小改变时
     */
    @Override
    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
        super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
    }
    /**
     * 每删除一次窗口小部件就调用一次
     */
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
    }
    /**
     * 当该窗口小部件第一次添加到桌面时调用该方法
     */
    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
    }
    /**
     * 当最后一个该窗口小部件删除时调用该方法
     */
    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
    }
    /**
     * 当小部件从备份恢复时调用该方法
     */
    @Override
    public void onRestored(Context context, int[] oldWidgetIds, int[] newWidgetIds) {
        super.onRestored(context, oldWidgetIds, newWidgetIds);
    }
}

第二步:创建布局文件

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/rel_all"
    android:background="@color/colorWhite">
    <TextView
        android:id="@+id/text_temperature"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="37度"
        android:textSize="30dp" />
    <TextView
        android:id="@+id/text_addr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@+id/text_temperature"
        android:text="海淀区" />
    <TextView
        android:id="@+id/text_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_addr"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@+id/text_temperature" />
</RelativeLayout>

第三步:添加AppWidgetProviderInfo元数据

在res文件夹下新建xml文件夹创建一个xml文件(我的是my_widget_provider_info.xml 大家可以根据实际需求取名字)

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/widget_layout"
    android:minHeight="110dp"
    android:minWidth="100dp"
    android:widgetCategory="home_screen"
    android:previewImage="@drawable/rect_yellow"
    android:updatePeriodMillis="86400000"
    >
</appwidget-provider>

第四步:声明AppWidgetProvider

代码语言:javascript
复制
  <receiver android:name=".MyWidgetProvider">
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/my_widget_provider_info">
            </meta-data>
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="com.ssy.mywidgettest.action.CLICK" />
            </intent-filter>

        </receiver>

第五步:运行并添加到屏幕上 长摁主屏幕,会出现添加工具,点击进去 添加我们自己的小部件到屏幕上。

小部件的制作还有很多细节需要处理大家可以看这个文档。https://developer.android.com/guide/topics/appwidgets/?hl=zh-cn

分析阶段

我们自己动手创建了通知和小部件。我们会发现RemoteView因为运行在远程进程中,无法通过设置监听去处理事件,而是依赖PendingIntent添加点击事件。

我们可以看到RemoteView会用PendingIntent进行传输信息。pendingIntent是一种特殊的Intent。 主要的区别在于: Intent的执行立刻的,而pendingIntent的执行不是立刻的。 Intent 是及时启动,intent 随所在的activity 消失而消失。

PendingIntent 可以看作是对intent的包装,通常通过getActivity,getBroadcast ,getService来得到pendingintent的实例,当前activity并不能马上启动它所包含的intent,而是在外部执行 pendingintent时,调用intent的。正由于pendingintent中 保存有当前App的Context,使它赋予外部App一种能力,使得外部App可以如同当前App一样的执行pendingintent里的 Intent, 就算在执行时当前App已经不存在了,也能通过存在pendingintent里的Context照样执行Intent。另外还可以处理intent执行后的操作。常和alermanger 和notificationmanager一起使用。 Intent一般是用作Activity、Sercvice、BroadcastReceiver之间传递数据,而Pendingintent,一般用在 Notification上,可以理解为延迟执行的intent,PendingIntent是对Intent一个包装。

探究RemoteView内部机制

RemoteView主要用于通知栏和桌面小部件中,而他们分别由NotificationManager和AppWidgetManager所管理,NotificationManager和AppWidgetManager通过Binder分别和SystemServer中的NotificationManagerService和AppWidgetService进行通信。所以通知栏和小部件的布局文件都是在NotificationManagerService和AppWidgetService中加载的,运行在SystemService中,所以这就造成了跨进程通信。

RemoteView通过Binder传递到SystemService进程中,因为RemoteView实现了Parcelable接口所以是可以跨进程传输的。系统会根据RemoteView中的包名和布局文件id得到应用程序的资源。然后通过LayoutInflater去加载RemoteView的布局,然后这个View会调用我们设置的各种set方法。注意这些set方法不是马上生效的而是记录在RemoteView中,具体实行实现需要等到RemoteView加载后下可以执行。当部件需要更新的时候我们也会调用各种set方法并通过NotificationManager和AppWidgetManager来提交更新任务。具体的更新操作发生在SystemService进程之中的。

那么RemoteView的这些set方法究竟是怎么实现的呢?我们通过源码来探究一番。

我们以setTextViewText()方法为例。

代码语言:javascript
复制
//我们传入viewId和text  
 public void setTextViewText(int viewId, CharSequence text) {
        setCharSequence(viewId, "setText", text);
    }
------------>>
//我们发现addAction方法,有点意思 ,接着往下看
 public void setCharSequence(int viewId, String methodName, CharSequence value) {
//把一个反射 Action添加到·· (暂时不知道添加到哪里)
//这个反射
        addAction(new ReflectionAction(viewId, methodName, ReflectionAction.CHAR_SEQUENCE, value));
    }
---------->>
//原来mActions是个ArrayList
private ArrayList<Action> mActions;

    /**
     * Add an action to be executed on the remote side when apply is called.
     *当远程apply被调用,那么添加的这个Action会被执行
     * @param a The action to add
     */
    private void addAction(Action a) {
        if (hasLandscapeAndPortraitLayouts()) {
            throw new RuntimeException("RemoteViews specifying separate landscape and portrait" +
                    " layouts cannot be modified. Instead, fully configure the landscape and" +
                    " portrait layouts individually before constructing the combined layout.");
        }
        if (mActions == null) {
            mActions = new ArrayList<Action>();
        }
        mActions.add(a);

        // update the memory usage stats
        a.updateMemoryUsageEstimate(mMemoryUsageCounter);
    }

从这里大概可以猜出来,把这些反射Action添加到ArrayList中只是保存作用,等待着apply的调用。那我们就看一下RemoteView的apply方法。

代码语言:javascript
复制
public View apply(Context context, ViewGroup parent) {
        return apply(context, parent, null);
    }
--------->
   /** @hide */
    public View apply(Context context, ViewGroup parent, OnClickHandler handler) {
        RemoteViews rvToApply = getRemoteViewsToApply(context);

        View result = inflateView(context, rvToApply, parent);
        loadTransitionOverride(context, handler);

        rvToApply.performApply(result, parent, handler);

        return result;
    }
--------->
 private View inflateView(Context context, RemoteViews rv, ViewGroup parent) {
        // RemoteViews may be built by an application installed in another
        // user. So build a context that loads resources from that user but
        // still returns the current users userId so settings like data / time formats
        // are loaded without requiring cross user persmissions.
        final Context contextForResources = getContextForResources(context);
        Context inflationContext = new RemoteViewsContextWrapper(context, contextForResources);

        LayoutInflater inflater = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        // Clone inflater so we load resources from correct context and
        // we don't add a filter to the static version returned by getSystemService.
        inflater = inflater.cloneInContext(inflationContext);
        inflater.setFilter(this);
        View v = inflater.inflate(rv.getLayoutId(), parent, false);
        v.setTagInternal(R.id.widget_frame, rv.getLayoutId());
        return v;
    }
------->
  private void performApply(View v, ViewGroup parent, OnClickHandler handler) {
        if (mActions != null) {
            handler = handler == null ? DEFAULT_ON_CLICK_HANDLER : handler;
            final int count = mActions.size();
            for (int i = 0; i < count; i++) {
                Action a = mActions.get(i);
                a.apply(v, parent, handler);
            }
        }
    }

我们再回头看一下ReflectionAction里的apply方法。其实就是反射调用。

代码语言:javascript
复制
    @Override
        public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
            final View view = root.findViewById(viewId);
            if (view == null) return;

            Class<?> param = getParameterType();
            if (param == null) {
                throw new ActionException("bad type: " + this.type);
            }

            try {
                getMethod(view, this.methodName, param).invoke(view, wrapArg(this.value));
            } catch (ActionException e) {
                throw e;
            } catch (Exception ex) {
                throw new ActionException(ex);
            }
        }

我们可以看到inflateView方法去加载RemoteViews布局,这个方法的原理相信大家应该都很熟悉了,平时也经常用到。 performApply方法会遍历mActions列表并执行里面的apply方法(注意两个apply是不同的),我们的各种set方法只是添加进mActions列表,真正操作View的是apply()方法。 所以我们捋一下这个逻辑。 1、调用RemoteViews的各种set方法的时候,并不会立马更新他们的界面。 2、必须通过NotificationManager的notify方法或者AppWidgetManager的updateAppWidget方法才能更新他们的界面。 3、内部实现上是RemoteView的apply或者reapply方法更新界面。 apply和reapply的区别在于apply加载并更新。reapply只是更新。 4、RemoteView的apply方法通过inflateView方法加载RemoteViews布局。 5、接着RemoteViews调用performApply方法,遍历mActions,调用ReflectionAction里的apply方法,通过反射达到我们想要的操作。

实现自己的Notification

第一步:先建一个NotificationActivity充当通知栏

代码语言:javascript
复制
public class NotificationActivity extends Activity {
    LinearLayout li_1;
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);
        li_1 = findViewById(R.id.li_1);
        btn = findViewById(R.id.btn);
        IntentFilter intentFilter = new IntentFilter("com.ssy.myintnent.action");
        registerReceiver(mRemoteViewReceiver,intentFilter);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NotificationActivity.this,MainActivity.class);
                startActivity(intent);
            }
        });
    }

    private BroadcastReceiver mRemoteViewReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          //  Toast.makeText(context, "+++++++", Toast.LENGTH_SHORT).show();
            Log.e("mytag","--");
            RemoteViews remoteViews = intent.getParcelableExtra("com.ssy.myintnent.remoteview");

            if(remoteViews!=null){

                int layout_id = getResources().getIdentifier("notify_layout","layout",getPackageName());
                View view = getLayoutInflater().inflate(layout_id,li_1,false);
                remoteViews.reapply(context,view);
              //  View view = remoteViews.apply(NotificationActivity.this,li_1);
                li_1.addView(view);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mRemoteViewReceiver);
    }
}

第二步:设置成其他进程

代码语言:javascript
复制
   <activity android:name=".NotificationActivity"
            android:process=":other"></activity>

第三步:在MainActivity发送信息

代码语言:javascript
复制
 void sendMyNotify() {

        RemoteViews views = new RemoteViews(getPackageName(), R.layout.notify_layout);
        views.setImageViewResource(R.id.img_1, R.drawable.rect_yellow);
        views.setImageViewResource(R.id.img_2, R.drawable.rect_white);
        views.setImageViewResource(R.id.img_3_1, R.drawable.rect_yellow);
        views.setImageViewResource(R.id.img_3_2, R.drawable.rect_white);
        views.setImageViewResource(R.id.img_3_3, R.drawable.rect_yellow);
        views.setTextViewText(R.id.text_context, "my progress:" + Process.myPid());
        views.setTextColor(R.id.text_context, Color.RED);
        views.setProgressBar(R.id.progerssbar, 100, 50, false);

        int requestId = (int) new Date().getTime();
        PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, requestId,
                new Intent(MainActivity.this, NotificationActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        views.setOnClickPendingIntent(R.id.text_context, pendingIntent);
        Intent intent = new Intent("com.ssy.myintnent.action");
        intent.putExtra("com.ssy.myintnent.remoteview", views);
        sendBroadcast(intent);
        Toast.makeText(this, "--", Toast.LENGTH_SHORT).show();

    }

第四步:运行

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-08-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 刘望舒 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 什么是RemoteViews?
  • 通知栏
  • 桌面小部件
  • 分析阶段
  • 探究RemoteView内部机制
  • 实现自己的Notification
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档