Android UI之跨進(jìn)程組件RemoteViews


本文基于android-27編譯并進(jìn)行源碼分析


一、概述

什么是RemoteViews?

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.

RemoteViews這個類用于跨進(jìn)程展示一個View結(jié)構(gòu),構(gòu)造時需要制定一個layout資源文件,用于解析生成View;并提供了更新View內(nèi)容的一些基本操作。

其和遠(yuǎn)程Service很像,由源進(jìn)程提供layout資源,RemoteViews可以跨進(jìn)程顯示,并且可以利用提供的基本操作來遠(yuǎn)程更新界面。其常見的用途有兩種:通知欄和桌面小部件。

二、應(yīng)用

2.1 通知欄

使用系統(tǒng)默認(rèn)樣式彈出一個通知欄是很簡單的,但是如果有通知欄自定義布局的需求,RemoteViews就派上用場了:

Notification notification =new Notification();
notification.icon = R.mipmap.ic_launcher;
notification.tickerText ="hello notification";
notification.when = System.currentTimeMillis();
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent =new Intent(this, RemoteViewsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoteViews =new RemoteViews(getPackageName(), R.layout.layout_notification);//RemoveViews所加載的布局文件
remoteViews.setTextViewText(R.id.tv, "這是一個Test");//設(shè)置文本內(nèi)容
remoteViews.setTextColor(R.id.tv, Color.parseColor("#abcdef"));//設(shè)置文本顏色
remoteViews.setImageViewResource(R.id.iv, R.mipmap.ic_launcher);//設(shè)置圖片
PendingIntent openActivity2Pending = PendingIntent.getActivity (this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);//設(shè)置RemoveViews點擊后啟動界面
remoteViews.setOnClickPendingIntent(R.id.tv, openActivity2Pending);
notification.contentView = remoteViews;
notification.contentIntent = pendingIntent;
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(2, notification);

2.2 桌面小部件

共分為四步:準(zhǔn)備要顯式的布局文件、定義小部件配置信息、自定義AppWidgetProvider的實現(xiàn)類、在AndroidManifest.xml中聲明。
res/layout下的widget.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_desk"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"/>

</LinearLayout>

res/xml目錄下的配置:

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

MyAppWidgetProvider.java

public class MyAppWidgetProvider extends AppWidgetProvider {
    private static final String TAG = "MyAppWidgetProvider";
    private static final String CLICK_ACTION = "com.satellite.remoteviews";

    public MyAppWidgetProvider(){
        super();
    }

    @Override
    public void onReceive(final Context context, Intent intent) {
        super.onReceive(context,intent);
        Log.i(TAG,"onReceive : action = "+intent.getAction());
        if(intent.getAction().equals(CLICK_ACTION)){
            Toast.makeText(context,"click it",Toast.LENGTH_SHORT).show();
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    // 更新view
                    ......
                }
            }.start();
        }
    }
    
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        Log.i(TAG,"onUpdate");
        final int counter = appWidgetIds.length;
        Log.i(TAG,"counter = " + counter);
        for(int i=0;i<counter;i++){
            int appWidgetId = appWidgetIds[i];
            onWidgetUpdate(context,appWidgetManager,appWidgetId);
        }
    }

    private void onWidgetUpdate(Context context,AppWidgetManager appWidgetManager,int appWidgetId){
        Log.i(TAG,"appWidgetId = "+appWidgetId);
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget);
        Intent intentClick = new Intent();
        intentClick.setAction(CLICK_ACTION);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0,intentClick,0);
        remoteViews.setOnClickPendingIntent(R.id.iv_desk,pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetId,remoteViews);
    }
}

AndroidManifest中注冊(注意兩個Action):

<receiver android:name=".MyAppWidgetProvider">
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/appwidget_provider_info" />
            <intent-filter>
                <!--自定義的action用于響應(yīng)點擊AppWidget-->
                <action android:name="com.satellite.remoteviews" />
                <!--必須要顯示聲明的action!因為所有的widget的廣播都是通過它來發(fā)送的;要接收widget的添加、刪除等廣播,就必須包含它-->
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
        </receiver>

