窃听用户发出的短信
用户使用系统自带的短信程序发送短信,程序会通过ContentProvider把短信保存进数据库,并且发出一个数据变化通知,使用ContentObserver对数据变化进行监听,在用户发送短信时,就会被ContentObserver窃听到短信:
注册监听:
getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, new SmsObserver(new Handler()));监听类:
private final class SmsObserver extends ContentObserver { public SmsObserver(Handler handler) { super(handler); } public void onChange(boolean selfChange) {// 查询发送箱中的短信(处于正在发送状态的短信放在发送箱) Cursor cursor = getContentResolver().query( Uri.parse("content://sms/outbox"), null, null, null, null); while (cursor.moveToNext()) { StringBuilder sb = new StringBuilder(); sb.append("_id=").append( cursor.getInt(cursor.getColumnIndex("_id"))); sb.append(",address=").append( cursor.getString(cursor.getColumnIndex("address"))); sb.append(";body=").append( cursor.getString(cursor.getColumnIndex("body"))); sb.append(";time=").append( cursor.getLong(cursor.getColumnIndex("date"))); Log.i("ReceiveSendSMS", sb.toString()); } } }完整代码示例:
package com.example.smslistener; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.database.ContentObserver; import android.database.Cursor; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Uri uri = Uri.parse("content://sms/"); getContentResolver().registerContentObserver(uri, true, new SmsObeserver(new Handler())); } public class SmsObeserver extends ContentObserver { public SmsObeserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { System.out.println("有短信了"); Cursor cursor = getContentResolver().query( Uri.parse("content://sms/outbox"), null, null, null, null); while (cursor.moveToNext()) { StringBuilder sb = new StringBuilder(); sb.append("_id=").append( cursor.getInt(cursor.getColumnIndex("_id"))); sb.append(",address=").append( cursor.getString(cursor.getColumnIndex("address"))); sb.append(",body=").append( cursor.getString(cursor.getColumnIndex("body"))); sb.append(",time=").append( cursor.getLong(cursor.getColumnIndex("date"))); System.out.println(sb.toString()); } super.onChange(selfChange); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }