我正在尝试从用户的手机中获取传入的短信并将其显示在应用程序中。我的广播接收器代码是:
class MyReceiver : BroadcastReceiver() {
var msg:String? = null
var msgList: MutableList<String>? = mutableListOf()
private var mAPIService: APIService? = null
@TargetApi(Build.VERSION_CODES.M)
override fun onReceive(context: Context, intent: Intent) {
Toast.makeText(context, "Entered onReceive()", Toast.LENGTH_LONG).show()
Log.i("TAG", "Entered onReceive")
val pdu_type = "pdus";
mAPIService = ApiUtils.aPIServicePOST
// Get the SMS message.
val bundle = intent.extras
val msgs: Array<SmsMessage?>
var strMessage = ""
val format = bundle!!.getString("format")
// Retrieve the SMS message received.
// Retrieve the SMS message received.
val pdus = bundle[pdu_type] as Array<*>?
if (pdus != null) {
// Check the Android version.
// Fill the msgs array.
msgs = arrayOfNulls(pdus.size)
for (i in msgs.indices) {
// Check Android version and use appropriate createFromPdu.
// If Android version M or newer:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
msgs[i] = SmsMessage.createFromPdu(pdus[i] as ByteArray, format)
} else {
// If Android version L or older:
msgs[i] = SmsMessage.createFromPdu(pdus[i] as ByteArray)
}
// Build the message to show.
strMessage += "SMS from " + msgs[i]!!.originatingAddress
strMessage += """ :${msgs[i]!!.messageBody}
"""
// Log and display the SMS message.
Log.d(ContentValues.TAG, "onReceive: $strMessage")
//Toast.makeText(context, strMessage, Toast.LENGTH_LONG).show()
}
msg = strMessage
val smsRequest = SMSRequest()
smsRequest.sms = msg
// sendSMS(smsRequest, context)
msgList?.add(msg!!)
var set: MutableSet<String> = mutableSetOf()
val sharedPreferences = context.getSharedPreferences("MySharedPref", Context.MODE_PRIVATE)
if (sharedPreferences!!.getStringSet("smses", null) != null)
{
set = sharedPreferences.getStringSet("smses", null) as MutableSet<String>
}
msgList?.let { set.addAll(it) }
var myEdit: SharedPreferences.Editor? = null
myEdit = sharedPreferences.edit()
myEdit.clear()
myEdit?.putStringSet("smses", set)
myEdit?.apply()
if (mListener != null) {
mListener!!.reloadPage()
}
if (mListener2 != null) {
mListener2!!.reloadPage()
}
}
}
companion object {
var mListener: MessageListener? = null
var mListener2: MessageListener? = null
fun bindListener(listener: MessageListener?) {
mListener = listener
}
fun bindListener2(listener: MessageListener?) {
mListener2 = listener
}
}
}
我已将我的广播接收器注册为:
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true"
>
<intent-filter android:priority="2332412" >
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
此代码在 Android 7 中打开和关闭应用程序时都能正常检测 SMS,但在模拟器和 Android 8 或 9 中不起作用。
我尝试以编程方式注册广播接收器,例如:
fun registerSMSReceiver()
{
val br: BroadcastReceiver = MyReceiver()
val filter = IntentFilter()
filter.addAction("android.provider.Telephony.SMS_RECEIVED")
this.registerReceiver(br, filter)
}
尽管如此,即使应用程序在模拟器和 Android 8 及更高版本中打开,广播接收器也不会被触发。
如何让 Android 8 及更高版本的设备触发我的广播接收器?