要注意,AppWidgetProvider的父類是BroadcastReceiver,其本質(zhì)就是一個廣播接收器,廣播到來的時候,AppWidgetProvider會自動根據(jù)廣播的Action通過onReceive方法來分發(fā)廣播,內(nèi)部方法如下:
onEnable: 當(dāng)該窗口小部件第一次添加到桌面時調(diào)用的方法,可添加多次但只在第一次調(diào)用。
onUpdate: 小部件被添加時或者每次小部件更新時都會調(diào)用一次該方法,小部件的更新時機是有updatePeriodMillis來指定,每個周期小部件就會自動更新一次。
onDeleted: 每刪除一次桌面小部件就調(diào)用一次。
onDisabled: 當(dāng)最后一個該類型的小部件被刪除時調(diào)用該方法。
onReceive: 這是廣播的內(nèi)置方法,用于分發(fā)具體事件給其他方法。

三、原理分析

3.1 問題

1、RemoteViews為什么可以通過一次IPC實現(xiàn)對多個View的操作。
2、其他進(jìn)程怎么獲取布局文件。

3.2 具體分析

3.2.1 PendingIntent

上面的通知欄消息和桌面小部件,都用到了PendingIntent。
PendingIntent表示一種處于pending(待定、等待、即將發(fā)生)狀態(tài)的意圖;PendingIntent通過send和cancel方法來發(fā)送和取消特定的待定Intent。
PendingIntent支持三種待定意圖:啟動Activity、啟動Service和發(fā)送廣播。分別對應(yīng):

getActivity / getService / getBroadcast
參數(shù)相同,都為:(Context context, int requestCode, Intent intent, int flags)

其中第二個參數(shù),requestCode表示PendingIntent發(fā)送方的請求碼,多少情況下為0即可,requestCode會影響到flags的效果。
PendingIntent的匹配規(guī)則是:如果兩個PendingIntent他們內(nèi)部的Intent相同并且requestCode也相同,那么這兩個PendingIntent就是相同的。那么什么情況下Intent相同呢?Intent的匹配規(guī)則是,如果兩個Intent的ComponentName和intent-filter都相同;那么這兩個Intent也是相同的。

flags參數(shù)的含義:
FLAG_ONE_SHOT 當(dāng)前的PendingIntent只能被使用一次,然后他就會自動cancel,如果后續(xù)還有相同的PendingIntent,那么它們的send方法就會調(diào)用失敗。
FLAG_NO_CREATE 當(dāng)前描述的PendingIntent不會主動創(chuàng)建,如果當(dāng)前PendingIntent之前存在,那么getActivity、getService和getBroadcast方法會直接返回Null,即獲取PendingIntent失敗,無法單獨使用,平時很少用到。
FLAG_CANCEL_CURRENT 當(dāng)前描述的PendingIntent如果已經(jīng)存在,那么它們都會被cancel,然后系統(tǒng)會創(chuàng)建一個新的PendingIntent。對于通知欄消息來說,那些被cancel的消息單擊后無法打開。
FLAG_UPDATE_CURRENT 當(dāng)前描述的PendingIntent如果已經(jīng)存在,那么它們都會被更新,即它們的Intent中的Extras會被替換為最新的。

manager.notify(2, notification);
// 結(jié)合通知欄功能說明一下,多次調(diào)用notify()后如果PendingIntent匹配時即Intent和requestCode相同:
// 1、FLAG_ONE_SHOT:點擊任何一條通知,剩余的通知都無法打開,所有通知被清除后,再次循環(huán)這個過程;
// 2、FLAG_CANCEL_CURRENT:只有最新的通知可以打開,之前的通知都無法打開;
// 3、FLAG_UPDATE_CURRENT:之前彈出的通知中的PendingIntent會更新,和最新通知保持一致,并且所有的通知都可以打開。
3.2.2 RemoteViews

接下來結(jié)合上面的代碼來分析RemoteViews的工作原理:
1、當(dāng)用戶將AppWidget拖到桌面上時,MyAppWidgetProvider繼承AppWidgetProvider原有的onReceive方法,回調(diào)其onUpdate方法

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

2、在onWidgetUpdate方法中建立RemoteViews,之后調(diào)用appWidgetManager的updateAppWidget發(fā)起IPC。

