Write received message to SMS provider ( API level 19+ )

孤街浪徒 提交于 2019-12-08 06:42:29
Sagar Nayak

Thanks to Mike M. for the help. i got help from this answer - sms-doesnt-save-on-kitkat-4-4-already-set-as-default-messaging-app from SO and this post - kitkat-sms-mms-supports .

here is what i have done :

to write the sms into the sms provider of android system i used content provider. and passed value to it. code snippet is :

ContentValues values = new ContentValues();
values.put(Telephony.Sms.ADDRESS, msg.getDisplayOriginatingAddress());
values.put(Telephony.Sms.BODY, msg.getMessageBody());
context.getApplicationContext().getContentResolver().insert(Telephony.Sms.Sent.CONTENT_URI, values);

this code will save the received sms into the system sms provider and even after your ap is uninstalled other sms app can read it. keep in mind that you need to be the default sms app to do this operation. and you have to provide WRITE_SMS permission in manifest. i have targeted kitkat and versions after it. for previous versions you have to some part of code differently.

the whole SmsReceiver class after completion is :

public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();
    if (bundle != null) {

        Object[] pdusObj = (Object[]) bundle.get("pdus");

        SmsMessage[] messages = new SmsMessage[pdusObj.length];

        for (int i = 0; i < messages.length; i++) {
            String format = bundle.getString("format");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i], format);
            } else {
                messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
            }
        }
        for (SmsMessage msg : messages) {
            Log.i("log", "display msg body  : " + msg.getDisplayMessageBody() + "originating address : " + msg.getDisplayOriginatingAddress() + " get message body : " + msg.getMessageBody());
            ContentValues values = new ContentValues();
            values.put(Telephony.Sms.ADDRESS, msg.getDisplayOriginatingAddress());
            values.put(Telephony.Sms.BODY, msg.getMessageBody());
            context.getApplicationContext().getContentResolver().insert(Telephony.Sms.Sent.CONTENT_URI, values);
        }

    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!