看到《Android開發藝術探索》書中 P241 頁提到RemoteViews跨程式資源訪問的限制,我在跨程式的實際使用時,證實是沒有限制的,可以跨程式使用,RemoteViews原始碼如下:
public RemoteViews(String packageName, int layoutId) {
this(getApplicationInfo(packageName, UserHandle.myUserId()), layoutId);
}
protected RemoteViews(ApplicationInfo application, int layoutId) {
mApplication = application;
...
}
複製程式碼
RemoteViews例項化的時候會儲存一個mApplication的變數,用於跨程式訪問資源。
/** @hide */
public View apply(Context context, ViewGroup parent, OnClickHandler handler) {
...
final Context contextForResources = getContextForResources(context);
Context inflationContext = new ContextWrapper(context) {
@Override
public Resources getResources() {
return contextForResources.getResources();
}
@Override
public Resources.Theme getTheme() {
return contextForResources.getTheme();
}
@Override
public String getPackageName() {
return contextForResources.getPackageName();
}
};
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
...
}
private Context getContextForResources(Context context) {
if (mApplication != null) {
if (context.getUserId() == UserHandle.getUserId(mApplication.uid)
&& context.getPackageName().equals(mApplication.packageName)) {
return context;
}
try {
return context.createApplicationContext(mApplication,
Context.CONTEXT_RESTRICTED);
} catch (NameNotFoundException e) {
Log.e(LOG_TAG, "Package name " + mApplication.packageName + " not found");
}
}
return context;
}
複製程式碼
感謝網友 magazmj@gmail.com
的反饋,希望對大家有所幫助。