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

8

我知道已经有很多类似的问题了,而且我已经尝试过所有能找到的方法,但是我依然无法让它正常工作。

我的问题是 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>

在我的主活动中,我尝试了多种方法来实现这一目标,但目前只有以下方法:
var smsReceiver = SMSReceiver()

非常感谢您能提供任何有用的提示,如果代码示例可以用 Kotlin 编写的话就更好了。


用户在接收/阅读/发送短信之前,需要先授予运行时权限。这意味着您缺少运行时权限检查。 - mmmatey
提醒一下 - 除非您的应用程序主要功能是处理短信,否则在Play商店上不再允许使用SMS权限。 - Pawel
是的,我有运行时权限,只是忘记在这里添加了。 此外,这是一个仅供个人使用的应用程序,没有计划添加到Play商店。 - Anders
你是否使用 context.registerReceiver() 注册了接收器? - Choim
我在MainActivity尝试了这个,但它没有产生任何影响。我将其删除了,因为我认为清单中的intent-filter会完成同样的事情。这仍然需要吗? - Anders
2个回答

1
我曾遇到相同的问题,实际上这只是权限问题,即使我请求了所有权限并一次性允许了所有权限,仍然有一些权限没有被授予,请通过应用调试标签确保您已经允许了所有权限。
我使用了以下方法:
private val appPermission = arrayOf(Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_MMS)

在 onCreate 中
// 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.
            }
        }
    }

0

不要在onReceive()函数内部使用if检查

class SMSReceiver : BroadcastReceiver() {
 override fun onReceive(context: Context, intent: Intent) {
  Log.d("BroadcastReceiver", "onReceive")

    Log.d("BroadcastReceiver", "SMS received")
    // Will do stuff with message here

}

谢谢,但是即使有if检查,我仍然应该能够获得第一条日志消息,但我没有收到它。 - Anders

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接