有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java识别Oreo中的sms号码ID

我的实际代码完美地阻止了调用,但现在我想识别一个传入的SMS号码ID并做一些事情,比如标记为read或其他什么(比如Mediumthisone)

我读过几篇文章和帖子,但都没有达到目的,请再次注意,这段代码可以完美地阻止呼叫,因此我将粘贴与SMS相关的信息

舱单。xml

<uses-permission 安卓:name="安卓.permission.RECEIVE_SMS" />
<uses-permission 安卓:name="安卓.permission.READ_SMS" />

<service 安卓:name=".CallReceiverService" />

广播接收机服务

@Override
public void onCreate() {
    super.onCreate();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);

        Notification notification = new Notification.Builder(this, SERVICE_CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText(this.getResources().getString(R.string.stg_ServiceRunning))
                .setContentIntent(pendingIntent)
                .setCategory(Notification.CATEGORY_CALL)
                .build();

        startForeground(44332255, notification);
    }

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("安卓.intent.action.PHONE_STATE"); // related to call feature, ignore
    intentFilter.addAction("安卓.provider.Telephony.SMS_RECEIVED");
    intentFilter.addAction("Telephony.Sms.Intents.SMS_RECEIVED_ACTION");
    intentFilter.setPriority(1000);
    registerReceiver(callCheckReceiver, intentFilter);
}


private BroadcastReceiver callCheckReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        try {
            if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
                Log.d("Call", "SMS received");
                String smsSender = "";
                if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
                    Log.d("Call", "SMS received");
                    String smsSender = "";
                    for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
                        smsSender = smsMessage.getDisplayOriginatingAddress();
                    }

                    if (!isValidPhoneNumber(smsSender)) {
                        Log.d("Call", "Invalid SMS detected: From " + smsSender);
                    }
                }
                if (!isValidPhoneNumber(smsSender)) {
                    Log.d("Call", "Invalid SMS detected: From " + smsSender);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

};

public static boolean isValidPhoneNumber(String phoneNumber) {
    return 安卓.util.Patterns.PHONE.matcher(phoneNumber).matches();
}

基本上,我在MainActivity中请求权限,在Manifest中设置它们,并在Oreo或更低版本的Android中正确调用的服务中传递FilterContent。目标空气污染指数>=十九,

我不想建立一个应用程序来管理短信,我只想截取号码ID并做一些事情。有人能提供建议吗


共 (1) 个答案

  1. # 1 楼答案

    你需要的是SMS Retriever API

    如果你想检测短信,你可以简单地使用

        SmsRetrieverClient client = SmsRetriever.getClient(this /* context */);
        Task<Void> task = client.startSmsRetriever();
        task.addOnSuccessListener(new OnSuccessListener<Void>()
        {
            @Override
            public void onSuccess(Void aVoid)
            {
                // Successfully started retriever, expect broadcast intent
                // ...
            }
        });
    
        task.addOnFailureListener(new OnFailureListener()
        {
            @Override
            public void onFailure(@NonNull Exception e)
            {
                // Failed to start retriever, inspect Exception for more details
                // ...
            }
        });
    

    在AndroidManifest中。xml只需添加接收者

        <receiver
            android:name=".custom.SMSBroadcastReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
            </intent-filter>
        </receiver>
    

    在接收器中,您可以对检测到的消息执行任何操作

        public class SMSBroadcastReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction()))
            {
                Bundle extras = intent.getExtras();
                Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
                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 for SMS authenticity.
    
    
    
    
                        break;
                    case CommonStatusCodes.TIMEOUT:
                        // Waiting for SMS timed out (5 minutes)
                        // Handle the error ...
                        break;
    
                }
            }
        }
    }
    

    需要注意的是,SMSRetrieverClient默认超时为5分钟

    要创建可检测短信,请遵循SMS Creator for Google