在Android Kotlin中,可以使用Telephony库来检测和读取收到的短信。下面是一个完整的示例代码:
首先,在AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
然后,在你的Activity中,可以创建一个BroadcastReceiver来接收短信:
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.provider.Telephony
import android.telephony.SmsMessage
import android.widget.Toast
class SmsReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION == intent.action) {
val messages = Telephony.Sms.Intents.getMessagesFromIntent(intent)
for (message in messages) {
val smsBody = message.messageBody
val smsSender = message.originatingAddress
Toast.makeText(context, "收到来自 $smsSender 的短信:$smsBody", Toast.LENGTH_SHORT).show()
}
}
}
}
接下来,在你的Activity中注册这个BroadcastReceiver:
import android.Manifest
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity() {
private val SMS_PERMISSION_REQUEST_CODE = 0
private val smsReceiver = SmsReceiver()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (checkPermission()) {
registerReceiver()
} else {
requestPermission()
}
}
private fun checkPermission(): Boolean {
val smsPermission = Manifest.permission.READ_SMS
val receiveSmsPermission = Manifest.permission.RECEIVE_SMS
val granted = PackageManager.PERMISSION_GRANTED
return ContextCompat.checkSelfPermission(this, smsPermission) == granted &&
ContextCompat.checkSelfPermission(this, receiveSmsPermission) == granted
}
private fun requestPermission() {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS),
SMS_PERMISSION_REQUEST_CODE
)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == SMS_PERMISSION_REQUEST_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
registerReceiver()
} else {
Toast.makeText(this, "权限被拒绝,无法接收短信", Toast.LENGTH_SHORT).show()
}
}
}
private fun registerReceiver() {
val intentFilter = IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)
registerReceiver(smsReceiver, intentFilter)
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(smsReceiver)
}
}
上述代码中,我们在Activity的onCreate方法中首先检查是否有读取短信的权限,如果有权限则注册BroadcastReceiver,如果没有则申请权限。然后,在onRequestPermissionsResult方法中处理权限申请结果。最后,我们在onDestroy方法中取消注册BroadcastReceiver,以免内存泄漏。
请注意,由于涉及到敏感信息的读取,需要在运行时动态申请权限,并且在用户拒绝权限时给予相应的提示。
推荐的腾讯云相关产品:无
领取专属 10元无门槛券
手把手带您无忧上云