广播接收器在发送新消息时,如同获取该消息及其详细信息一样,收听新的传入消息。
public class incomingSms extends BroadcastReceiver
{
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String message = currentMessage.getDisplayMessageBody();
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
Date date = new Date(currentMessage.getTimestampMillis());
String formattedDate = new SimpleDateFormat("MM/dd/yyyy").format(date);
long time=date.getTime();
String formattedTime = new SimpleDateFormat("hh:mm:ss").format(time);
Toast.makeText(context,"recieved sms "+"senderNum: "+ phoneNumber + ", message: " + message+ " , date:" + formattedDate + ",time: "+formattedTime , Toast.LENGTH_LONG).show();
MyDBHandler db = new MyDBHandler(context);
int f_id=1;
db.insertDat2(new DataSetGet(f_id,phoneNumber,message,formattedDate,formattedTime));
// addData(phoneNumber,message,formattedDate,formattedTime);
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
SmsMessage[] msgs = null;
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String no = "SMS from " + msgs[i].getOriginatingAddress() + " : ";
String message= msgs[i].getMessageBody().toString();
Toast.makeText(context,"sent message "+"no: "+no+" message: "+ message,Toast.LENGTH_LONG).show();
}
}
}
现在,当我发送信息时,吐司不会出现。
答案 0 :(得分:0)
在清单文件中添加:
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
将此代码放在活动文件中:
// Create Sent box URI
Uri sentURI = Uri.parse("content://sms/sent");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body" };
// Get Content Resolver object, which will deal with Content Provider
ContentResolver cr = getContentResolver();
// Fetch Sent SMS Message from Built-in Content Provider
Cursor c = cr.query(sentURI, reqCols, null, null, null);
您将收到此接收方收到的所有发送消息。现在您可以在sqlite数据库中存储消息。