首页 > 代码库 > 基于BroadReceiver实现获取短信内容
基于BroadReceiver实现获取短信内容
我朋友拜托我做一个能实现向指定号码发短信获取动态密码的一个小app,中间用到了基于监听系统通知的BroadReceiver
来实现获取有新短信并且获取新短信的内容。下面就是这个小app的实现监听部分的BroadReceiver的实现:
首先要实现一个类继承自BroadcastReceiver:
public class TheSmsReciver extends BroadcastReceiver {
private static MessageListener mMessageListener;
public TheSmsReciver() {
super();
}
@Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
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);
//从号码为"106557777"的短信中截取为六位数字的密码
if (msg.getOriginatingAddress().equals("106557777")) {
String str = msg.getDisplayMessageBody();
str=str.trim();
String str2="";
String str3="";
if(str != null && !"".equals(str)){
for(int i=0,j=0;i<str.length();i++){
if(str.charAt(i)>=48 && str.charAt(i)<=57){
j++;
str2+=str.charAt(i);
if(j==6){
str3 = str2;
}
}else{
str2="";
}
}
}
mMessageListener.OnReceived(str3,msg.getTimestampMillis()+"");
}
}
}
}
public interface MessageListener {
public void OnReceived(String message,String time);
}
public void setOnReceivedMessageListener(MessageListener messageListener) {
this.mMessageListener=messageListener;
}
}
然后在Activity中实现对BroadcastReceiver的监听:
public class MainActivity extends Activity {
private TheSmsReciver mSmsReciver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSmsReciver=new TheSmsReciver();
mSmsReciver.setOnReceivedMessageListener(new MessageListener() {
? ? @Override
? ? public void OnReceived(String message,String time) {
? ? //message和time就是获取的密码和这条短信的时间
? ? }
? ? });
}
}
?
基于BroadReceiver实现获取短信内容