Android应用如何主动触发Application Not Responding(ANR)错误?
First, let's break down why your current code isn't triggering an ANR: your snippet mentions a "long time" task but doesn't actually implement the blocking logic. Even if you had, blocking during onCreate might not reliably show the ANR dialog right away—ANRs are most consistently triggered when the main thread is blocked after the app is visible and can respond to user input.
Here are a few reliable methods to trigger an ANR for testing:
1. Block the Main Thread on User Interaction (Most Consistent)
Add a button to your layout, then use its click listener to freeze the main thread. The system monitors input events closely—if it doesn't get a response within ~5 seconds, the ANR dialog will pop up immediately.
Update Your Layout (activity_main.xml)
Add a button to trigger the ANR:
<Button android:id="@+id/trigger_anr_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Trigger ANR" />
Update MainActivity.java
Handle the button click with an infinite loop to block the main thread:
public class MainActivity extends AppCompatActivity { TextView tt; Button triggerBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tt = findViewById(R.id.dd); triggerBtn = findViewById(R.id.trigger_anr_btn); triggerBtn.setOnClickListener(v -> { // Freeze the main thread indefinitely while (true) { // No operations here—this will lock up the UI } }); } }
2. Block the Main Thread During Startup
If you want to trigger ANR during app launch, you need to block the main thread for at least 5 seconds (the system's threshold for input-related ANRs). Use Thread.sleep() (never do this in production code!):
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tt = findViewById(R.id.dd); try { // Sleep for 10 seconds—well over the ANR threshold Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } }
Note: During startup, the system might take a bit longer to show the ANR dialog or even kill the app if it's unresponsive for too long. The button click method is more reliable because it's tied to a user action the system expects to respond to.
3. Verify ANR Behavior
- Ensure developer options are enabled on your test device/emulator (some debug environments suppress ANR dialogs by default).
- After triggering the block, wait 5-10 seconds—you should see the "App isn't responding" dialog with options to wait or close the app.
Remember: ANRs indicate poor app performance, so this is only for testing. Always run long tasks on background threads (like using Coroutines, WorkManager, or AsyncTask) in production apps.
内容的提问来源于stack exchange,提问作者sgkim

