Android第一课:Broadcast机制-接收短信

来源:互联网 发布:mac pro display 编辑:程序博客网 时间:2024/05/18 02:47

1.首先BroadcastReceiver具有两种注册方式:

You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the <receiver> tag in your AndroidManifest.xml.。

2.设计一个接受短信的广播接收器的程序,当有短信来了,进行提醒。

主界面:



主函数:

  private TextView mTextView1;  /** Called when the activity is first created. */  @Override  public void onCreate(Bundle savedInstanceState)  {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);    /*通过findViewById构造器创建TextView对象*/    mTextView1 = (TextView) findViewById(R.id.myTextView1);    mTextView1.setText("等待接收短信...");    Button bt1=(Button) findViewById(R.id.button1);    bt1.setOnClickListener(new OnClickListener()    {            @Override      public void onClick(View arg0)      {        finish();    //退出程序      }    });  }
Receiver代码:

/* 自定义继承自BroadcastReceiver类,聆听系统服务广播的信息 */public class EX06_01_SMSreceiver extends BroadcastReceiver {   /*声明静态字符串,并使用android.provider.Telephony.SMS_RECEIVED  作为Action为短信的依据*/  private static final String mACTION =   "android.provider.Telephony.SMS_RECEIVED";     @Override   public void onReceive(Context context, Intent intent)   {     // TODO Auto-generated method stub     /* 判断传来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());          }        }          /* 以Notification(Toase)显示来讯信息  */      Toast.makeText      (        context, sb.toString(), Toast.LENGTH_LONG      ).show();             /* 返回主Activity */       Intent i = new Intent(context, EX06_01.class);       /*设置让以一个全新的task来运行*/      i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);       context.startActivity(i);     }   } 

在manifest.xml中注册(需要申请短信接受权限):


     <!-- 建立receiver聆聽系統廣播訊息 -->    <receiver android:name="EX06_01_SMSreceiver">     <!-- 設定要捕捉的訊息名稱為provider中Telephony.SMS_RECEIVED -->  <intent-filter>     <action       android:name="android.provider.Telephony.SMS_RECEIVED" />   </intent-filter>     </receiver>   </application><uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>



有意思的地方:

当我们使用结束按钮结束程序时,可以发现当有短信收到时,将触发该程序运行

并且,当我们重启手机,可以发现程序仍然可以被触发

原创粉丝点击