0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Android Intent

Posted at
  1. 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" />
  1. 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

  1. 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;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?