private void onWidgetUpdate(Context context,AppWidgetManager appWidgetManager,int appWidgetId){
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget);
        Intent intentClick = new Intent();
        intentClick.setAction(CLICK_ACTION);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0,intentClick,0);
        remoteViews.setOnClickPendingIntent(R.id.iv_desk,pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetId,remoteViews);
    }

3、這里實例化了RemoteViews,倆參數(shù)分別是包名和布局資源id

/**
     * Create a new RemoteViews object that will display the views contained
     * in the specified layout file.
     *
     * @param packageName Name of the package that contains the layout resource
     * @param layoutId The id of the layout resource
     */
    public RemoteViews(String packageName, int layoutId) {
        this(getApplicationInfo(packageName, UserHandle.myUserId()), layoutId);
    }

/**
     * Create a new RemoteViews object that will display the views contained
     * in the specified layout file.
     *
     * @param application The application whose content is shown by the views.
     * @param layoutId The id of the layout resource.
     *
     * @hide
     */
    protected RemoteViews(ApplicationInfo application, int layoutId) {
        mApplication = application;
        mLayoutId = layoutId;
        mBitmapCache = new BitmapCache();
        // setup the memory usage statistics
        mMemoryUsageCounter = new MemoryUsageCounter();
        recalculateMemoryUsage();
    }

4、之后RemoteViews調(diào)用了setOnClickPendingIntent方法。

remoteViews.setOnClickPendingIntent(R.id.iv_desk,pendingIntent);
// RemoteViews源碼
public void setOnClickPendingIntent(int viewId, PendingIntent pendingIntent) {
        addAction(new SetOnClickPendingIntent(viewId, pendingIntent));
    }

/**
     * Add an action to be executed on the remote side when apply is called.
     * 譯:當(dāng)apply()方法被調(diào)用時,添加的action會在遠(yuǎn)程被執(zhí)行。
     * @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);
    }

setOnClickPendingIntent方法在內(nèi)部利用viewId, pendingIntent生成SetOnClickPendingIntent對象,并將此對象作為參數(shù)傳入addAction中,而SetOnClickPendingIntent和Action是繼承的關(guān)系,是Action的子類。先看addAction的具體邏輯,發(fā)現(xiàn)addAction中將傳入的參數(shù)添加至RemoteViews的成員變量mActions中,并且未來會在遠(yuǎn)程調(diào)用Action的apply方法來執(zhí)行Action,下面來看Action類的信息。
5、Action

/**
     * Base class for all actions that can be performed on an
     * inflated view.
     *
     *  SUBCLASSES MUST BE IMMUTABLE SO CLONE WORKS!!!!!
     */
    private abstract static class Action implements Parcelable {
        public abstract void apply(View root, ViewGroup rootParent,
                OnClickHandler handler) throws ActionException;
        public abstract String getActionName();
        ......
}

Action類為一個抽象類,同時實現(xiàn)了Parcelable接口,支持IPC。最關(guān)鍵的一個抽象方法apply。再看其實現(xiàn)click的子類SetOnClickPendingIntent :

 /**
     * Equivalent to calling(等同于調(diào)用View#setOnClickListener)
     * {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)}
     * to launch the provided {@link PendingIntent}.
     */
    private class SetOnClickPendingIntent extends Action {
        public SetOnClickPendingIntent(int id, PendingIntent pendingIntent) {
            this.viewId = id;
            this.pendingIntent = pendingIntent;
        }
        .....
        @Override
        public void apply(View root, ViewGroup rootParent, final OnClickHandler handler) {
            final View target = root.findViewById(viewId);
            if (target == null) return;
            ......
            // If the pendingIntent is null, we clear the onClickListener
            OnClickListener listener = null;
            if (pendingIntent != null) {
                listener = new OnClickListener() {
                    public void onClick(View v) {
                        // Find target view location in screen coordinates and
                        // fill into PendingIntent before sending.
                        final Rect rect = getSourceBounds(v);

                        final Intent intent = new Intent();
                        intent.setSourceBounds(rect);
                        handler.onClickHandler(v, pendingIntent, intent);
                    }
                };
            }
            target.setOnClickListener(listener);
        }

        public String getActionName() {
            return "SetOnClickPendingIntent";
        }

        PendingIntent pendingIntent;
    }

