package com.example.broadcasttext;
import android.app.Activity;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/*通过activity来注册和取消注册广播
* 特别注意Mainfest。xml中注册permit
* */
public class MainActivity extends Activity {
private Button mBtn_register;
private Button mBtn_unregister;
private BCReceiver SMSReceiver;
//当设备收到sms短信,android系统会广播此Action
private static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtn_register = (Button) findViewById(R.id.btn_register);
mBtn_unregister = (Button) findViewById(R.id.btn_unregister);
mBtn_register.setOnClickListener(new RegisterListener());
mBtn_unregister.setOnClickListener(new UnRegisterListener());
}
//用于注册BroadCastReceiver的监听器
class RegisterListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SMSReceiver = new BCReceiver();
//创建一个BroadCastReceiver类
IntentFilter filter = new IntentFilter();
//创建一个过滤器
filter.addAction(SMS_ACTION);//过滤器添加Action
MainActivity.this.registerReceiver(SMSReceiver, filter);//在Activity中注册BroadCastReceiver
System.out.println("-----Register is succeed---");
//输出字符串作为标记,
}
}
//用于取消注册BroadCastReceiver的监听器
class UnRegisterListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.this.unregisterReceiver(SMSReceiver);
//取消注册BroadCastReceiver
System.out.println("-----------UnRegister is succeed");
//输出字符串作为标记
}
}
}
package com.example.broadcasttext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.test.suitebuilder.annotation.Smoke;
/*当Activity中注册BroadCastReceiver以后,andrid系统传来SMS_Action
* 就会执行onReceive这个方法
* PDU (protocol description unit) 协议解释单元
* 短信发送的intent的bundle中取值用key="PUDS"
* */
public class BCReceiver extends BroadcastReceiver{
private Bundle bundle;
//用于接受android系统传来的intent,以及进行进一步数据处理
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("-------onReceive is succeed--nice");//输出字符串作为标记
bundle = intent.getExtras(); //通过调用Intent类中getExtras()方法返回bundle,
Object[] SMSObject = (Object[]) bundle.get("PUDS"); //通过调用Bundle类中get()方法返回object对象,PUDS为获取短信的key
SmsMessage[] sms = new SmsMessage[SMSObject.length]; //创建一个长度为SMSobject的Smsmessage的数组对象
for(int i=0; i<SMSObject.length ; i++){
sms[i] = SmsMessage.createFromPdu((byte[]) SMSObject[i]); //根据一行pud创建一个SMSmessage对象
}
}
}