我尝试使用ContentObserver
为外发邮件制作短信观察员。下面的代码完美无缺,但每当我通过向同事发送短信来测试时,我都会得到两次输出。
观察者在服务中注册,如下所示:
SentSMSObserver sentSMSObserver = new SentSMSObserver(new Handler(), this);
getContentResolver().registerContentObserver(sentSMSObserver.CONTENT_SMS_URI, true, sentSMSObserver);
每当我发送一个textmessage到我自己的号码时,我只得到一次输出,这真的很奇怪。作为一个服务是一个单身人士(据我的研究让我相信),它是不太可能的,我的观察者有第二个实例。
public class SentSMSObserver extends ContentObserver {
private static final String CONTENT_SMS = "content://sms";
public final Uri CONTENT_SMS_URI = Uri.parse(CONTENT_SMS);
private Context context;
public SentSMSObserver(Handler handler, Context context) {
super(handler);
this.context = context;
}
@Override
public void onChange(boolean selfChange) {
Cursor cursor = context.getContentResolver().query(CONTENT_SMS_URI, null, null, null, null);
try {
if (cursor.moveToNext()) {
String protocol = cursor.getString(cursor.getColumnIndex("protocol"));
int type = cursor.getInt(cursor.getColumnIndex("type"));
if (protocol != null || type != Telephony.TextBasedSmsColumns.MESSAGE_TYPE_SENT) {
return;
}
String to = cursor.getString(cursor.getColumnIndex("address"));
Date now = new Date(cursor.getLong(cursor.getColumnIndex("date")));
String message = cursor.getString(cursor.getColumnIndex("body"));
Log.e("sentmessage", to + " - " + now + " - " + message);
}
} finally {
cursor.close();
}
}
}
logcat的:
08-11 14:25:14.292 12574-12574/com.androidfun.smstest E/sentmessage﹕ +(deleted phone n°) - Mon Aug 11 14:25:10 CEST 2014 - Test
08-11 14:25:18.306 12574-12574/com.androidfun.smstest E/sentmessage﹕ +(deleted phone n°) - Mon Aug 11 14:25:10 CEST 2014 - Test
答案 0 :(得分:0)
在某些情况下,已发送的消息也会使用“已发送确认”更新,甚至还会更新“发送确认”。发送给自己,你可能没有得到“发送确认”,因为它一步发送并确认。
见这里的帖子: