http://www.jb51.net/article/95503.htm
短信的接收
对于短信息的接收相对来说会复杂一些。而复杂的原因大家也应该比较容易理解——接收是不可控制的。也就是说我们的手机根本不知道什么时候会有一条短信息过来。由于过于被动,Android的机制中就出现了一个强大到让你佩服的东西,那就是广播接收者。我们注册一个广播接收者,然后让这个广播接收者时时刻刻地去监听短信息是否到达的这一事件。就这样,被动触发事件完美地解决了。下面让我们来看看这个过程:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 | public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( "android.provider.Telephony.SMS_RECEIVED" )) { Bundle bundle = intent.getExtras(); Object messages[] = (Object[]) bundle.get( "pdus" ); SmsMessage smsMessage[] = new SmsMessage[messages.length]; for ( int n = 0 ; n < messages.length; n++) { smsMessage[n] = SmsMessage.createFromPdu(( byte []) messages[n]); } showToast(context, "短信内容: " + smsMessage[ 0 ].getMessageBody()); } } |
添加权限:
?
1 2 | < uses-permission android:name = "android.permission.RECEIVE_SMS" /> < uses-permission android:name = "android.permission.READ_SMS" /> |
以及在manifest中进行一个静态注册:
?
1 2 3 4 | < receiver android:name = ".broadcast.SMSReceiver" > < action android:name = "android.provider.Telephony.SMS_RECEIVED" /> </ intent-filter > </ receiver > |
短信的拦截
在能够接收短信的基础上做一个短信拦截倒是简单了许多。因为能够接收,所以我只要成为第一个接收的人,并把接收到的短信不再向下传播,这就完成了短信息的拦截了。
提高优先权:
![](https://i-blog.csdnimg.cn/blog_migrate/50c0cc9e903ed3247441665dbee3fd10.png)
阻断传播:
![](https://i-blog.csdnimg.cn/blog_migrate/8f89554b10609cedcff18beb36f35d3f.png)
短信的删除
以下是短信相关的协议
content://sms/inbox 收件箱
content://sms/sent 已发送
content://sms/draft 草稿
content://sms/outbox 发件箱
content://sms/failed 发送失败
content://sms/queued 待发送列表
就拿收件箱为例实现短信的删除代码如下:
实现删除短信中包含某一字段的短信:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public void deleteSMS(String smscontent) { ContentResolver CR = getContentResolver(); try { // 准备系统短信收信箱的uri地址 Uri uri = Uri.parse( "content://sms/inbox" ); // 查询收信箱里所有的短信 Cursor cursor = CR.query(uri, new String[] { "_id" , "address" , "person" , "body" , "date" , "type" }, null , null , null ); int count = cursor.getCount(); if (count > 0 ) { while (cursor.moveToNext()) { String body = cursor.getString(cursor.getColumnIndex( "body" )); // 获取信息内容 if (body.contains(smscontent)) { int id = cursor.getInt(cursor.getColumnIndex( "_id" )); CR.delete(Uri.parse( "content://sms" ), "_id=" + id, null ); } } } } catch (Exception e) { Log.v( "e" , e.getMessage()); } } |
根据最新的短信实现删除信息(删除的对象是联系人而非短信)
?
1 2 3 4 5 6 7 8 9 10 11 12 | public void deleteSMS() { ContentResolver CR = getContentResolver(); // 查询收信箱里所有的短信 Cursor cursor = CR.query(Uri.parse( "content://sms/inbox" ), new String[] { "_id" , "thread_id" }, null , null , null ); if (cursor != null ) { cursor.moveToFirst(); int a = cursor.getCount(); int b = cursor.getColumnCount(); long threadId = cursor.getLong( 1 ); CR.delete(Uri.parse( "content://sms/conversations/" + threadId), null , null ); } } |