安卓开发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 进行组件间的通信和数据传递。

编辑

分享

相关推荐
羊群智妍4 小时前
2026 AI搜索流量密码:免费GEO监测工具,优化效果看得见
笔记·百度·微信·facebook·新浪微博
Doro再努力5 小时前
【Linux操作系统10】Makefile深度解析:从依赖推导到有效编译
android·linux·运维·服务器·编辑器·vim
Daniel李华5 小时前
echarts使用案例
android·javascript·echarts
做人不要太理性6 小时前
CANN Runtime 运行时组件深度解析:任务调度机制、存储管理策略与维测体系构建逻辑
android·运维·魔珐星云
山岚的运维笔记6 小时前
SQL Server笔记 -- 第18章:Views
数据库·笔记·sql·microsoft·sqlserver
我命由我123456 小时前
Android 广播 - 静态注册与动态注册对广播接收器实例创建的影响
android·java·开发语言·java-ee·android studio·android-studio·android runtime
朗迹 - 张伟7 小时前
Tauri2 导出 Android 详细教程
android
lpruoyu8 小时前
【Android第一行代码学习笔记】Android架构_四大组件_权限_持久化_通知_异步_服务
android·笔记·学习
wdfk_prog8 小时前
[Linux]学习笔记系列 -- [drivers][mmc][mmc_sdio]
linux·笔记·学习
果果燕8 小时前
今日学习笔记:双向链表、循环链表、栈
笔记·学习·链表