Activity之间交互

Backgroud:

想要实现Activity之间的交互,需要用到intent工具

本博客中所有第二Activity均为SecActivity,需要预先进行创建

本博客所使用的开发语言为Kotlin

使用intent调用Activity

显式调用

Kotlin 复制代码
val intent = Intent(this, SecActivity::class.java)
startActivity(intent)

隐式调用

一般调用

  1. 在注册文件AndroidManifest.xml中为被调用Activity添加响应的action与category
XML 复制代码
<activity 
    android:name=".SecActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="com.example.activitytest.ACTION_START" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>
  1. 在MainActivity中调用
Kotlin 复制代码
//这里由于SecActivity所用category为默认值,故不需要另行添加
val intent = Intent("com.example.activitytest.ACTION_START")
startActivity(intent)

每个intent只能指定一个action,却可以指定数个category

自定义category调用

XML 复制代码
<activity 
    android:name=".SecActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="com.example.activitytest.ACTION_START" />
        <category android:name="com.example.activitytest.MY_CATEGORY" />
    </intent-filter>
</activity>
Kotlin 复制代码
val intent = Intent("com.example.activitytest.ACTION_START")
intent.addCategory("com.example.activitytest.MY_CATEGORY")
startActivity(intent)

Uri调用

Kotlin 复制代码
//这段代码会调用默认浏览器打开设定的网址
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("https://www.baidu.com")
startActivity(intent)

向第二Activity传递数据

javascript 复制代码
//MainActivity向SecActivity传递数据
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("USER", message)
startActivity(intent)
Kotlin 复制代码
//SecActivity获取从MainActivity传递而来的数据
val name = intent.getStringExtra("USER")
val textView = findViewById<TextView>(R.id.secTxt)
textView.text = "This is the second activity!\nWelcome $name!"

向调用Activity返回数据

调用Activity:

Kotlin 复制代码
//注册回调
private val resultLauncher = registerForActivityResult(
    ActivityResultContracts.StartActivityForResult()
) { result ->
    if (result.resultCode == RESULT_OK) {
        val data = result.data
        viewText.text = data?.getStringExtra("key")
    }
}

//在主函数中调用SecActivity
val intent = Intent(this, SecdActivity::class.java)
resultLauncher.launch(intent)

被调用Activity:

Kotlin 复制代码
//设置返回数据
setResult(RESULT_OK, Intent().putExtra("key", "This\'s returnData"))
相关推荐
圆号本昊6 分钟前
【2025最新】Flutter 加载显示 Live2D 角色,实战与踩坑全链路分享
android·flutter
小曹要微笑1 小时前
MySQL的TRIM函数
android·数据库·mysql
mrsyf2 小时前
Android Studio Otter 2(2025.2.2版本)安装和Gradle配置
android·ide·android studio
DB虚空行者2 小时前
MySQL恢复之Binlog格式详解
android·数据库·mysql
liang_jy4 小时前
Android 事件分发机制(一)—— 全流程源码解析
android·面试·源码
峥嵘life5 小时前
2026 Android EDLA 认证相关资源网址汇总(持续更新)
android·java·学习
kkk_皮蛋5 小时前
在移动端使用 WebRTC (Android/iOS)
android·ios·webrtc
aqi006 小时前
FFmpeg开发笔记(九十六)采用Kotlin+Compose的视频编辑器OpenVideoEditor
android·ffmpeg·kotlin·音视频·流媒体
诸神黄昏EX7 小时前
Android Safety 系列专题【篇一:系统签名】
android
ll_god7 小时前
android gradle中如何引用 libs.versions.toml中定义的版本变量添加compose引用
android