RemoteViews的setOnClickPendingIntent方法可以這么理解:將添加監(jiān)聽的一個View動作,封裝成一個Action類,保存在RemoteViews的mActions中。其實查看RemoteViews的每一個set方法,不難發(fā)現(xiàn)都是把對View操作的動作封裝成Action類,最終保存在RemoteViews的mActions中。這個過程可以理解為:


RemoteViews的每一個set方法.png

到目前為止發(fā)現(xiàn)RemoteViews更多承擔(dān)的是信息的一個載體,這些信息包括:要顯示View的資源ID值、mActions等等。


上面介紹了RemoteViews如何通過Action來封裝和組合View的多個操作,下面開始介紹如何執(zhí)行這些Action的即如何遠(yuǎn)程加載布局并執(zhí)行更新操作。


6、appWidgetManager.updateAppWidget
上面無論是onWidgetUpdate還是onReceive中收到CLICK_ACTION時,最后都調(diào)用了:

appWidgetManager.updateAppWidget(appWidgetId,remoteViews);

我們來看看里面的流程:

private final IAppWidgetService mService;
public void updateAppWidget(int appWidgetId, RemoteViews views) {
        if (mService == null) {
            return;
        }
        updateAppWidget(new int[] { appWidgetId }, views);
    }

public void updateAppWidget(int[] appWidgetIds, RemoteViews views) {
        if (mService == null) {
            return;
        }
        try {
            mService.updateAppWidgetIds(mPackageName, appWidgetIds, views);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

看到了RemoteException猜測這里就開始了遠(yuǎn)程服務(wù)的調(diào)用,而這個遠(yuǎn)程服務(wù)對象mService的類型是 IAppWidgetService。之后由AppWidgetService發(fā)送消息,AppWidgetHost監(jiān)聽來自AppWidgetService的事件(鏈接:AppWidget的詳細(xì)流程),AppWidgetHost收到AppWidgetService發(fā)送的消息,創(chuàng)建AppWidgetHostView,然后通過AppWidgetService查詢appWidgetId對應(yīng)的RemoteViews,最后把RemoteViews傳遞給AppWidgetHostView去updateAppWidget。
AppWidgetHost的內(nèi)部流程:

// AppWidgetHost源碼
 /**
     * Create the AppWidgetHostView for the given widget.
     * The AppWidgetHost retains a pointer to the newly-created View.
     */
    public final AppWidgetHostView createView(Context context, int appWidgetId,
            AppWidgetProviderInfo appWidget) {
        if (sService == null) {
            return null;
        }
        AppWidgetHostView view = onCreateView(context, appWidgetId, appWidget);
        view.setOnClickHandler(mOnClickHandler);
        view.setAppWidget(appWidgetId, appWidget);
        synchronized (mViews) {
            mViews.put(appWidgetId, view);
        }
        RemoteViews views;
        try { // 通過AppWidgetService查詢appWidgetId對應(yīng)的RemoteViews
            views = sService.getAppWidgetViews(mContextOpPackageName, appWidgetId);
        } catch (RemoteException e) {
            throw new RuntimeException("system server dead?", e);
        }
// 最后把RemoteViews傳遞給AppWidgetHostView去updateAppWidget。
        view.updateAppWidget(views);

        return view;
    }

7、AppWidgetHostView.updateAppWidget()
注意:1、layoutId出場了;
2、remoteViews的apply和reapply在調(diào)用中第二個參數(shù)的不同

public void updateAppWidget(RemoteViews remoteViews) {
        applyRemoteViews(remoteViews, true);
    }

protected void applyRemoteViews(RemoteViews remoteViews, boolean useAsyncIfPossible) {
        ......
        if (remoteViews == null) {
           ......
        } else {
           ......
            // Prepare a local reference to the remote Context so we're ready to
            // inflate any requested LayoutParams.
            mRemoteContext = getRemoteContext();
            int layoutId = remoteViews.getLayoutId();

            // If our stale view has been prepared to match active, and the new
            // layout matches, try recycling it(已經(jīng)加載過了直接復(fù)用)
            if (content == null && layoutId == mLayoutId) {
                try { // reapply的第二個參數(shù)是layoutId的布局
                    remoteViews.reapply(mContext, mView, mOnClickHandler);
                    content = mView;
                    recycled = true;
                    if (LOGD) Log.d(TAG, "was able to recycle existing layout");
                } catch (RuntimeException e) {
                    exception = e;
                }
            }

            // Try normal RemoteView inflation(layoutId不匹配,重新加載布局)
            if (content == null) {
                try { // apply的第二個參數(shù)是AppWidgetHostView
                    content = remoteViews.apply(mContext, this, mOnClickHandler);
                    if (LOGD) Log.d(TAG, "had to inflate new layout");
                } catch (RuntimeException e) {
                    exception = e;
                }
            }

            mLayoutId = layoutId;
            mViewMode = VIEW_MODE_CONTENT;
        }

        applyContent(content, recycled, exception);
        updateContentDescription(mInfo);
    }

AppWidgetHostView.updateAppWidget()的實現(xiàn)邏輯很好理解(當(dāng)然這里只是保留了主要的邏輯代碼),通過匹配layoutId ,如果沒有加載過,remoteViews的布局則調(diào)用remoteViews.apply方法,若加載過了則調(diào)用remoteViews.reapply方法
其實這個時候所有的操作已經(jīng)處于systemServer進(jìn)程中了,最后看一下remoteViews的apply和reapply方法。
8、remoteViews的apply和reapply(注意倆方法第二個參數(shù)的不同)
apply比reapply多一步inflate的過程,只分析apply:

 public View apply(Context context, ViewGroup parent) {
        return apply(context, parent, null);
    }
 // apply流程如下: 
   // 1、通過RemoteViews的getLayoutId方法獲取要顯示的資源ID值
   // 2、利用LayoutInflater加載要加載的xml文件,生成View。
   // 3、調(diào)用RemoteViews的performApply方法。
 public View apply(Context context, ViewGroup parent, OnClickHandler handler) {
        RemoteViews rvToApply = getRemoteViewsToApply(context);
// 1、通過RemoteViews的getLayoutId方法獲取要顯示的資源ID值
   // 2、利用LayoutInflater加載要加載的xml文件,生成View。
        View result = inflateView(context, rvToApply, parent);
        loadTransitionOverride(context, handler);
// 3、調(diào)用RemoteViews的performApply方法。
        rvToApply.performApply(result, parent, handler);

        return result;
    }

    private View inflateView(Context context, RemoteViews rv, ViewGroup parent) {
        // ......
        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;
    }

    // 將前面存入mActions中的Action遍歷取出來,并調(diào)用action的apply方法
    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);
            }
        }
    }

