简体   繁体   中英

Android- read incoming messages using broadcast receiver

I have created an android application that listens for incoming sms. The issue i am encountering is that it also reads previous sms. The goal of the app was to grab sms from a specific originating address and store it in a database.

public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Log.i(TAG, "Intent Received: "+intent.getAction());
        if (intent.getAction()==SMS_RECEIVED){
            Bundle dataBundle = intent.getExtras();
            if(dataBundle != null){
                //creating PDU protocol Data unit object which is a protocol for transferring message
                Object[] mypdu = (Object[])dataBundle.get("pdus");
                final SmsMessage[] message = new SmsMessage[mypdu.length];

                for(int i =0; i< mypdu.length; i++){
                    //for build version >= API
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                        String format = dataBundle.getString("format");
                        //From PDU we get all object and smsMessage using following line of code
                        message[i] = SmsMessage.createFromPdu((byte[])mypdu[i],format);
                    }else{
                        message[i] = SmsMessage.createFromPdu((byte[]) mypdu[i]);
                    }
                    msg += message[i].getMessageBody().toString().replace("null","");
                    originatingAddress = message[i].getOriginatingAddress();
                }
                msg = msg.replace("null","");
                if(originatingAddress.trim().equals("MPESA")) {
                    Toast.makeText(context.getApplicationContext(), "message: " + msg, Toast.LENGTH_SHORT).show();
                }

            }
        }
//        throw new UnsupportedOperationException("Not yet implemented");

    }
}

Please try with below way (1)The Simple way you can achieve to store the unique of record on every SMS is timestamp is only unique in this case whenever you get SMS store timestamp of every Sms as a Unique or primary key as you want in database, like system.currentTimeMillisecond to get time of current SMS and store as LONG type Column in your database,

(2) you can also check with unique time on every SMS get but it is complex to check with every existing records

Hope this process will help in your way with prevent of duplicate record store in database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM