为何在Android Activity间传输数据需用putExtra()而非静态变量?
putExtra() for Activity Data Transfer Instead of Static Variables? Great question—this is a common point of confusion for Android developers, especially when static variables seem like a "quick fix." Let’s break down why putExtra() is the recommended approach, and why static variables carry significant risks.
First: Why putExtra() is designed for this job
Android’s component model is built around loose coupling and handling lifecycle changes gracefully, and putExtra() aligns perfectly with these goals:
- Lifecycle resilience: Activities can be destroyed and recreated by the system at any time (e.g., screen rotation, low memory). Data passed via
putExtra()is stored in the Intent’sBundle, which the system automatically saves and restores during these lifecycle events. Static variables, on the other hand, aren’t managed by the system—if your app is killed in the background, static values will be cleared, leading to nulls or incorrect data when the app resumes. - Type safety & clear contracts:
putExtra()provides type-specific methods (likeputStringExtra(),putIntExtra()) that catch type mismatches at compile time. Static variables require manual casting, which can lead toClassCastExceptioncrashes. Additionally, the Intent acts as an explicit contract: anyone maintaining the target Activity can see exactly what data it expects, whereas static variables create hidden dependencies that are hard to track. - Low coupling: Using
putExtra()keeps your Activities independent. The sender only needs to know the target Activity’s class and the required data keys, while the receiver only needs to read from the Intent. Static variables create tight coupling—changing the static field in one Activity can break another, making your code harder to maintain and test.
The hidden dangers of static variables
While static variables might seem simpler, they introduce several critical issues:
- Memory leaks: If a static variable holds a reference to an Activity (or any Context-dependent object), that Activity will never be garbage collected—even after it’s destroyed. Over time, this leads to memory bloat and eventual
OutOfMemoryErrorcrashes. - Data inconsistency: Static variables are shared across all instances of your app. If you launch multiple instances of the same Activity, or if the app is restarted after being killed, the static value might be overwritten or cleared. For example: if User A sets a static variable, then User B launches the same flow, they’ll get User A’s data instead of their own.
- Against Android’s design principles: The Android framework is built to handle component lifecycle changes and inter-component communication via Intents. Using static variables is a hack that bypasses this framework, leading to unpredictable behavior that’s hard to debug.
Example: putExtra() vs. Static Variables
Recommended approach with putExtra()
// Sending Activity val intent = Intent(this, ProfileActivity::class.java) intent.putExtra("USER_ID", 12345) intent.putExtra("USER_FULL_NAME", "Jane Smith") startActivity(intent) // Receiving Activity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val userId = intent.getIntExtra("USER_ID", -1) // Default to -1 if missing val fullName = intent.getStringExtra("USER_FULL_NAME") // Use the data safely }
Not recommended: Static variables
// A global object to hold static data object AppState { var currentUserId: Int? = null } // Sending Activity AppState.currentUserId = 12345 startActivity(Intent(this, ProfileActivity::class.java)) // Receiving Activity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val userId = AppState.currentUserId // Risk: userId could be null if app was killed, or hold an old value from a previous session }
Final takeaway
While putExtra() might feel a bit verbose, it’s the reliable, maintainable way to pass data between Activities. If you’re dealing with complex objects, you can use Parcelable or Serializable to bundle them, or even use ViewModel for data sharing within the same task stack. Static variables should be avoided for inter-Activity communication—they’re a shortcut that leads to long-term headaches.
内容的提问来源于stack exchange,提问作者MohammadReza Ganjkhanlou

