android 使用广播 接收和拦截 android系统短信
package com.app.sms_broadcastreceiver; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.gsm.SmsMessage; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MyReceiver extends Activity { public static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED"; Button button1; TextView textView4,textView2; Intent intent; BroadcastReceiver mReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onStart() { super.onStart(); //注册广播 mReceiver = new MyReceiverSMS(); IntentFilter filter = new IntentFilter(SMS_ACTION); registerReceiver(mReceiver, filter); } @Override protected void onStop() { super.onStop(); //取消广播 unregisterReceiver(mReceiver); } /** * 内部类 * @author Administrator * */ class MyReceiverSMS extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(MyReceiver.SMS_ACTION)){ Toast.makeText(context, "监测到系统短信", Toast.LENGTH_SHORT).show(); //获取intent参数 Bundle bundle=intent.getExtras(); //判断bundle内容 if (bundle!=null) { //获得并解析短信 Object[] pdus=(Object[])bundle.get("pdus");//取 pdus内容 SmsMessage[] messages = new SmsMessage[pdus.length];//解析短信 //获取短信内容 显示到控件 textView2 =(TextView)findViewById(R.id.textView2); textView4 =(TextView)findViewById(R.id.textView4); for(int i=0;i<messages.length;i++) { byte[] pdu=(byte[])pdus[i]; messages[i]=SmsMessage.createFromPdu(pdu); textView2.setText(messages[0].getDisplayOriginatingAddress().toString()); textView4.setText(messages[0].getDisplayMessageBody().toString()); } //取消系统短信广播 abortBroadcast(); } } } } }