近日,看了《第一行代码》有关短信接收的内容,就总结了一下。
1.手机接收到一条短信时,系统会发出一条android.provider.Telephy.SMS_RECEIVER的广播,这条广播带有短信的所有数据
2.首先定义xml文件
<LinearLayout android:layout_width="match_parent" android:layout_height="50dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="From:"/> <TextView android:id="@+id/sender" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="Content:"/> <TextView android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical"/>
2.MainActivity
public class MainActivity extends ActionBarActivity { private TextView sender; private TextView content; private IntentFilter receiverFilter; private MessageReceiver messageReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sender=(TextView)findViewById(R.id.sender); content=(TextView)findViewById(R.id.content); receiverFilter = new IntentFilter(); receiverFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); receiverFilter.setPriority(100); messageReceiver=new MessageReceiver(); //第一个参数表示将要执行的方法,第二个表示接受的广播 registerReceiver(messageReceiver, receiverFilter); } @Override protected void onDestroy() { super.onDestroy(); //动态注册广播,要在ondestroy()方法中取消注册 unregisterReceiver(messageReceiver); } class MessageReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Bundle bundle=intent.getExtras(); Object[] pdus=(Object[]) bundle.get("pdus"); SmsMessage[] messages=new SmsMessage[pdus.length]; for(int i=0;i<messages.length;i++){ messages[i]=SmsMessage.createFromPdu((byte[]) pdus[i]); } //获取发送方号码 String address = messages[0].getOriginatingAddress(); String fullMessage=""; for(SmsMessage message:messages){ fullMessage +=message.getMessageBody(); //获取短信内容 } sender.setText(address); content.setText(fullMessage); //abortBroadcast(); } } }
3.最后要在AndroidManifest.xml中声明权限
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
4.运行图
ps:这里的接受方式好像是API11之前的方法,现在已经不建议使用了
时间: 2024-11-16 15:35:10