如何从特定号码读取短信并以编程方式从收件箱中删除

时间:2012-09-14 06:12:16

标签: android

我使用此代码从特定的电话号码获取短信,然后打开我的应用程序。

工作正常,但在从特定电话号码获取短信后,它不会从收件箱中删除短信。

我正在使用模拟器进行测试请帮忙告诉我代码中的错误是什么? 如何删除特定号码的短信???

public class SmsReceiver extends BroadcastReceiver {

    String specificPhoneNumber = "15555215554";

    public void onReceive(Context context, Intent intent) 
    {
            //---get the SMS message passed in---
            Bundle bundle = intent.getExtras();        
            SmsMessage[] msgs = null;
            String str = "";  

            if (bundle != null)
            {         
                //---retrieve the SMS message received---
                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]);
                    String phNum = msgs[i].getOriginatingAddress();  
                    str += msgs[i].getMessageBody().toString();
             if (specificPhoneNumber.equals(phNum))

            {
                Uri uri = Uri.parse("content://sms/inbox");

                ContentResolver contentResolver = context.getContentResolver();

                String where = "address="+phNum;
                Cursor cursor = contentResolver.query(uri, new String[] { "_id", "thread_id"}, where, null,
                                  null);

                while (cursor.moveToNext()) {

                    long thread_id = cursor.getLong(1);
                    where = "thread_id="+thread_id;
                    Uri thread = Uri.parse("content://sms/inbox");
                    context.getContentResolver().delete(thread, where, null);

                }
                        Intent l = new Intent(context,AgAppMenu.class);                  
                        l.putExtra("msg",str);                   
                        l.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(l);
                    }
                }
            }
     }
}

2 个答案:

答案 0 :(得分:1)

只是不要让来自特定号码的邮件传递到收件箱。为此,请执行以下操作:

  1. 为您的SmsReceiver设置高优先级

    <receiver android:name="SmsReceiver">
        <intent-filter android:priority="999">
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
    </receiver>
    
  2. 使用abortBroadcast()阻止特定邮件传递到收件箱。

答案 1 :(得分:0)

您可以尝试以下更改 -

Uri uri = Uri.parse("content://sms/inbox");

查询 -

String where = "address="+phNum;
Cursor cursor = contentResolver.query(uri, new String[] { "_id", "thread_id"}, where, null,
                  null);

线程ID将是第二个元素 -

long thread_id = cursor.getLong(1);
where = "thread_id="+thread_id;
Uri thread = Uri.parse("content://sms/inbox");
context.getContentResolver().delete(thread, where, null);