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"))
相关推荐
xzkyd outpaper2 小时前
onSaveInstanceState() 和 ViewModel 在数据保存能力差异
android·计算机八股
梓仁沐白3 小时前
【Kotlin】协程
开发语言·python·kotlin
CYRUS STUDIO3 小时前
FART 脱壳某大厂 App + CodeItem 修复 dex + 反编译还原源码
android·安全·逆向·app加固·fart·脱壳
WAsbry3 小时前
现代 Android 开发自定义主题实战指南
android·kotlin·material design
xzkyd outpaper4 小时前
Android动态广播注册收发原理
android·计算机八股
唐墨1234 小时前
android与Qt类比
android·开发语言·qt
林林要一直努力5 小时前
Android Studio 向模拟器手机添加照片、视频、音乐
android·智能手机·android studio
AD钙奶-lalala5 小时前
Mac版本Android Studio配置LeetCode插件
android·ide·android studio
梓仁沐白6 小时前
【Kotlin】注解&反射&扩展
开发语言·python·kotlin
散人10246 小时前
Android Test3 获取的ANDROID_ID值不同
android·unit testing