小米手机需要去短信设置里,把系统短信优先关闭,不然短信广播是监听不到的。其他型号手机还没测试过。
首先注意权限
<uses-permissionandroid:name="android.permission.READ_SMS"/>
<uses-permissionandroid:name="android.permission.RECEIVE_SMS"/>
package com.example.smsreciver;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends Activity {
final String SMS_URI_ALL = "content://sms/"; //所有信息
final String SMS_URI_INBOX = "content://sms/inbox"; //收件箱
final String SMS_URI_SEND = "content://sms/sent"; //已发送
final String SMS_URI_DRAFT = "content://sms/draft"; //草稿
final String SMS_URI_OUTBOX = "content://sms/outbox"; //发件箱
final String SMS_URI_FAILED = "content://sms/failed"; //发送失败
final String SMS_URI_QUEUED = "content://sms/queued"; //待发送列表
static TextView tv;
private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
tv = new TextView(this);
tv.setText(getSmsInPhone());
ScrollView sv = new ScrollView(this);
sv.addView(tv);
setContentView(sv);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
/**
* 注册短信广播
*/
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.setPriority(Integer.MAX_VALUE);
this.registerReceiver(SmsReciver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
this.unregisterReceiver(SmsReciver);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* 读取本机短信
* @return
*/
public String getSmsInPhone() {
StringBuilder smsBuilder = new StringBuilder();
try {
Uri uri = Uri.parse(SMS_URI_INBOX);
String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };
Cursor cur = getContentResolver().query(uri, projection, null, null, "date desc");
if (cur.moveToFirst()) {
int index_Address = cur.getColumnIndex("address");
int index_Person = cur.getColumnIndex("person");
int index_Body = cur.getColumnIndex("body");
int index_Date = cur.getColumnIndex("date");
int index_Type = cur.getColumnIndex("type");
do {
String strAddress = cur.getString(index_Address);
if(strAddress.equals("10086"))
{
int intPerson = cur.getInt(index_Person);
String strbody = cur.getString(index_Body);
if(strbody.startsWith("尊敬的客户"))
{
Log.e("", "getSmsInPhone"+strbody);
long longDate = cur.getLong(index_Date);
int intType = cur.getInt(index_Type);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date d = new Date(longDate);
String strDate = dateFormat.format(d);
String strType = "";
if (intType == 1) {
strType = "接收";
} else if (intType == 2) {
strType = "发送";
} else {
strType = "null";
}
smsBuilder.append("[ ");
smsBuilder.append(strAddress + ", ");
smsBuilder.append(intPerson + ", ");
smsBuilder.append(strbody + ", ");
smsBuilder.append(strDate + ", ");
smsBuilder.append(strType);
smsBuilder.append(" ]\n\n");
}
}
} while (cur.moveToNext());
if (!cur.isClosed()) {
cur.close();
cur = null;
}
} else {
smsBuilder.append("no result!");
}
smsBuilder.append("End!");
} catch (SQLiteException ex) {
Log.d("SQLiteException in getSmsInPhone", ex.getMessage());
}
return smsBuilder.toString();
}
/**
* 广播监听器,接收新收到的短信
*/
BroadcastReceiver SmsReciver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage msg = null;
if (null != bundle)
{
Object[] smsObj = (Object[]) bundle.get("pdus");
for (Object object : smsObj)
{
msg = SmsMessage.createFromPdu((byte[]) object);
Date date = new Date(msg.getTimestampMillis());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String receiveTime = format.format(date);
System.out.println("number:" + msg.getOriginatingAddress()
+ " body:" + msg.getDisplayMessageBody() + " time:"
+ receiveTime);
if (msg.getOriginatingAddress().equals("10086"))
{
String number = extractNumber(msg.getDisplayMessageBody());
handler.sendEmptyMessage(1);
}
}
}
}
};
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
tv.setText(getSmsInPhone());
};
};
/**
* 提取短信中的6个数字(验证码等)
*
* @param extractNumber
* @return
*/
private String extractNumber(String content) {
if (TextUtils.isEmpty(content)) {
return null;
}
Pattern p = Pattern.compile(patternCoder);
Matcher matcher = p.matcher(content);
if (matcher.find()) {
return matcher.group();
}
return null;
}
}
sms主要结构:
- _id => 短消息序号 如100
- thread_id => 对话的序号 如100
- address => 发件人地址,手机号.如+8613811810000
- person => 发件人,返回一个数字就是联系人列表里的序号,陌生人为null
- date => 日期 long型。如1256539465022
- protocol => 协议 0 SMS_RPOTO, 1 MMS_PROTO
- read => 是否阅读 0未读, 1已读
- status => 状态 -1接收,0 complete, 64 pending, 128 failed
- type => 类型 1是接收到的,2是已发出
- body => 短消息内容
- service_center => 短信服务中心号码编号。如+8613800755500