安卓开发Intent详细介绍和使用

1. 什么是 Intent

在 Android 开发里,Intent 是一个极为关键的组件,它本质上是一种消息传递对象。其主要用途是在不同的组件之间进行通信,这些组件涵盖了 ActivityServiceBroadcastReceiver 等。借助 Intent,你能够启动新的 Activity、开启或停止 Service,还能发送广播消息。

2. Intent 的主要作用

  • 启动 Activity :从一个 Activity 跳转到另一个 Activity
  • 启动 Service:开启或停止一个后台服务。
  • 发送广播:向系统或者应用内的广播接收器发送消息。
  • 数据传递:在不同组件之间传递数据。

3. Intent 的类型

显式 Intent

显式 Intent 明确指定了要启动的组件的名称,通常用于应用内部组件之间的交互。

kotlin

kotlin 复制代码
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = findViewById<Button>(R.id.start_button)
        button.setOnClickListener {
            // 创建显式 Intent,指定要启动的 Activity 类
            val intent = Intent(this, SecondActivity::class.java)
            startActivity(intent)
        }
    }
}

隐式 Intent

隐式 Intent 不指定具体的组件,而是通过 ActionCategoryData 等信息来描述要执行的操作,系统会根据这些信息寻找合适的组件来处理。

kotlin

kotlin 复制代码
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = findViewById<Button>(R.id.open_browser_button)
        button.setOnClickListener {
            // 创建隐式 Intent,打开网页
            val uri = Uri.parse("https://www.example.com")
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        }
    }
}

4. Intent 的主要属性

  • Action :是一个字符串,用于指定要执行的通用操作,如 ACTION_VIEWACTION_EDIT 等。
  • Data :一个 Uri 对象,用于指定操作所涉及的数据,例如文件的 Uri、网页的 Uri 等。
  • Category :是一个字符串集合,用于进一步描述 Intent 的附加信息,例如 CATEGORY_DEFAULT 表示默认的操作。
  • Type :指定数据的 MIME 类型,如 text/plainimage/jpeg 等。
  • Extras :是一个 Bundle 对象,用于在 Intent 中携带额外的数据,例如传递字符串、整数等。

5. 在 Intent 中传递数据

kotlin

kotlin 复制代码
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = findViewById<Button>(R.id.send_data_button)
        button.setOnClickListener {
            val intent = Intent(this, SecondActivity::class.java)
            intent.putExtra("message", "这是传递的数据")
            startActivity(intent)
        }
    }
}

class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        val textView = findViewById<TextView>(R.id.received_text)
        val message = intent.getStringExtra("message")
        textView.text = message
    }
}

6. 启动 Activity 并获取返回结果

kotlin

kotlin 复制代码
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    private val REQUEST_CODE = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = findViewById<Button>(R.id.start_for_result_button)
        button.setOnClickListener {
            val intent = Intent(this, SecondActivity::class.java)
            startActivityForResult(intent, REQUEST_CODE)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            val result = data?.getStringExtra("result")
            val textView = findViewById<TextView>(R.id.result_text)
            textView.text = result
        }
    }
}

class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        val button = findViewById<Button>(R.id.return_result_button)
        button.setOnClickListener {
            val resultIntent = Intent()
            resultIntent.putExtra("result", "这是返回的结果")
            setResult(RESULT_OK, resultIntent)
            finish()
        }
    }
}

7. 启动 Service

kotlin

kotlin 复制代码
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val startServiceButton = findViewById<Button>(R.id.start_service_button)
        startServiceButton.setOnClickListener {
            val intent = Intent(this, MyService::class.java)
            startService(intent)
        }

        val stopServiceButton = findViewById<Button>(R.id.stop_service_button)
        stopServiceButton.setOnClickListener {
            val intent = Intent(this, MyService::class.java)
            stopService(intent)
        }
    }
}

import android.app.Service
import android.content.Intent
import android.os.IBinder

class MyService : Service() {
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // 执行服务操作
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        // 服务销毁时的操作
    }
}

8. 发送广播

kotlin

kotlin 复制代码
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val sendBroadcastButton = findViewById<Button>(R.id.send_broadcast_button)
        sendBroadcastButton.setOnClickListener {
            val intent = Intent("com.example.MY_CUSTOM_BROADCAST")
            sendBroadcast(intent)
        }
    }

    override fun onResume() {
        super.onResume()
        val filter = IntentFilter("com.example.MY_CUSTOM_BROADCAST")
        registerReceiver(broadcastReceiver, filter)
    }

    override fun onPause() {
        super.onPause()
        unregisterReceiver(broadcastReceiver)
    }

    private val broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == "com.example.MY_CUSTOM_BROADCAST") {
                // 处理广播消息
            }
        }
    }
}

以上就是 Intent 的详细介绍和使用示例,通过这些示例你可以了解如何使用 Intent 进行组件间的通信和数据传递。

编辑

分享

相关推荐
Piko61417 小时前
锐捷交换机 DHCP Server部署
运维·网络·笔记
CyL_Cly17 小时前
解决官网下载慢!Android Studio 最新版网盘下载
android·ide·android studio
智塑未来17 小时前
鸿蒙系统对比安卓、iOS,核心优势是什么?
android·ios·harmonyos
AI刀刀17 小时前
豆包智能体对话导出后,如何构建长期归档与高效检索体系?
android·人工智能·word·excel·ai导出鸭
取地址符18 小时前
Rust学习笔记(基于Rustlings)(2):数据结构与集合
笔记·学习·rust
A.零点18 小时前
期末复习,408考研数据结构:第一章绪论完整知识梳理与真题深度解读
c语言·数据结构·笔记·考研
茯苓gao19 小时前
嵌入式开发笔记:工业机器人通信协议深度解析——从现场总线到工业以太网
笔记·嵌入式硬件·学习·机器人·信息与通信
初雪云19 小时前
iOS 上架入门:证书、描述文件、IPA 上传到底是什么关系?
android·ios·自动化·产品经理·iphone
取地址符19 小时前
Rust语法学习 (基于Rustlings)(1):基础语法
经验分享·笔记·学习·rust
不会调制解调的猫19 小时前
笔记 | 什么是 rp_filter(反向路径过滤)?
服务器·网络·笔记