RemoteViews内部机制

1.RemoteViews 支持的view 类型,不支持他们的子类及其他类型,

  • Layout : FrameLayout,LinearLayout,RelativeLayout,GridLayout
  • View: AnalogClock,Button,Chronometer,ImageButton,Imageview,ProgressBar,TextView,ViewFlipper,ListView,GridView,StackView,AdapterViewFlipper,ViewStub,
  • RemoteViews 主要用于通知栏和桌面小部件.分别由NotificationManager 和AppWidgetManager 管理,通过Binder分别和SystemServer进程中的NotificationManagerService和 AppWidgetManagerService进行跨进程通信.所以需要通过一些列set方法来给RemoteViews设置属性,然后在SystemServer进程中更近view.
  • 系统提供一个Action 类,实现了 Parcelable接口,用来表示一个对view的更新操作.Action对象通过Binder夸进程传输到SystemServer 远程进程. 远程进程通过调用RemoteViews 的appply方法更新view,apply方法内部会遍历所有Action并调用Action内部的apply方法来具体更新view.具体的更新方法是在Action内部的apply内部实现.
  • 进行代码追踪
//RemoteViews  
/通过set...方法来更新view属性
public void setTextViewText(int viewId, CharSequence text) {
      setCharSequence(viewId, "setText", text);  //view的id,设置的属性,设置的内容
  }
public void setCharSequence(int viewId, String methodName, CharSequence value) {
    //添加了一个 RefelctionAction对象 这是一个Action 的子类,先接着看
    addAction(new ReflectionAction(viewId, methodName, ReflectionAction.CHAR_SEQUENCE, value));
}   
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(); //用一个集合保存所有的对view的操作Action
    }
    mActions.add(a);

    // update the memory usage stats
    a.updateMemoryUsageEstimate(mMemoryUsageCounter);
} 
//到此时,只是把一个对view的操作添加到 RemoteViews 的 mActions集合中,接下来在看ReflectionAction前,还需要看下 RemoteViews 的apply方法.


    /** @hide */
public View apply(Context context, ViewGroup parent, OnClickHandler handler) {
    RemoteViews rvToApply = getRemoteViewsToApply(context); //得到需要更新属性的RemoteViews

    View result = inflateView(context, rvToApply, parent);//重点1 .rvToApply 代表RemoteViews,这里是加载我们为RemoteViews设置的layout布局

    loadTransitionOverride(context, handler); 
    rvToApply.performApply(result, parent, handler); //重点2
    return result;
}
//重点1
 private View inflateView(Context context, RemoteViews rv, ViewGroup parent) {
  ...
    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); //加载了RemoteViews的布局文件进来
    v.setTagInternal(R.id.widget_frame, rv.getLayoutId());
    return v;
}
 //重点2
 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内部的apply方法
            Action a = mActions.get(i);
            a.apply(v, parent, handler);
        }
    }
}
  • 之后.当我们调用RemoteViews.set 方法时,不会立即更新view.而必须通过NotificationManager.noitefy 或AppWidgetManager.upodateAppWidget方法,在内部通过SystemServer夸进程调用RemoteViews的apply和reapply方法.apply在初始化时调用,reapply方法在每次更新时调用,二者内部都是调用 performApply()进而调用Action的apply方法.
  • 接下来看ReflectionAction 的实现
 //ReflectionAction 继承 Action
//参数: viewId, 设置的属性名,操作类型,操作的值
ReflectionAction(int viewId, String methodName, int type, Object value) {
        this.viewId = viewId;
        this.methodName = methodName;
        this.type = type;
        this.value = value;
    }
     @Override root使我们自己设定的layout,rootParent是RemoteViews
    public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
        final View view = root.findViewById(viewId); //找到要更新的view
        if (view == null) return;

        Class param = getParameterType(); //返回参数类型 int .long.bitmap.intent 等等
        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);
        }
    }
   private Method getMethod(View view, String methodName, Class paramType) {
      Method method;
      Class klass = view.getClass();

      synchronized (sMethodsLock) {
        ArrayMap>, Method> methods = sMethods.get(klass); 
     //这个sMethods 是一个key为 View类的class.  value为 ArrayMap,.Method>的map,
他的value也是map,key是方法名和形参类型的map,值是方法
        if (methods == null) {
            methods = new ArrayMap>, Method>();
            sMethods.put(klass, methods);
        }
        //MutablePair 类, 由方法名和参数的class类构成
        mPair.first = methodName;
        mPair.second = paramType;

        method = methods.get(mPair);//找到最重要反射执行的方法.
        if (method == null) {
            try {
                if (paramType == null) {  // 反射得到对应方法.区别在于是否有参数
                    method = klass.getMethod(methodName);
                } else {
                    method = klass.getMethod(methodName, paramType);
                }
            } catch (NoSuchMethodException ex) {
                throw new ActionException("view: " + klass.getName() + " doesn't have method: "
                        + methodName + getParameters(paramType));
            }

            if (!method.isAnnotationPresent(RemotableViewMethod.class)) {
                throw new ActionException("view: " + klass.getName()
                        + " can't use method with RemoteViews: "
                        + methodName + getParameters(paramType));
            }
            //保存方法
            methods.put(new MutablePair>(methodName, paramType), method);
        }
    }
    //返回得到的方法.
    return method;
}
  • 到此就结束了.当然,对于RemoteViews调用不同的set方法,添加的Action也是不同的.

你可能感兴趣的:(RemoteViews内部机制)