You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android BroadcastReceiver触发java.lang.StackOverflowError问题求助

分析与解决:接收广播时的java.lang.StackOverflowError

Hey there, let's break down why you're hitting this StackOverflowError when handling broadcasts. The error log tells us everything we need—this has nothing to do with too many broadcasts being sent, it's an infinite recursion bug in your InputActivity.getContext() method.

问题原因分析

Look at your error stack trace: every line repeats com.example.curie.fairbanks_01.InputActivity.getContext(InputActivity.java:56). That means the getContext() method on line 56 of InputActivity is calling itself over and over without stopping. Each recursive call adds a frame to the app's call stack, and once it hits the 8MB stack limit, the system throws a StackOverflowError.

This is a super common mistake—you probably accidentally wrote a recursive call instead of returning a valid Context. For example, your code might look like this right now:

public Context getContext() {
    return getContext(); // Oops! This calls itself forever
}

解决方案

Here's how to fix this quickly:

  1. Fix the getContext() method in InputActivity
    Since Activity is a subclass of Context by default, you don't need a custom getContext() that loops infinitely. Replace the faulty method with one of these options:

    • If you're overriding getContext() (unnecessary for most Activity use cases), call the superclass implementation:
      @Override
      public Context getContext() {
          return super.getContext();
      }
      
    • Or simpler: just return the Activity instance directly, since it's already a Context:
      public Context getContext() {
          return this;
      }
      
  2. Use the BroadcastReceiver's built-in Context
    Even better—you don't need to call InputActivity.getContext() at all in your broadcast receiver. The onReceive() method already gets a valid Context as its first parameter. Use that instead of trying to fetch the Activity's Context manually:

    @Override
    public void onReceive(Context context, Intent intent) {
        // Use the 'context' parameter here directly
        Toast.makeText(context, "Broadcast received", Toast.LENGTH_SHORT).show();
    }
    

额外提示

The Bluetooth connection code you shared doesn't seem related to this error (the stack trace doesn't mention any Bluetooth methods). The root cause is definitely the recursive getContext() call in your Activity.

内容的提问来源于stack exchange,提问作者Collin Urie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:04:16