这个函数是从Dialog.java里找到的:
/**
* @return The activity associated with this dialog, or null if there is no assocaited activity.
*/
private ComponentName getAssociatedActivity() {
Activity activity = mOwnerActivity;
Context context = getContext();
while (activity == null && context != null) {
if (context instanceof Activity) {
activity = (Activity) context; // found it!
} else {
context = (context instanceof ContextWrapper) ?
((ContextWrapper) context).getBaseContext() : // unwrap one level
null; // done
}
}
return activity == null ? null : activity.getComponentName();
}
函数的作用是找到与Dialog关联的Activity的ComponentName,这个复杂的判断逻辑吸引了我,所以把它拿出来分析分析。
这个函数为什么要分析Activity和Context的区分呢,我想可能是在Activity里new这个dialog的时候,有的人是用this来代替this.getApplicationContext()吧,猜测呵呵。如果是的话那么确实会有很大区别。
当然更主要的是Activity是继承自Context的才导致了这个复杂的判断,呵呵
从下面的函数的注释来看,判断这个Dialog的所有者即Activity是为了万一要用到声音控制:
/**
* Sets the Activity that owns this dialog. An example use: This Dialog will
* use the suggested volume control stream of the Activity.
*
* @param activity The Activity that owns this dialog.
*/
public final void setOwnerActivity(Activity activity) {
mOwnerActivity = activity;
getWindow().setVolumeControlStream(mOwnerActivity.getVolumeControlStream());
}
下面这个也能验证我的一个猜测,即Dialog未必都是从Activity里制造出来的,所以才会有返回值是NUll的情况
/**
* Returns the Activity that owns this Dialog. For example, if
* {@link Activity#showDialog(int)} is used to show this Dialog, that
* Activity will be the owner (by default). Depending on how this dialog was
* created, this may return null.
*
* @return The Activity that owns this Dialog.
*/
public final Activity getOwnerActivity() {
return mOwnerActivity;
}