检测传入的 SMS 消息
Posted
技术标签:
【中文标题】检测传入的 SMS 消息【英文标题】:Detecting incoming SMS messages 【发布时间】:2020-03-06 14:16:39 【问题描述】:在我的 android 代码中,我试图。下面的代码自 2 年以来一直在工作,但现在它停止工作了。我错过了哪些更新?
public class SmsListener extends BroadcastReceiver
private String msgBody;
private SharedPreferences preferences;
@Override
public void onReceive(Context context, Intent intent)
// TODO Auto-generated method stub
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
Toast.makeText(context,"message received",Toast.LENGTH_SHORT).show();
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null)
//---retrieve the SMS message received---
try
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++)
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
msgBody = msgs[i].getMessageBody();
MainActivity.handleMessage(msgBody);
Toast.makeText(context,"message is:"+msgBody,Toast.LENGTH_SHORT).show();
catch(Exception e)
Log.d("Exception caught",e.getMessage());
在我的主要活动中,我请求用户许可,并使用 SMS 接收器如下:
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Updated///////////////////////////////////////////////////////////////////////////////////
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
requestSmsPermission();
else
smsListener = new SmsListener();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsListener, intentFilter);
///////Updated///////////////////////////////////////////////////////////////////////////////////
private void requestSmsPermission()
String permission = Manifest.permission.RECEIVE_SMS;
int grant = ContextCompat.checkSelfPermission(this, permission);
if ( grant != PackageManager.PERMISSION_GRANTED)
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, 1);
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1)
smsListener = new SmsListener();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsListener, intentFilter);
我的 Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.zaidalmahmoud.expenseless">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".GraphActivity"></activity>
<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=".SmsListener"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity android:name=".DetailedExpenseActivity" />
</application>
</manifest>
收到短信后,我的 android 应用程序没有检测到它,但它没有崩溃或显示任何内容。为什么?谢谢。
注意:我对接收带有验证码的短信不感兴趣。我希望我的应用程序能够捕获任何传入的 SMS。
【问题讨论】:
【参考方案1】:Android 应用需要 SMS 接收/读取权限才能检索 SMS 内容。 Google 引入了 SMS Retriever API,此 API 允许在您的应用程序中无需 SMS 权限即可检索 OTP。
为 SMS Retriever API 添加这些依赖项
implementation 'com.google.android.gms:play-services-base:16.0.1'
implementation 'com.google.android.gms:play-services-identity:16.0.0'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.android.gms:play-services-auth-api-phone:16.0.0'
然后创建如下界面:
public interface OnNewMessageListener
void onNewMessageReceived(String activationCode);
然后,创建一个广播接收器来接收短信:
public class SmsBroadcastReceiver extends BroadcastReceiver
OnNewMessageListener onNewMessageListener;
public SmsBroadcastReceiver()
public SmsBroadcastReceiver(OnNewMessageListener onNewMessageListener)
this.onNewMessageListener = onNewMessageListener;
@Override
public void onReceive(Context context, Intent intent)
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction()))
Bundle extras = intent.getExtras();
if (extras != null)
Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
if (status != null)
switch (status.getStatusCode())
case CommonStatusCodes.SUCCESS:
// Get SMS message contents
String message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
// Extract one-time code from the message and complete verification
// by sending the code back to your server.
if (!TextUtils.isEmpty(message))
String activationCode = null;
Pattern p = Pattern.compile("your pattern like \\b\\d4\\b");
Matcher m = p.matcher(message);
if (m.find())
activationCode = (m.group(0)); // The matched substring
if (onNewMessageListener != null && !TextUtils.isEmpty(activationCode))
onNewMessageListener.onNewMessageReceived(activationCode);
break;
case CommonStatusCodes.TIMEOUT:
// Waiting for SMS timed out (5 minutes)
// Handle the error ...
break;
在您的AndroidManifest
声明广播接收器:
<receiver
android:name=".SmsBroadcastReceiver"
android:exported="true"
tools:ignore="ExportedReceiver">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
</intent-filter>
</receiver>
在您的活动中添加以下代码:
private SmsBroadcastReceiver smsListener;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get an instance of SmsRetrieverClient, used to start listening for a matching
// SMS message.
SmsRetrieverClient client = SmsRetriever.getClient(Objects.requireNonNull(getContext()) /* context */);
// Starts SmsRetriever, which waits for ONE matching SMS message until timeout
// (5 minutes). The matching SMS message will be sent via a Broadcast Intent with
// action SmsRetriever#SMS_RETRIEVED_ACTION.
Task<Void> task = client.startSmsRetriever();
// Listen for success/failure of the start Task. If in a background thread, this
// can be made blocking using Tasks.await(task, [timeout]);
task.addOnSuccessListener(aVoid ->
// Successfully started retriever, expect broadcast intent
// ...
);
task.addOnFailureListener(e ->
// Failed to start retriever, inspect Exception for more details
// ...
);
OnNewMessageListener onNewMessageListener = activationCode ->
if (!TextUtils.isEmpty(activationCode))
editText.setText(String.valueOf(activationCode));
;
smsListener = new SmsBroadcastReceiver(onNewMessageListener);
if (getContext() != null)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
getContext().registerReceiver(smsListener, new IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION));
@Override
public void onStop()
super.onStop();
try
if (getContext() != null && smsListener != null)
getContext().unregisterReceiver(smsListener);
smsListener = null;
catch (Exception ignored)
你的短信应该是这样的:
<#> Use 123456 as your verification code
FC+7qAH5AZu
消息必须:
不超过 140 个字节 以前缀<#>
开头
包含客户端发送回您的服务器以完成验证流程的一次性代码 (see Generating a one-time code)
以 11 个字符的哈希字符串结尾,用于标识您的应用 (see Computing your app’s hash string)
有关更多信息,请参阅link。
更新
看到这个link。
编辑
将您的活动更改为:
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
requestSmsPermission();
else
smsListener = new SmsListener();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsListener, intentFilter);
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1)
smsListener= new SmsListener();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsListener, intentFilter);
更新
将您的 BroadcastReceiver
更改为:
public class SmsListener extends BroadcastReceiver
private String msgBody;
private SharedPreferences preferences;
@Override
public void onReceive(Context context, Intent intent)
// TODO Auto-generated method stub
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
Toast.makeText(context, "message received", Toast.LENGTH_SHORT).show();
Bundle bundle = intent.getExtras();
try
if (bundle != null)
final Object[] pdus = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdus.length; i++)
SmsMessage smsMessage;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i], bundle.getString("format"));
else smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
msg_from = smsMessage.getDisplayOriginatingAddress();
msgBody = smsMessage.getMessageBody();
MainActivity.handleMessage(msgBody);
Toast.makeText(context, "message is:" + msgBody, Toast.LENGTH_SHORT).show();
catch (Exception e)
Log.d("Exception caught", e.getMessage());
【讨论】:
感谢您的帮助,但我不想检测带有验证码的短信。我的问题是关于捕捉任何短信。事实上,我对一种完全不同的 SMS 很感兴趣。 谢谢,我尝试重用其中的一些代码,但我看不出我的代码和他的代码有什么不同,而且我的应用程序没有任何变化。未检测到短信。我需要知道我的错误到底在哪里。 嗨。我想告诉你,它只工作了一次,然后就停止工作了,我不知道为什么。我把你的代码放在最后一次编辑中 @TravelingSalesman 我认为您的问题在于: MainActivity.handleMessage(msgBody);使用接口更新数据或将数据发送到主要活动。 我没有改变任何东西(可能除了一条祝酒消息),现在它又可以工作了。我会继续测试它,并让你知道。但我非常怀疑 MainActivity.handleMessage(msgBody) 中是否存在问题,因为我对其进行了很好的测试,或者至少因为现在它可以正常工作而没有任何问题。【参考方案2】:在您的 android 清单文件中声明 SMS 读取和接收权限:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
那么我们需要一个 SMS Receiver 如下:
class SMSReceiver : BroadcastReceiver()
override fun onReceive(context: Context, intent: Intent?)
if (intent != null && intent.action != null && intent.action!!.equals("android.provider.Telephony.SMS_RECEIVED", ignoreCase = true))
val bundle = intent.extras
if (bundle != null)
val sms = bundle.get(SMS_BUNDLE) as Array<Any>?
val smsMsg = StringBuilder()
var smsMessage: SmsMessage
if (sms != null)
for (sm in sms)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
val format = bundle.getString("format")
smsMessage = SmsMessage.createFromPdu(sm as ByteArray, format)
else
smsMessage = SmsMessage.createFromPdu(sm as ByteArray)
val msgBody = smsMessage.messageBody.toString()
val msgAddress = smsMessage.originatingAddress
smsMsg.append("SMS from : ").append(msgAddress).append("\n")
smsMsg.append(msgBody).append("\n")
sendBroadcast(smsMsg.toString())
private fun sendBroadcast(smsMSG: String)
val broadcastIntent = Intent()
broadcastIntent.action = AppConstants.mBroadcastSMSUpdateAction
broadcastIntent.putExtra(AppConstants.message, smsMSG)
EventBus.getDefault().post(EventIntent(broadcastIntent))
companion object
val SMS_BUNDLE = "pdus"
您可以将收到的短信信息广播到您的 MainActivity。
然后你需要在你的 manifest 文件中声明 SMS Broadcast 接收器如下:
<receiver
android:name=".SMSReceiver"
android:enabled="true">
<intent-filter android:priority="2147483647">
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
在 MainActivity 中启动应用程序后,您需要通过以下方式检查 SMS 权限:
Manifest.permission.READ_SMS,
Manifest.permission.RECEIVE_SMS
您可以为此使用内置的 android 权限模块或 RxPermission:
val rxPermissions = RxPermissions(this)
rxPermissions.request(
Manifest.permission.READ_SMS,
Manifest.permission.RECEIVE_SMS)
.subscribe(object : Observer<Boolean>
override fun onNext(t: Boolean)
if (t)
else
Toast.makeText(activity, getString(R.string.permission_request_denied), Toast.LENGTH_LONG).show()
override fun onSubscribe(d: Disposable)
override fun onError(e: Throwable)
override fun onComplete()
)
【讨论】:
您使用的是什么语言?那绝对不是java语法 @Traveling Salesman 这是 Kotlin 用于 Android 应用程序开发的新语言 不幸的是,我正在使用带有 Java 语法的 Android Studio。以上是关于检测传入的 SMS 消息的主要内容,如果未能解决你的问题,请参考以下文章
如何检测用户卸载的iOS App?我需要推送严肃的通知。我不想失去它