这种方法是通过监控手机的短信数据库content://sms实现的。
1.实现Observer
public class SMSObserver extends ContentObserver
{
...
@Override
public void onChange(boolean selfChange)
{
Log.i(TAG, "onChange : " + selfChange + "; " + MAX_ID + "; " + SELECTION);
super.onChange(selfChange);
try {
Cursor cursor = mResolver.query(SMS.CONTENT_URI, PROJECTION, String.format(SELECTION, MAX_ID), null, null);
Log.i(TAG,"cursor numbers :"+ cursor.getCount() );
int id, type, protocol;
Long thread_id;
String phone, body;
Message message;
MessageItem item;
int iter = ;
boolean hasDone = false;
while (cursor.moveToNext())
{
id = cursor.getInt(COLUMN_INDEX_ID);
thread_id = cursor.getLong(COLUMN_THREAD_ID);
type = cursor.getInt(COLUMN_INDEX_TYPE);
phone = cursor.getString(COLUMN_INDEX_PHONE);
body = cursor.getString(COLUMN_INDEX_BODY);
protocol = cursor.getInt(COLUMN_INDEX_PROTOCOL);
Log.i(TAG,"content : "+body+" protocol : "+ protocol);
if (hasDone)
{
MAX_ID = id;
break;
}
Log.i(TAG," body.startsWith : "+ body.startsWith(SMS.FILTER));
if (protocol == SMS.PROTOCOL_SMS && body != null
&& body.startsWith(SMS.FILTER))
{//本示例程序是把以SMS.FILTER打头的短信视为垃圾短信
hasDone = true;
item = new MessageItem();
item.setId(id);
item.setThreadId(thread_id);
item.setType(type);
item.setPhone(phone);
item.setBody(body);
item.setProtocol(protocol);
message = new Message();
message.obj = item;
mHandler.sendMessage(message);
Log.i(TAG,"send to handler;");
}
else
{
if (id > MAX_ID)
MAX_ID = id;
}
if (iter > MAX_NUMS)
break;
iter++;
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.实现Handler
public class SMSHandler extends Handler
{
public static final String TAG = "SMSHandler";
private Context mContext;
public SMSHandler(Context context)
{
super();
this.mContext = context;
}
public void handleMessage(Message message)
{
Log.i(TAG, "handleMessage: " + message);
MessageItem item = (MessageItem) message.obj;
//delete the sms
Uri uri = ContentUris.withAppendedId(Uri.parse(SMS.CONTENT_URI+"/conversations"), item.getThreadId());
int iResult=mContext.getContentResolver().delete(uri, "_id="+item.getId(), null);
Log.i(TAG, "delete sms item: " + uri.toString()+"(id="+item.getId()+"), result: "+iResult);
}
}
注:
- 本方法同样仅适用于Android4.3及以下版本
- 在Android4.4及以上版本,如果不为短信的default app,则仅仅能探测到垃圾短信,但在删除垃圾短信时会失败(除非通过安卓的AppOps给本软件赋予了短信写的权限)。