Dialog中的一个函数的源码分析

本文深入探讨了Android中Dialog与Activity之间的复杂关联。通过分析Dialog.java中的getAssociatedActivity方法,揭示了如何确定与Dialog相关联的Activity,并解释了为何需要进行这种复杂的判断逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个函数是从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;
    }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值