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"))
相关推荐
2501_915918412 小时前
App 使用 HTTPS 的工程化实战,从接入到真机排查的一线指南
android·ios·小程序·https·uni-app·iphone·webview
恋猫de小郭3 小时前
第一台 Andriod XR 设备发布,Jetpack Compose XR 有什么不同?对原生开发有何影响?
android·前端·flutter
allk554 小时前
List && Map在安卓中的优化
android·数据结构·性能优化·list·map
.豆鲨包4 小时前
【Android】从源码角度理解Handler机制
android
杨筱毅5 小时前
【Android】Handler/Looper机制相关的类图和流程图
android·java·流程图
Kapaseker6 小时前
酷炫的文字效果 — Compose 文本着色
android·kotlin
努力进修6 小时前
【JavaEE初阶】 多线程编程核心:解锁线程创建、方法与状态的创新实践密码
android·java·java-ee
生莫甲鲁浪戴6 小时前
Android Studio新手开发第二十八天
android·ide·android studio
zhaoyufei1337 小时前
Android触屏TP驱动事件上报以及多点触摸
android
杨筱毅7 小时前
【Android】详细讲解ViewDragHelper的实现原理(不含代码版)
android