android开发ContentObserver 监控短信的实现

        因为可以访问SMS收件箱,所以将能够访问其他与SMS 相关的文件夹,比如已发送文件夹或草稿箱文件夹。访问收件箱与访问其它文件夹的唯一区别就在于所指定的 URI。例如,可以对 content://smsnt 执行查询来访问已发送的文件夹。以下是完整的 SMS文件夹列表和每个文件夹的URI。

所有文件夹:content://sms/all
收件箱:content://sms/inbox
已发送:content://smsnt
草稿:content://sms/draft
发件箱:content://sms/outbox
发送失败:content://sms/failed
排队消息:content://sms/queued
未送达:content://sms/undelivered
对话:content://sms/conversations

//ContentObserver 短信监控类
class SmsObserver extends ContentObserver {
 private ContentResolver resolver;
 private Context mContext;
 /**
 * Creates a content observer.
 *
 * @param handler The handler to run {@link #onChange} on, or null if none.
 */
 public SmsObserver(Handler handler,ContentResolver rl,Context ctx) {
 super(handler);
 resolver = rl;
 mContext = ctx;
 }

 public void onChange(boolean selfChange) {

 Cursor cursor = resolver.query(Uri.parse("content://sms/inbox"),null,null,null,null);
 String fromPhone = "",subject = "",body = "",time = "";
 while (cursor.moveToNext()){
 fromPhone = cursor.getString(cursor.getColumnIndex("address"));
 subject = cursor.getString(cursor.getColumnIndex("subject"));
 body = cursor.getString(cursor.getColumnIndex("body"));
 time = cursor.getString(cursor.getColumnIndex("date"));
 }
 Log.i("LOG", fromPhone);
 //Log.i("LOG", subject);
 Log.i("LOG", body);
 Log.i("LOG",time);

 Toast.makeText(mContext,body,Toast.LENGTH_LONG).show();


 }

}


在Oncreate中注册监听器

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        init(this);
        getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, new SmsObserver(new Handler(), getContentResolver(), this));
    }

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |