我正在构建一个从收件箱中读取每个新短信的应用程序 它来自特定发件人,我的应用会阅读内容,如果它有一些特定内容,那么它会做一些动作。
目标:
1。我想获取新邮件发件人的姓名或号码(比如说我的特定发件人不会显示数字TM-Google , TM-MyGinger
类似电讯市场发件人)
2。如果是来自我正在搜索的人,那么我想阅读邮件的内容。 别的是我的一部分。 请提供一些想法或代码段。
答案 0 :(得分:2)
创建短信接收器
public class SMSReceiver extends BroadcastReceiver {
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];
// getting SMS information from Pdu.
for (int i = 0; i < pdusObj.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
}
for (SmsMessage currentMessage : messages) {
// currentMessage.getDisplayOriginatingAddress() has sender's phone number
// currentMessage.getDisplayMessageBody() has the actual message
}
}
}
}
您可以使用以下代码阅读收件箱:
Uri mSmsinboxQueryUri = Uri.parse("content://sms");
Cursor cursor1 = getContentResolver().query(
mSmsinboxQueryUri,
new String[] { "_id", "thread_id", "address", "person", "date",
"body", "type" }, null, null, null);
startManagingCursor(cursor1);
String[] columns = new String[] { "address", "person", "date", "body",
"type" };
if (cursor1.getCount() > 0) {
String count = Integer.toString(cursor1.getCount());
Log.e("Count",count);
while (cursor1.moveToNext()) {
String address = cursor1.getString(cursor1
.getColumnIndex(columns[0]));
String name = cursor1.getString(cursor1
.getColumnIndex(columns[1]));
String date = cursor1.getString(cursor1
.getColumnIndex(columns[2]));
String msg = cursor1.getString(cursor1
.getColumnIndex(columns[3]));
String type = cursor1.getString(cursor1
.getColumnIndex(columns[4]));
et.setText( et.getText() + "Address:" + address + "\n"
+ "Name:" + name + "\n"
+ "Date:" + date + "\n"
+ "MSG:" + msg + "\n"
+ "type:" + type + "\n"
);
}
}
添加流向清单
<receiver android:name="SMSReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
并添加READ_SMS
和RECEIVE_SMS