Android中第三方短信应用接收短信并保存到系统的数据库

时间:2024-03-10 13:32:39

                  Android中第三方短信应用接收短信并保存到系统的数据库                                        

/**
* 继承广播接收器
* @author Administrator
*
*/

public class SmsReceiver extends BroadcastReceiver {

private long date;
private Context context;
private final int six = 6;
private String phoneNumber;
private StringBuilder messageBody = new StringBuilder();
private final String SmsAction = "android.provider.Telephony.SMS_RECEIVED";

/**
* 接收短信
*/

// @Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(SmsAction)) {
Bundle bundle = intent.getExtras();
if (null != bundle) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] msg = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
for (SmsMessage currMsg : msg) {
messageBody.append(currMsg.getDisplayMessageBody());
phoneNumber = currMsg.getDisplayOriginatingAddress();
date = currMsg.getTimestampMillis();
}
String time = AbstractActivity.formatTimeStampString(
context, date);
String sender = AbstractActivity.queryNameByNum(phoneNumber,
context, false);

   addSmsToDB(phoneNumber, messageBody.toString());
}
}

}

/**

*添加到系统短信数据库

*/

private void addSmsToDB(String address, String content) {
ContentValues values = new ContentValues();
values.put("date", System.currentTimeMillis());
values.put("read", 0);//0为未读信息
values.put("type", 1);//1为收件箱信息
values.put("address", address);
values.put("body", content);
SmsApp.context.getContentResolver().insert(Uri.parse("content://sms"),
values);
}

}