BroadcastReceiver 接收系统短信广播
BroadcastReceiver 接收系统短信广播
/* 注册广播:
* |--静态注册 (在AndroidManifest .xml 中注册)
* <receiver android:name=".MyBroadcastRecevier" >
<intent-filter>
<action android:name="com.example.broadcasttest" />
</intent-filter>
</receiver>
* |--动态注册:
* //动态注册广播
BroadcastReceiver receiver = new MyBroadcastRecevier();
//创建IntentFilter 意图过滤器
IntentFilter filter = new IntentFilter();
//注册广播
registerReceiver(receiver, filter);
*/
package com.app.broadcaststest; 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.EditText; import android.widget.Toast; public class RecevierSMSActivity extends Activity { BroadcastReceiver mBroadcastReceiver; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); // 设置布局 setContentView(R.layout.activity_resms); } @Override protected void onStart() { // 注册广播 super.onStart(); mBroadcastReceiver = new ReceiverSms(); IntentFilter mfFilter = new IntentFilter(); mfFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); registerReceiver(mBroadcastReceiver, mfFilter); } @Override protected void onStop() { // 取消广播 super.onStop(); unregisterReceiver(mBroadcastReceiver); } private final class ReceiverSms extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 处理接收短信 if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){ Toast.makeText(context, "接收到短信", Toast.LENGTH_SHORT).show(); Bundle bundle = intent.getExtras(); if(bundle!=null){ Object[] SmsData = (Object[]) bundle.get("pdus"); SmsMessage sd[] = new SmsMessage[SmsData.length]; for (int i = 0; i < SmsData.length; i++) { sd[i] = SmsMessage.createFromPdu((byte[]) SmsData[i]); EditText editText3 = (EditText)findViewById(R.id.editText3); EditText editText4 =(EditText) findViewById(R.id.editText4); editText4.setText(sd[0].getDisplayOriginatingAddress().toString());//短信号码 editText3.setText(sd[0].getDisplayMessageBody().toString());//短信内容 } } } } } }