发送短信时未调用ContentObserver的Onchange方法

时间:2012-12-14 04:41:17

标签: android android-service android-contentresolver

我已经使用已发送消息的观察者定义了以下服务。问题是,当发送消息时,onChange()方法没有被调用,有人请告诉我为什么?

感谢

public class countService extends Service {

    ContentResolver contentResolver;

    MyContentObserver Observer;

    Uri sms_content = Uri.parse("content://sms/sent");

    public Cursor cursor;

    @Override
    public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    contentResolver = getBaseContext().getContentResolver();
    Observer = new MyContentObserver();
    contentResolver.registerContentObserver(sms_content, true, Observer);
    super.onCreate();

}

private class MyContentObserver extends ContentObserver {

    public MyContentObserver() {
        super(null);
    }   

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Log.d("BOOOOOOOOOOOOOOOOOO", "c");
        Cursor cursor = contentResolver.query(sms_content, null, null,
                null, null);
        cursor.moveToFirst();
        String type = cursor.getString(cursor.getColumnIndex("type"));
        Log.d("THEMESSAGE", type);


    }

}

}

1 个答案:

答案 0 :(得分:0)

要为发送/接收的短信注册ContentObserver,您需要为"content://sms"而不是"content://sms/sent"注册ContentObserver,并将您的逻辑用于获取onChange内的传入或传出短信ContentObserver的方法:

将您的服务onCreate()更改为:

@Override
public void onCreate() {
// TODO Auto-generated method stub
contentResolver = getBaseContext().getContentResolver();
Observer = new MyContentObserver();
contentResolver.registerContentObserver(
                  Uri.parse("content://sms"),true, Observer);
super.onCreate();

} 

并在MyContentObserver ContentObserver中,您可以检查发送/接收的短信,并确保您在Manifast中添加了SMS READ权限:

<uses-permission android:name="android.permission.READ_SMS"/>