一,寫在前面
在前面兩篇文章RemoteViews的基本使用(上)之通知欄 ,RemoteViews的基本使用(下)之窗口小部件 中講述了RemoteViews的兩個應用場景,這篇文章主要介紹RemoteViews的內部機制,以及一個小擴展,使用RemoteViews實現跨進程操作界面。本篇文章以窗口小部件爲例,來分析RemoteViews如何實現跨進程操作界面。我們都知道在將小部件列表中將窗口小部件拖到桌面,會調用onUpdate方法,在該方法中會調用AppWidgetManager.updateAppWidget(appWidgetIds,remoteViews)來更新窗口小部件,調用RemoteViews方法的一些set..方法,修改窗口小部件的界面。對於這些不是很清楚的哥們,可以查看文章RemoteViews的基本使用(下)之窗口小部件 ,這篇文章對窗口小部件做了簡單的介紹,本篇文章主要從源碼角度分析RemoteViews,對窗口小部件的生命週期以及使用不再闡述。
二,以窗口小部件爲例
public void updateAppWidget(int[] appWidgetIds, RemoteViews views) {
try {
sService.updateAppWidgetIds(appWidgetIds, views, mContext.getUserId());
}
catch (RemoteException e) {
throw new RuntimeException("system server dead?", e);
}
}
public static AppWidgetManager getInstance(Context context) {
synchronized (sManagerCache) {
if (sService == null) {
IBinder b = ServiceManager.getService(Context.APPWIDGET_SERVICE);
sService = IAppWidgetService.Stub.asInterface(b);
}
WeakReference<AppWidgetManager> ref = sManagerCache.get(context);
AppWidgetManager result = null;
if (ref != null) {
result = ref.get();
}
if (result == null) {
result = new AppWidgetManager(context);
sManagerCache.put(context, new WeakReference<AppWidgetManager>(result));
}
return result;
}
}
sService是一個代理對象,updateAppWidgetIds方法的真正調用在服務裏,IAppWidgetService是一個AIDL接口,需要找到繼承IAppWidgetService.Stub的那個類,這裏直接告訴大家該類是AppWidgetService。public void updateAppWidgetIds(int[] appWidgetIds, RemoteViews views) {
if (appWidgetIds == null) {
return;
}
if (appWidgetIds.length == 0) {
return;
}
final int N = appWidgetIds.length;
synchronized (mAppWidgetIds) {
for (int i=0; i<N; i++) {
AppWidgetId id = lookupAppWidgetIdLocked(appWidgetIds[i]);
updateAppWidgetInstanceLocked(id, views);
}
}
}
//進入updateAppWidgetInstanceLocked方法
void updateAppWidgetInstanceLocked(AppWidgetId id, RemoteViews views) {
// allow for stale appWidgetIds and other badness
// lookup also checks that the calling process can access the appWidgetId
// drop unbound appWidgetIds (shouldn't be possible under normal circumstances)
if (id != null && id.provider != null && !id.provider.zombie && !id.host.zombie) {
id.views = views;
// is anyone listening?
if (id.host.callbacks != null) {
try {
// the lock is held, but this is a oneway call
id.host.callbacks.updateAppWidget(id.appWidgetId, views);
} catch (RemoteException e) {
// It failed; remove the callback. No need to prune because
// we know that this host is still referenced by this instance.
id.host.callbacks = null;
}
}
}
}
//callbacks實例化的位置
public int[] startListening(IAppWidgetHost callbacks, String packageName, int hostId,
List<RemoteViews> updatedViews) {
int callingUid = enforceCallingUid(packageName);
synchronized (mAppWidgetIds) {
Host host = lookupOrAddHostLocked(callingUid, packageName, hostId);
host.callbacks = callbacks;
updatedViews.clear();
ArrayList<AppWidgetId> instances = host.instances;
int N = instances.size();
int[] updatedIds = new int[N];
for (int i=0; i<N; i++) {
AppWidgetId id = instances.get(i);
updatedIds[i] = id.appWidgetId;
updatedViews.add(id.views);
}
return updatedIds;
}
}
最後會調用id.host.callbacks.updateAppWidget(id.appWidgetId, views),需要找到callbacks的實例化位置,上面代碼已經給出答案,調用AppWidgetService$startListening方法會實例化callbacks對象。那麼,誰調用了AppWidgetService$startListening方法呢。public void startListening() {
int[] updatedIds;
ArrayList<RemoteViews> updatedViews = new ArrayList<RemoteViews>();
try {
if (mPackageName == null) {
mPackageName = mContext.getPackageName();
}
updatedIds = sService.startListening(mCallbacks, mPackageName, mHostId, updatedViews);
}
catch (RemoteException e) {
throw new RuntimeException("system server dead?", e);
}
final int N = updatedIds.length;
for (int i=0; i<N; i++) {
updateAppWidgetView(updatedIds[i], updatedViews.get(i));
}
}
sService對象就是AppWidgetService,代理對象sService.startListening(mCallbacks, mPackageName, mHostId, updatedViews)的調用,基於底層Binder機制,調用遠程服務的startListening方法,也就是AppWidgetService$startListening。int mHostId;
Callbacks mCallbacks = new Callbacks();
final HashMap<Integer,AppWidgetHostView> mViews = new HashMap<Integer, AppWidgetHostView>();
public AppWidgetHost(Context context, int hostId) {
mContext = context;
mHostId = hostId;
mHandler = new UpdateHandler(context.getMainLooper());
synchronized (sServiceLock) {
if (sService == null) {
IBinder b = ServiceManager.getService(Context.APPWIDGET_SERVICE);
sService = IAppWidgetService.Stub.asInterface(b);
}
}
}
sService = IAppWidgetService.Stub.asInterface(b);獲取的不就是AppWidgetService的代理對象麼。 class Callbacks extends IAppWidgetHost.Stub {
public void updateAppWidget(int appWidgetId, RemoteViews views) {
Message msg = mHandler.obtainMessage(HANDLE_UPDATE);
msg.arg1 = appWidgetId;
msg.obj = views;
msg.sendToTarget();
}
public void providerChanged(int appWidgetId, AppWidgetProviderInfo info) {
Message msg = mHandler.obtainMessage(HANDLE_PROVIDER_CHANGED);
msg.arg1 = appWidgetId;
msg.obj = info;
msg.sendToTarget();
}
}
代碼比較簡單,發送了一個消息到消息隊列裏,接下來是處理消息,源碼如下:class UpdateHandler extends Handler {
public UpdateHandler(Looper looper) {
super(looper);
}
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLE_UPDATE: {
updateAppWidgetView(msg.arg1, (RemoteViews)msg.obj);
break;
}
case HANDLE_PROVIDER_CHANGED: {
onProviderChanged(msg.arg1, (AppWidgetProviderInfo)msg.obj);
break;
}
}
}
}
//繼續查看方法updateAppWidgetView
void updateAppWidgetView(int appWidgetId, RemoteViews views) {
AppWidgetHostView v;
synchronized (mViews) {
v = mViews.get(appWidgetId);
}
if (v != null) {
v.updateAppWidget(views);
}
}
這裏的v就是AppWidgetHostView,繼續查看AppWidgetHostView$updateAppWidget源碼如下:/**
* Process a set of {@link RemoteViews} coming in as an update from the
* AppWidget provider. Will animate into these new views as needed
*/
public void updateAppWidget(RemoteViews remoteViews) {
if (LOGD) Log.d(TAG, "updateAppWidget called mOld=" + mOld);
boolean recycled = false;
View content = null;
Exception exception = null;
// Capture the old view into a bitmap so we can do the crossfade.
if (CROSSFADE) {
if (mFadeStartTime < 0) {
if (mView != null) {
final int width = mView.getWidth();
final int height = mView.getHeight();
try {
mOld = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError e) {
// we just won't do the fade
mOld = null;
}
if (mOld != null) {
//mView.drawIntoBitmap(mOld);
}
}
}
}
if (remoteViews == null) {
if (mViewMode == VIEW_MODE_DEFAULT) {
// We've already done this -- nothing to do.
return;
}
content = getDefaultView();
mLayoutId = -1;
mViewMode = VIEW_MODE_DEFAULT;
} else {
// Prepare a local reference to the remote Context so we're ready to
// inflate any requested LayoutParams.
mRemoteContext = getRemoteContext(remoteViews);
int layoutId = remoteViews.getLayoutId();
// If our stale view has been prepared to match active, and the new
// layout matches, try recycling it
if (content == null && layoutId == mLayoutId) {
try {
remoteViews.reapply(mContext, mView);
content = mView;
recycled = true;
if (LOGD) Log.d(TAG, "was able to recycled existing layout");
} catch (RuntimeException e) {
exception = e;
}
}
// Try normal RemoteView inflation
if (content == null) {
try {
content = remoteViews.apply(mContext, this);
if (LOGD) Log.d(TAG, "had to inflate new layout");
} catch (RuntimeException e) {
exception = e;
}
}
mLayoutId = layoutId;
mViewMode = VIEW_MODE_CONTENT;
}
if (content == null) {
if (mViewMode == VIEW_MODE_ERROR) {
// We've already done this -- nothing to do.
return ;
}
Log.w(TAG, "updateAppWidget couldn't find any view, using error view", exception);
content = getErrorView();
mViewMode = VIEW_MODE_ERROR;
}
if (!recycled) {
prepareView(content);
addView(content);
}
if (mView != content) {
removeView(mView);
mView = content;
}
if (CROSSFADE) {
if (mFadeStartTime < 0) {
// if there is already an animation in progress, don't do anything --
// the new view will pop in on top of the old one during the cross fade,
// and that looks okay.
mFadeStartTime = SystemClock.uptimeMillis();
invalidate();
}
}
}
注意看49行,61行,分別調用remoteViews.reapply(mContext, mView),content = remoteViews.apply(mContext, this),調用了RemoteViews的apply加載或更新界面,調用RemoteViews的reapply方法更新界面,但不能加載。以本篇文章爲例,界面指的是在launcher應用上顯示的窗口小部件。三,小結
四,另外
五,RemoteViews源碼分析
5.1,分析RemoteViews$setXXX方法
public void setTextViewText(int viewId, CharSequence text) {
setCharSequence(viewId, "setText", text);
}
//繼續看setCharSequence
public void setCharSequence(int viewId, String methodName, CharSequence value) {
addAction(new ReflectionAction(viewId, methodName, ReflectionAction.CHAR_SEQUENCE, value));
}
//繼續看addAction
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);
}
從上面代碼可知:setTextViewText方法做了這樣一件事,用Action將控件的id,text的值封裝起來,並將Action對象放入到list集合中。後面肯定要取出集合裏的元素進行相應處理,那麼是在哪呢,後面會給出答案。 private abstract static class Action implements Parcelable {
public abstract void apply(View root, ViewGroup rootParent,
OnClickHandler handler) throws ActionException;
//...code
}
可以發現Action是一個抽象類,並實現了Parcelable接口,有一個很重要的抽象方法apply。Action有很多子類,如TextViewSizeAction,ReflectionAction等,setTextViewText方法中的Action是ReflectionAction,setTextViewTextSize方法中Action是TextViewSizeAction。也就是說,在調用remoteViews.setXXX方法時,對控件的操作的數據封裝在Action中。每調用一次remoteViews.setXXX方法,就將對應Action對象存入list集合中,然後統一交給AppWidgetService處理。5.2,分析RemoteViews$apply/reapply方法
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;
Context c = prepareContext(context);
LayoutInflater inflater = (LayoutInflater)
c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater = inflater.cloneInContext(c);
inflater.setFilter(this);
result = inflater.inflate(rvToApply.getLayoutId(), parent, false);
rvToApply.performApply(result, parent, handler);
return result;
}
//繼續看performApply
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);
}
}
}
result = inflater.inflate(rvToApply.getLayoutId(), parent, false)就是加載佈局文件,創建RemoteViews對象時會給字段mLayoutId賦值,即rvToApply.getLayoutId()的返回值;parent是AppWidgetHostView。5.3,分析Action$apply方法
前面以RemoteViews$setTextViewText爲例,封裝更新界面數據的Action是ReflectionAction,以其爲例。private class ReflectionAction extends Action {
ReflectionAction(int viewId, String methodName, int type, Object value) {
this.viewId = viewId;
this.methodName = methodName;
this.type = type;
this.value = value;
}
//...code
@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);
}
Class klass = view.getClass();
Method method;
try {
method = klass.getMethod(this.methodName, getParameterType());
}
catch (NoSuchMethodException ex) {
throw new ActionException("view: " + klass.getName() + " doesn't have method: "
+ this.methodName + "(" + param.getName() + ")");
}
if (!method.isAnnotationPresent(RemotableViewMethod.class)) {
throw new ActionException("view: " + klass.getName()
+ " can't use method with RemoteViews: "
+ this.methodName + "(" + param.getName() + ")");
}
try {
//noinspection ConstantIfStatement
if (false) {
Log.d(LOG_TAG, "view: " + klass.getName() + " calling method: "
+ this.methodName + "(" + param.getName() + ") with "
+ (this.value == null ? "null" : this.value.getClass().getName()));
}
method.invoke(view, this.value);
}
catch (Exception ex) {
throw new ActionException(ex);
}
}
}
第12行,findViewById獲取控件引用;第20,23,43行,使用反射技術更新該控件。有興趣的哥們可以研究下TextViewSizeAction的apply方法,它更新界面並不是用反射,在findViewById獲取到控件引用後,調用view.setTextSize(..)更新界面。六,RemoteViews的擴展使用
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void clickButton(View v) {
//發送廣播
Intent intent = new Intent();
intent.setAction("com.example.remoteview");
RemoteViews rv = new RemoteViews(getPackageName(), R.layout.rv_layout);
rv.setTextViewText(R.id.tv, "hello, from Sender");
intent.putExtra("remoteview", rv);
sendBroadcast(intent);
}
}
rv_layout.xml<?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:gravity="center_horizontal">
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:src="@drawable/ic_launcher"/>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/iv"
android:layout_marginTop="20dp"
android:textSize="24sp"
android:textColor="#f00"
android:background="@android:color/darker_gray"
android:text="remoteview"/>
</RelativeLayout>
應用RvReceiver:
public class MainActivity extends Activity {
private RelativeLayout rl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
public void init() {
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.remoteview");
MyReceiver receiver = new MyReceiver();
registerReceiver(receiver, filter);
rl = (RelativeLayout) findViewById(R.id.rl);
}
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("com.example.remoteview".equals(intent.getAction())) {
RemoteViews remoteViews = intent.getParcelableExtra("remoteview");
View view = remoteViews.apply(context, rl);
rl.addView(view);
}
}
}
}
activity_main.xml<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:text="RvReceiver" />
<RelativeLayout
android:id="@+id/rl"
android:layout_marginTop="120dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"></RelativeLayout>
</RelativeLayout>
需要注意的是,應用RvReceiver中並不需要rv_layout.xml資源文件。在應用RvSender中點擊按鈕後,應用RvReceiver界面如下: