无需切换Activity且不调用startIntent,如何实现数据传递?
Hey, great question! I totally get what you're trying to do—pass a number between two Activities without triggering an immediate jump via startActivity(). Let's walk through several solid solutions you can use, depending on your use case:
This is the easiest way to hold temporary shared data across your app, perfect if you don't need the number to persist after the app restarts.
- Step 1: Create a custom Application subclass
class MyApp : Application() { // Define a variable to store your shared number var sharedNumber: Int = 0 }
- Step 2: Register it in
AndroidManifest.xml
<application android:name=".MyApp" <!-- Keep your existing application attributes --> > <!-- Your Activities go here --> </application>
- Step 3: Set the number in your first Activity
val myApp = application as MyApp myApp.sharedNumber = 42 // Replace with your target number
- Step 4: Retrieve it in your second Activity
val myApp = application as MyApp val receivedNumber = myApp.sharedNumber
Note: This data is lost when the app is killed or restarted.
Use this if you need the number to stick around even after the app restarts. It's great for small, key-value data like numbers.
- Write the number from the first Activity:
val sharedPref = getSharedPreferences("MyAppData", Context.MODE_PRIVATE) with(sharedPref.edit()) { putInt("KEY_SHARED_NUMBER", 42) apply() // Async write, won't block the main thread }
- Read it in the second Activity:
val sharedPref = getSharedPreferences("MyAppData", Context.MODE_PRIVATE) // 0 is the default value if the key doesn't exist yet val receivedNumber = sharedPref.getInt("KEY_SHARED_NUMBER", 0)
If you want a clean, lifecycle-safe way to share data (and avoid losing it during configuration changes like screen rotation), ViewModel is Google's go-to solution.
- First, add the ViewModel dependency to your
build.gradle(Module level):
dependencies { implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.2" }
- Create a shared ViewModel class:
class SharedNumberViewModel : ViewModel() { // LiveData lets you observe changes if needed val numberLiveData = MutableLiveData<Int>() fun updateNumber(number: Int) { numberLiveData.value = number } }
- Set the number in the first Activity:
val viewModel = ViewModelProvider(this)[SharedNumberViewModel::class.java] viewModel.updateNumber(42)
- Retrieve it in the second Activity:
val viewModel = ViewModelProvider(this)[SharedNumberViewModel::class.java] // Option 1: Observe real-time changes viewModel.numberLiveData.observe(this) { number -> // Do something with the updated number Log.d("SecondActivity", "Got number: $number") } // Option 2: Get the current value directly val receivedNumber = viewModel.numberLiveData.value ?: 0
This is a quick fix but carries risks like memory leaks, so only use it for small, temporary scenarios.
- Define a static variable in your first Activity:
class FirstActivity : AppCompatActivity() { companion object { var sharedNumber: Int = 0 } // Somewhere in your code, set the value fun setSharedNumber() { sharedNumber = 42 } }
- Retrieve it in the second Activity:
val receivedNumber = FirstActivity.sharedNumber
Warning: If the first Activity is destroyed but the static variable still holds references, it can cause memory leaks. Avoid this in production apps.
Pick the solution that fits your needs:
- Temporary, simple share: Custom Application Class
- Persistent data: SharedPreferences
- Lifecycle-safe, clean architecture: ViewModel
- Quick emergency fix: Static Variables (carefully)
内容的提问来源于stack exchange,提问作者J.JAIT