9、action的apply方法
performApply()中取出所有的Action并調(diào)用其apply()方法,回過頭分析SetOnClickPendingIntent的apply,分三步來分析:

 // 1、通過viewId獲取對應(yīng)的view
 // 2、如果pendingIntent不為空,為target生成OnClickListener
 // 3、target綁定監(jiān)聽
 @Override
        public void apply(View root, ViewGroup rootParent, final OnClickHandler handler) {
            // 1、通過viewId獲取對應(yīng)的view
            final View target = root.findViewById(viewId);
            if (target == null) return;
            ......
            // If the pendingIntent is null, we clear the onClickListener
            OnClickListener listener = null;
            // 2、如果pendingIntent不為空,為target生成OnClickListener
            if (pendingIntent != null) {
                listener = new OnClickListener() {
                    public void onClick(View v) {
                        // Find target view location in screen coordinates and
                        // fill into PendingIntent before sending.
                        final Rect rect = getSourceBounds(v);

                        final Intent intent = new Intent();
                        intent.setSourceBounds(rect);
                        handler.onClickHandler(v, pendingIntent, intent);
                    }
                };
            }
           // 3、target綁定監(jiān)聽
           target.setOnClickListener(listener);

這樣便完成了View的setOnClickListener
這里就分析了一個相對簡單的Action——SetOnClickPendingIntent,其他的Action邏輯也是相同的,有的會使用反射技術(shù)來修改View的某些屬性。

3.2.3 小結(jié)

至于3.1開頭提出的倆問題,應(yīng)該已經(jīng)有明確的答案了,這里不再贅述
1、RemoveViews并不能支持所有View類型,支持以下:
Layout:FrameLayout、LinearLayout、RelativeLayout、GridLayout。
View:Button、ImageButton、ImageView、ProgressBar、TextView、ListView、GridView、ViewStub等(例如EditText是不允許在RemoveViews中使用的,使用會拋異常)。
2、RemoteView沒有findViewById方法,因此無法訪問里面的View元素,而必須通過RemoteViews所提供的一系列set方法來完成,這是通過反射調(diào)用的。
3、通知欄和小組件分別由NotificationManager(NM)和AppWidgetManager(AWM)管理,而NM和AWM通過Binder分別和SystemService進(jìn)程中的NotificationManagerService以及AppWidgetService中加載的,而它們運行在系統(tǒng)的SystemService中,這就和我們進(jìn)程構(gòu)成了跨進(jìn)程通訊。
4、工作流程:首先RemoteViews會通過Binder傳遞到SystemService進(jìn)程,因為RemoteViews實現(xiàn)了Parcelable接口,因此它可以跨進(jìn)程傳輸,系統(tǒng)會根據(jù)RemoteViews的包名等信息拿到該應(yīng)用的資源;然后通過LayoutInflater去加載RemoteViews中的布局文件。接著系統(tǒng)會對View進(jìn)行一系列界面更新任務(wù),這些任務(wù)就是之前我們通過set來提交的。set方法對View的更新并不會立即執(zhí)行,會記錄下來,等到RemoteViews被加載以后才會執(zhí)行。

工作流程.png

5、為了提高效率,系統(tǒng)沒有直接通過Binder去支持所有的View和View操作。而是提供一個Action概念,Action同樣實現(xiàn)Parcelable接口。系統(tǒng)首先將View操作封裝到Action對象并將這些對象跨進(jìn)程傳輸?shù)絊ystemService進(jìn)程,接著SystemService進(jìn)程執(zhí)行Action對象的具體操作。遠(yuǎn)程進(jìn)程通過RemoteViews的apply方法來進(jìn)行View的更新操作,RemoteViews的apply方法會去遍歷所有的Action對象并調(diào)用他們的apply方法。這樣避免了定義大量的Binder接口,也避免了大量IPC操作。
6、apply和reApply的區(qū)別在于:apply會加載布局并更新界面,而reApply則只會更新界面。
7、關(guān)于單擊事件,RemoteViews中只支持發(fā)起PendingIntent,不支持onClickListener那種模式。setOnClickPendingIntent用于給普通的View設(shè)置單擊事件,不能給集合(ListView/StackView)中的View設(shè)置單擊事件(開銷大,系統(tǒng)禁止了這種方式)。如果要給ListView/StackView中的item設(shè)置單擊事件,必須將setPendingIntentTemplate和setOnClickFillInIntent組合使用才可以。

