短信接收器Android Studio Kotlin

问题描述

我想做一个SMS接收器。我的应用程序应该会收到一条短信,并显示一条消息“已检测到短信”。

我上了MyReciever.kt类

  package com.example.messageresender

    import android.content.broadcastReceiver
    import android.content.Context
    import android.content.Intent
    import android.telephony.SmsMessage
    import android.widget.Toast


    class MyReceiver : broadcastReceiver() {

        override fun onReceive(context: Context,intent: Intent) {

            Toast.makeText(context,"sms detected",Toast.LENGTH_SHORT).show()


        }
    }

添加到android清单

<receiver
            android:name=".MyReceiver"
            <intent-filter android:priority="9999">
                <action android:name="android.provider.telephony.SMS_RECEIVED"></action>
            </intent-filter>
        </receiver>

androidManifest.xml现在看起来像这样

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.messageresender">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:fullBackupContent="@xml/backup_descriptor">


        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".MyReceiver"
            <intent-filter android:priority="9999">
                <action android:name="android.provider.telephony.SMS_RECEIVED"></action>
            </intent-filter>
        </receiver>
    </application>

</manifest>

,它根本不起作用。当我将SMS发送到仿真的android设备时,未显示“检测到SMS”消息。我在android 7.1(不是oreo)上进行了尝试,因为互联网上有人说broadCastReciever无法在android oreo上运行,因为我应该注册它,但是我做不到,因为当我这样做时,我的应用程序崩溃了。但这仍然行不通

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            var syReceiver = MyReceiver()
            val intentFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
            intentFilter.addAction(Telephony.Sms.Intents.DATA_SMS_RECEIVED_ACTION)
            this.registerReceiver(syReceiver,intentFilter)
        }

请帮助我。我想发短信!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)