Sms ContentObserver onChange() fires multiple times

后端 未结 4 1806
春和景丽
春和景丽 2020-12-09 13:36

I know this question has been asked multiple times, but nobody has been able to come up with a working answer from what I have seen.

Im working on an app to intercep

4条回答
  •  悲&欢浪女
    2020-12-09 13:42

    here is my code, it works fine for me

    public class SmsObserver extends ContentObserver {  
        private Context context;
        private static int initialPos;
        private static final String TAG = "SMSContentObserver";
        private static final Uri uriSMS = Uri.parse("content://sms/sent");
    
        public SmsObserver(Handler handler, Context ctx) {
            super(handler);
            context = ctx;
            initialPos = getLastMsgId();
    
        }
    
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            queryLastSentSMS();
        }
    
        public int getLastMsgId() {
    
            Cursor cur = context.getContentResolver().query(uriSMS, null, null, null, null);
            cur.moveToFirst();
            int lastMsgId = cur.getInt(cur.getColumnIndex("_id"));
            Log.i(TAG, "Last sent message id: " + String.valueOf(lastMsgId));
            return lastMsgId;
        }
    
        protected void queryLastSentSMS() {
    
            new Thread(new Runnable() {
    
                @Override
                public void run() {
                    Cursor cur =
                        context.getContentResolver().query(uriSMS, null, null, null, null);
    
                    if (cur.moveToNext()) {
    
    
                        try {
                            if (initialPos != getLastMsgId()) {
                                // Here you get the last sms. Do what you want.
                                String receiver = cur.getString(cur.getColumnIndex("address"));
                               System.out.println(" Receiver Ph no :"+receiver);
    
    
                                // Then, set initialPos to the current position.
                                initialPos = getLastMsgId(); 
                            }
                        } catch (Exception e) {
                            // Treat exception here
                        }
                    }
                    cur.close();
                }
            }).start();
    
        }
    
    }//End of class SmsObserver
    

提交回复
热议问题