四、RemoteViews的意義

分析了RemoteViews的原理后,我們可以模擬一下跨進(jìn)程UI更新,場景如下:一個應(yīng)用的兩個Activity A、B,修改A的process屬性讓其運行在獨立的進(jìn)程中,構(gòu)建多進(jìn)程環(huán)境。

<activity android:name=".FirstActivity"
            android:process=":remote">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SendMsgActivity"></activity>

A啟動后再啟動B,B通過廣播發(fā)送RemoteViews,A接收后更新RemoteViews。
這里要注意的是,如果A哈B不在一個應(yīng)用內(nèi),那么B中的資源文件Id傳到A中可能就是無效的,此時最好提前約定好RemoteViews中要加載的布局文件名稱,A在收到RemoteViews后根據(jù)布局名稱加載布局:

// 假如RemoteViews跨應(yīng)用顯示,那么就不能通過id來加載layout了,需要根據(jù)名稱來加載布局
        // 注意:第三個參數(shù):包名,一定要寫RemoteViews來源的應(yīng)用包名
        int layoutId = getResources().getIdentifier("layout_simulated_notification",
                "layout", getPackageName());
        View view = getLayoutInflater().inflate(layoutId, remote_views_content, false);
        // reapply方法不需要加載layout
        remoteViews.reapply(this, view);

        remote_views_content.addView(view);

github地址:RemoteViewsDemo

附錄

參考:
1、《Android開發(fā)藝術(shù)探索》
2、Android神奇“控件”-----RemoteViews
3、Android開發(fā)藝術(shù)探索 第5章 理解RemoteViews 讀書筆記

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容