Android Kotlin - 如何检测和读取收到的短信

标签 android kotlin sms

我知道有很多这样的问题已经浮出水面,我已经尝试了所有我能遇到的问题,但我仍然无法让它发挥作用。

我的问题是 BroadcastReceiver onReceive 似乎从未被调用过。 我的代码如下:

class SMSReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
    Log.d("BroadcastReceiver", "onReceive")
    if (intent.action == Telephony.Sms.Intents.SMS_RECEIVED_ACTION) {
        Log.d("BroadcastReceiver", "SMS received")
        // Will do stuff with message here
    }
}

日志消息永远不会显示。

AndroidManifest.xml

<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS"/>
<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/Theme.AppCompat.Light.NoActionBar">
    <activity android:name=".main.MainActivity" 
    android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" 
            />
        </intent-filter>
    </activity>
    <activity android:name=".setup.SetupActivity" 
     android:screenOrientation="portrait">
    </activity>
    <receiver
            android:name=".SMSReceiver"
            android:enabled="true"
            android:exported="true">
        <intent-filter android:priority="1000">
            <action 
         android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
</application>

在我的 mainActivity 中,我尝试了多种方法来实现这一点,但目前只有:

var smsReceiver = SMSReceiver()

我很感激我能得到的任何提示,如果有任何代码示例是用 Kotlin 编写的,那就太好了。 :)

最佳答案

我遇到了同样的问题,实际上这只是权限问题,即使我请求所有权限并同时允许所有权限,仍然有一些权限没有被授予,通过应用调试标签确保您拥有所有允许的权限。

我用了下面的

private val appPermission = arrayOf(Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_MMS)

在创建中

// Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.RECEIVE_SMS)
            != PackageManager.PERMISSION_GRANTED) {

        // Permission is not granted
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.RECEIVE_SMS)) {
            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    arrayOf(Manifest.permission.RECEIVE_SMS),
                    PERMISSIONS_RECEIVE_SMS)

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    } else {
        // Permission has already been granted
    }

这里是onRequestPermission

override fun onRequestPermissionsResult(requestCode: Int,
                                            permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            PERMISSIONS_RECEIVE_SMS -> {
                // If request is cancelled, the result arrays are empty.
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Log.d(TAG, "PERMISSIONS_RECEIVE_SMS permission granted")

                    // Here, thisActivity is the current activity
                    if (ContextCompat.checkSelfPermission(this,
                                    Manifest.permission.READ_SMS)
                            != PackageManager.PERMISSION_GRANTED) {

                        // Permission is not granted
                        // Should we show an explanation?
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                                        Manifest.permission.READ_SMS)) {
                            // Show an explanation to the user *asynchronously* -- don't block
                            // this thread waiting for the user's response! After the user
                            // sees the explanation, try again to request the permission.
                        } else {
                            // No explanation needed, we can request the permission.
                            ActivityCompat.requestPermissions(this,
                                    arrayOf(Manifest.permission.READ_SMS),
                                    PERMISSIONS_REQUEST_READ_SMS)

                            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                            // app-defined int constant. The callback method gets the
                            // result of the request.
                        }
                    } else {
                        // Permission has already been granted
                    }


                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Log.d(TAG, "PERMISSIONS_RECEIVE_SMS permission denied")
                }
                return
            }

            PERMISSIONS_REQUEST_READ_SMS -> {
                // If request is cancelled, the result arrays are empty.
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Log.d(TAG, "PERMISSIONS_REQUEST_READ_SMS permission granted")
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Log.d(TAG, "PERMISSIONS_REQUEST_READ_SMS permission denied")
                }
                return
            }

            // Add other 'when' lines to check for other
            // permissions this app might request.
            else -> {
                // Ignore all other requests.
            }
        }
    }

关于Android Kotlin - 如何检测和读取收到的短信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54972505/

相关文章:

java - 如何使用 AT 命令代替 Java Wireless Messaging API (WMA),将 SMS 发送到 PORT

java - 在 Android Studio 中运行 YouTube Activity 时出错

java - 使用谓词的通用集合过滤

Kotlin 编译器错误 : Type mismatch. 必需:CapturedType(out A) 找到:A

linux - 在 asterisk sip 上接收短信

php - 在 PHP 中如何使用两个 header 位置

android - 在 Android 中获取最大 OpenGL ES 2.0 纹理大小限制

javascript - Android WebView Javascript 未启用

android - ListView 中的按钮

android - 自定义导航图标不显示//Jetpack Navigation