Android BroadcastReceiver触发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:
Fix the
getContext()method in InputActivity
SinceActivityis a subclass ofContextby default, you don't need a customgetContext()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; }
- If you're overriding
Use the BroadcastReceiver's built-in Context
Even better—you don't need to callInputActivity.getContext()at all in your broadcast receiver. TheonReceive()method already gets a validContextas 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

