contentObserver在传出时获取短信号码

时间:2011-04-06 04:16:01

标签: android contentobserver

这是我从默认模拟器发送短信时尝试获取短信号码的代码,但它不起作用。 请结帐并告诉我有关

的信息

Thanx

package com.SMSOberver5;
import android.app.Activity;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

public class SMSOberver5 extends Activity {
        /** Called when the activity is first created. */
    Handler handler = null;
    @Override
        public void onCreate(Bundle savedInstanceState) 
        {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                setReceiver();
        }
     private SMSObserver smsSentObserver = new SMSObserver(new Handler());
    private void setReceiver() {
        this.getContentResolver().registerContentObserver(
                        Uri.parse("content://sms/sent"), true, smsSentObserver);
}
class SMSObserver extends ContentObserver 
{
        public SMSObserver(Handler handler) {
        super(handler);
        }       

                    @Override
                    public void onChange(boolean selfChange) 
                    {
                        try
                        {
                         //startManagingCursor(c);
                         super.onChange(selfChange);
                         System.out.println("body");
                            System.out.println("number");
                        Cursor sms_sent_cursor = SMSOberver5.this.managedQuery(Uri
                                .parse("content://sms/sent"), null, "type=?",
                                new String[] { "2" }, null);
                        int smsEntriesCount = sms_sent_cursor.getCount();
                        String[] body = new String[smsEntriesCount];
                        String[] number = new String[smsEntriesCount];
                        if (sms_sent_cursor.moveToFirst()) 
                        {
                                for (int i = 0; i < smsEntriesCount; i++) 
                                {
                                        body[i] = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndexOrThrow("body")).toString();
                                        number[i] = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndexOrThrow("address")).toString();
                                        sms_sent_cursor.moveToNext();
                                }

                                Toast.makeText(getBaseContext(), "text", Toast.LENGTH_LONG).show();
                            }sms_sent_cursor.close();
                        }catch(Exception e)
                        {}

                    }
        }}

1 个答案:

答案 0 :(得分:2)

请查看以下代码:http://gbandroid.googlecode.com/svn-history/r46/trunk/MobileSpy/src/org/ddth/android/monitor/observer/AndroidSmsWatcher.java

它创建一个ContentObserver,侦听sms表,然后获取传出的短信并获取它们的几个信息。