You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何拦截Android默认收件箱的短信——基于BroadcastReceiver

How to Block Specific SMS from Entering Default Android Inbox

Hey there! Let's get your SMS-based chat app sorted so that messages from your target number (77100) don't end up in the default system inbox. I'll walk through the issues in your current code and fix them step by step.

Key Issues in Your Current Setup

  1. Incorrect abortBroadcast() placement: You're calling it unconditionally, which would block all SMS from reaching the inbox—even those not from 77100.
  2. Unnecessary broadcast actions: SMS_DELIVER and SMS_DELIVER_ACTION are only for the default SMS app; your app can't receive these anyway, so they're just cluttering your manifest.
  3. Permission handling (for newer Android versions): You need to request dangerous permissions at runtime for Android 6.0+.

Step 1: Fix the Broadcast Receiver Manifest Configuration

Update your receiver to only include relevant actions and keep the high priority (999 is the max for non-default SMS apps):

<receiver android:name=".IncomingSms" android:permission="android.permission.BROADCAST_SMS">
    <intent-filter android:priority="999">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

Also, make sure you've declared the required permissions in your manifest:

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

Step 2: Correct the SMS Receiver Code

Adjust the code to only block broadcasts when you process a message from 77100. We'll add a flag to track if we need to abort the broadcast:

public void onReceive(Context context, Intent intent) { 
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY); 
    this.intent = new Intent(BROADCAST_ACTION); 
    this.context = context; 
    chatlogDBAdapter = new ChatlogDBAdapter(context); 
    final Bundle bundle = intent.getExtras(); 
    boolean shouldAbortBroadcast = false;

    try { 
        if (bundle != null) { 
            final Object[] pdusObj = (Object[]) bundle.get("pdus"); 
            for (int i = 0; i < pdusObj.length; i++) { 
                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]); 
                String senderNum = currentMessage.getDisplayOriginatingAddress(); 

                if(senderNum.equals("77100")){ 
                    String message = currentMessage.getDisplayMessageBody(); 
                    Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message); 

                    String timestamp = String.valueOf(System.currentTimeMillis()); 
                    String[] messagearray = message.split(",", -1); 
                    String username = messagearray[0]; 
                    String messagebody = messagearray[1]; 

                    chatlogDBAdapter.addMessage(username, username, "username", messagebody, timestamp); 
                    msgusername = username; 

                    handler.removeCallbacks(sendUpdatesToUI); 
                    handler.postDelayed(sendUpdatesToUI, 10); 

                    shouldAbortBroadcast = true; // Mark to block this broadcast
                } 
            } 

            // Only abort if we processed a message from the target number
            if(shouldAbortBroadcast){
                abortBroadcast();
            }
            return; 
        } 
    } catch (Exception e) { 
        Log.e("SmsReceiver", "Exception in smsReceiver: " + e.getMessage()); 
    } 
}

Step 3: Add Runtime Permission Handling (Android 6.0+)

Since your compile SDK is 27, you need to request SMS permissions at runtime for devices running Android 6.0 (API 23) or higher. Add this to your main activity:

private static final int SMS_PERMISSION_REQUEST_CODE = 100;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkAndRequestSmsPermissions();
    }
}

private void checkAndRequestSmsPermissions() {
    if (checkSelfPermission(Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED ||
            checkSelfPermission(Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(
                new String[]{Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS},
                SMS_PERMISSION_REQUEST_CODE
        );
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == SMS_PERMISSION_REQUEST_CODE) {
        if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "SMS permissions are required for the app to work", Toast.LENGTH_LONG).show();
        }
    }
}

Why This Works

  • Priority: Your receiver uses the maximum allowed priority (999) for non-default SMS apps, ensuring it gets processed before the system's inbox receiver.
  • Conditional Broadcast Abort: We only call abortBroadcast() when we handle a message from 77100, so other SMS still reach the default inbox.
  • Proper Permissions: Runtime permission checks ensure your app can receive SMS on newer Android versions.

内容的提问来源于stack exchange,提问作者Suresh Peiris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:08:05