3

我正在使用 ContentObserver 来检测传出消息。问题是每当发送消息时 onChange() 会触发 3 次。我一直在查看一些关于 SO 的答案,这似乎是因为每次发送消息时都会更新三个表。

幸运的是,每条消息都有一个唯一的 id,但我不知道如何最好地过滤掉具有相同 id 的消息。我尝试了一些不同的方法,但它们似乎都失败了。

有谁知道这样做的好方法?

我的 ContentObserver 看起来像这样

    private class OutgoingSMS extends ContentObserver {
    public OutgoingSMS(Handler handler) {
        super(handler);
    }

    @Override
    public boolean deliverSelfNotifications(){
        return true;
    }

    @Override
    public void onChange(boolean selfChange){
        super.onChange(selfChange);

        Uri smsuri = Uri.parse("content://sms/sent");
        Cursor cursor = mContext.getContentResolver().query(smsuri, null, null, null, null);
        String outgoingSMS = null;

        if (cursor != null && cursor.moveToFirst()){

            try{

                cursor.moveToFirst();
                String type = cursor.getString(cursor.getColumnIndex("type"));

                if (type.equals("2")){

                    outgoingSMS = cursor.getString(cursor.getColumnIndex("address"));
                    String subString = outgoingSMS.substring(0, 3);
                }

            }
            catch (CursorIndexOutOfBoundsException e){
                Log.e(Constants.TAG, "SMSHelper: outgoingSMS", e);
            }
            finally{
                cursor.close();
            }

            //Filter out duplicate ids here.

            if (outgoingSMS != null ){
                long timestamp= getTime();
                DataModel.getInstance(mContext).addLog(outgoingSMS), "sms", timestamp, 0, 1);
                Log.d(Constants.TAG, "SMSHelper: outgoingSMS: " + outgoingSMS);

            }
        }
    }
}
4

0 回答 0