You need to enable JavaScript to run this app. 调用mInterstitialAd.show展示广告,关闭时触发焦点回调致应用崩溃
优惠活动
大模型
产品
解决方案
定价
更多

调用mInterstitialAd.show展示广告,关闭时触发焦点回调致应用崩溃

崩溃排查与优化方案

崩溃触发链路

你遇到的崩溃是多因素叠加导致的:

  • 插屏广告弹出/关闭时,会触发原界面的焦点切换,此时焦点所在的counterName会触发onFocusChange回调
  • 回调里直接调用CounterList.get(getAdapterPosition()),在ViewHolder解绑、列表数据变动等场景下,getAdapterPosition()会返回RecyclerView.NO_POSITION(值为-1),直接取值会触发数组越界崩溃
  • 原有广告调度逻辑存在错误:在主线程的Runnable里调用Thread.currentThread().interrupt()实际是中断主线程,而非最初的休眠子线程,可能引发额外异常

具体优化点

1. 焦点回调增加安全校验

原有代码没有做任何边界判断,同时存在参数名误导问题:系统回调的第二个参数实际是hasFocus(表示当前控件是否获得焦点),你原代码命名为lostFocus很容易导致逻辑判断写反。优化后需要覆盖位置有效性、列表数据有效性两层校验,同时避免直接拿全局控件取值(防止View复用导致的取值错误):

counterName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        // 原有逻辑判断
        if (MainActivity.menuOpened) return;
        // 校验Adapter返回的位置是否有效
        int currentPosition = getAdapterPosition();
        if (currentPosition == RecyclerView.NO_POSITION) return;
        // 校验列表数据是否为空、是否越界
        if (CounterList == null || currentPosition >= CounterList.size()) return;
        // 用回调传入的View取值,避免复用偏差
        TextView currentFocusView = (TextView) v;
        CounterList.get(currentPosition).name = currentFocusView.getText().toString();
    }
});

如果需要避免广告弹出/关闭时的焦点切换误触发回调,可以新增广告展示状态标记,在焦点回调里直接跳过广告展示期间的操作:

// 广告展示前标记状态
isAdShowing = true;
mInterstitialAd.show(MainActivity.this);

// 广告关闭回调里重置状态
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
    @Override
    public void onAdDismissedFullScreenContent() {
        isAdShowing = false;
    }
});

// 焦点回调里增加状态判断
if (MainActivity.menuOpened || isAdShowing) return;

2. 广告调度逻辑重构

去掉「新建子线程+硬编码sleep」的延迟方案,改用主线程Handler延迟执行,既避免子线程内存泄漏,也修正中断逻辑的错误:

// 直接用主线程Handler延迟3分钟执行,不需要新建子线程
Runnable showAdRunnable = new Runnable() {
    @Override
    public void run() {
        if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
            isAdShowing = true;
            mInterstitialAd.show(MainActivity.this);
        }
    }
};
MainActivity.handler.postDelayed(showAdRunnable, 180000);

// 在Activity onDestroy时移除任务,避免内存泄漏
@Override
protected void onDestroy() {
    super.onDestroy();
    MainActivity.handler.removeCallbacks(showAdRunnable);
}

原来的Thread.currentThread().interrupt()逻辑完全不需要保留:如果需要提前取消广告展示,直接调用handler.removeCallbacks(showAdRunnable)即可,不需要中断线程。


内容的提问来源于stack exchange,提问作者EDGARS CEBOTARS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.11 10:06:07