- Use Explicit Intent to start another Activity
From StartActivity.kt to start LocalMusicActivity.kt
val intent = Intent(this@StartActivity, LocalMusicActivity::class.java)
startActivity(intent)
- If this error happened in Logcat.
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.simplemusic/com.example.simplemusic.activity.LocalMusicActivity}; have you declared this activity in your AndroidManifest.xml, or does your intent not match its declared ?
Remember to declare the activity in AndroidManifest.xml
<activity android:name="com.example.simplemusic.activity.LocalMusicActivity" />
- Pass data with Intent using Bundle directly
val intent =
Intent(this@StartActivity, LocalMusicActivity::class.java)
val bundle = Bundle()
bundle.putString("action", "play")
bundle.putInt("count", 10)
intent.putExtras(bundle)
startActivity(intent)
In the target Activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val bundle = this.intent.extras
Log.d(
"Intent data",
"name: ${bundle?.getString("name")}, action: ${bundle?.getString("action")}, count: ${
bundle?.getInt("count")
}"
)
// ...
Output
name: null, action: play, count: 10
- Pass data with Intent
val intent =
Intent(this@StartActivity, LocalMusicActivity::class.java)
intent.putExtra("action", "play")
intent.putExtra("count", 10)
startActivity(intent)
The same result as the last one. It will create a bundle auto.
public @NonNull Intent putExtra(String name, @Nullable String value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putString(name, value);
return this;
}