1

我已经用发送消息的观察者定义了以下服务。问题是发送消息时,没有调用 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);


    }

}

}

4

1 回答 1

0

要注册ContentObserver发送/接收短信,您需要注册 ContentObserver ,"content://sms"而不是"content://sms/sent"将获取传入或传出短信的逻辑放在以下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您可以检查发送/接收的 SMS 并确保您已在 Manifast 添加 SMS 读取权限:

<uses-permission android:name="android.permission.READ_SMS"/>
于 2012-12-14T05:03:24.027 回答