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

编辑

分享

相关推荐
stanleyrain18 分钟前
VIM学习笔记
笔记·学习·vim
QING6182 小时前
详解:Kotlin 类的继承与方法重载
android·kotlin·app
QING6183 小时前
Kotlin 伴生对象(Companion Object)详解 —— 使用指南
android·kotlin·app
一一Null3 小时前
Android studio 动态布局
android·java·android studio
美味的大香蕉7 小时前
Spark SQL
笔记
轻闲一号机9 小时前
【机器学习】机器学习笔记
人工智能·笔记·机器学习
天下琴川9 小时前
Dify智能体平台源码二次开发笔记(5) - 多租户的SAAS版实现(2)
人工智能·笔记
AD钙奶-lalala10 小时前
某车企面试备忘
android
我爱拉臭臭11 小时前
kotlin音乐app之自定义点击缩放组件Shrink Layout
android·java·kotlin
workworkwork勤劳又勇敢11 小时前
Adversarial Attack对抗攻击--李宏毅机器学习笔记
人工智能·笔记·深度学习·机器学习