Android-使用广播接收器读取传入消息

问题描述 投票:0回答:2

我创建了一个 Android 应用程序来监听传入的短信。我遇到的问题是它还会读取以前的短信。该应用程序的目标是从特定的原始地址获取短信并将其存储在数据库中。

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");

    }
}
android broadcastreceiver
2个回答
0
投票

请尝试以下方式 (1)您可以实现在每条短信上存储唯一记录的简单方法是时间戳,在这种情况下,每当您将每条短信的短信存储时间戳作为数据库(如系统)中的唯一键或主键时,时间戳才是唯一的。 currentTimeMillisecond 获取当前短信的时间并以 LONG 类型列存储在数据库中,

(2) 您还可以检查每条短信的唯一时间,但检查每条现有记录很复杂

希望此过程能够帮助您防止数据库中重复记录存储


0
投票

您找到解决方案了吗?

© www.soinside.com 2019 - 2024. All rights reserved.