Android启动另一个Activity崩溃,报ActivityNotFoundException求助
Hey there! As someone who's fumbled through this exact error early on in my Android dev journey, let's break down the most common fixes to get your app running smoothly again.
1. Make sure your target Activity is registered in AndroidManifest.xml
This is the #1 culprit for this error—Android requires every Activity in your app to be declared in the manifest. Double-check that you've added an entry for your target Activity, like this:
<activity android:name=".YourTargetActivity" <!-- Replace with your actual Activity class name --> android:exported="true" /> <!-- Required for Android 12+; set to false if only accessed internally -->
If your Activity is in a subpackage (e.g., com.example.myapp.ui.DetailsActivity), you can use the relative path .ui.DetailsActivity or write the full class name.
2. Verify your Intent has the correct Activity class
It's easy to typo the class name when creating your Intent. Check that the class you're referencing matches exactly (Java is case-sensitive!):
// Wrong example: Typo in the Activity class name Intent badIntent = new Intent(MainActivity.this, DetaisActivity.class); // Correct example: Exact match to your Activity class Intent goodIntent = new Intent(MainActivity.this, DetailsActivity.class); startActivity(goodIntent);
3. Confirm the target Activity file still exists
Accidentally deleting or moving the Activity's .java file will definitely trigger this error. Head to your project's file structure and make sure the target Activity is in the right package and hasn't been removed.
4. Check the exported attribute (Android 12+)
If your app targets Android 12 (API 31) or higher, every Activity must have the android:exported attribute set. If the Activity is only launched from within your app, set it to false; if it's a main entry point or needs to be accessed externally, set it to true. Omitting this attribute will cause Android to throw an exception.
5. Ensure you're using the right Context for your Intent
While this is less common, using an incorrect Context (like the Application Context instead of your Activity Context) can sometimes cause issues. Stick to MainActivity.this when creating the Intent to launch another Activity from your MainActivity.
If you've gone through all these steps and still hit the error, feel free to share the code you're using to launch the Activity and the relevant parts of your AndroidManifest.xml—that'll help narrow down the problem even more!
内容的提问来源于stack exchange,提问作者FranCode

