EX06_05SMSreceiver.java
上传用户:vip_99
上传日期:2021-03-27
资源大小:61159k
文件大小:3k
- package irdc.EX06_05;
- /*引用BroadcastReceiver类*/
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.os.Bundle;
- /*引用telephoney.gsm.SmsMessage来收取短信*/
- import android.telephony.gsm.SmsMessage;
- /*引用Toast类来告知用户收到短信*/
- import android.widget.Toast;
- /*自定义继承自BroadcastReceiver类,聆听系统服务广播的信息 */
- public class EX06_05SMSreceiver extends BroadcastReceiver
- {
- /*
- * 声明静态字符串,并使用
- * android.provider.Telephony.SMS_RECEIVED
- * 作为Action为短信的依据
- */
- private static final String mACTION =
- "android.provider.Telephony.SMS_RECEIVED";
-
- private String str_receive="收到短信!";
-
- @Override
- public void onReceive(Context context, Intent intent)
- {
- // TODO Auto-generated method stub
- Toast.makeText(context, str_receive.toString(),
- Toast.LENGTH_LONG).show();
-
- /*判断传来Intent是否为短信*/
- if (intent.getAction().equals(mACTION))
- {
- /*建构一字符串集合变量sb*/
- StringBuilder sb = new StringBuilder();
- /*接收由Intent传来的数据*/
- Bundle bundle = intent.getExtras();
- /*判断Intent是有数据*/
- if (bundle != null)
- {
- /* pdus为 android内置短信参数 identifier
- * 通过bundle.get("")返回一包含pdus的对象*/
- Object[] myOBJpdus = (Object[]) bundle.get("pdus");
-
- /*构造短信对象array,并依据收到的对象长度来创建array的大小*/
- SmsMessage[] messages = new SmsMessage[myOBJpdus.length];
-
- for (int i = 0; i<myOBJpdus.length; i++)
- {
- messages[i] =
- SmsMessage.createFromPdu((byte[]) myOBJpdus[i]);
- }
-
- /* 将送来的短信合并自定义信息于StringBuilder当中 */
- for (SmsMessage currentMessage : messages)
- {
- sb.append("接收到来自:n");
- /* 收信人的电话号码 */
- sb.append(currentMessage.getDisplayOriginatingAddress());
- sb.append("n------传来的短信------n");
- /* 取得传来信息的BODY */
- sb.append(currentMessage.getDisplayMessageBody());
- Toast.makeText
- (
- context, sb.toString(), Toast.LENGTH_LONG
- ).show();
- }
- }
-
- /* 以Notification(Toase)显示来讯信息 */
- Toast.makeText
- (
- context, sb.toString(), Toast.LENGTH_LONG
- ).show();
-
- /* 返回主Activity */
- Intent i = new Intent(context, EX06_05.class);
- /*自定义一Bundle*/
- Bundle mbundle = new Bundle();
- /*将短信信息以putString()方法存入自定义的bundle内*/
- mbundle.putString("STR_INPUT", sb.toString());
- /*将自定义bundle写入Intent中*/
- i.putExtras(mbundle);
- /*设置Intent的Flag以一个全新的task来运行*/
- i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- context.startActivity(i);
- }
- }
- }