在上一篇文章
Android简单实现BroadCastReceiver广播机制 中简单的实现了一个广播机制,这里利用BroadCarstRecevier实现一个接收短信并显示内容的案例,当然至于接收到短信以后是显示还是做其它的工作都可以由你自己决定了,我现在只关心的是获取到短信内容就可以了。 看实例: MainActivity.java 采用默认,不需要任何修改
package com.example.broadcastreceiver; import android.os.Bundle; import android.view.Menu; import android.app.Activity; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }MyBroadcastReceiver.java
package com.example.broadcastreceiver; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.SmsMessage; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Object[] pduses = (Object[]) intent.getExtras().get("pdus");// 得到所有的短信 for (Object pdus : pduses) { byte[] pdusmessage = (byte[]) pdus;// 得到每一条短信 SmsMessage sms = SmsMessage.createFromPdu(pdusmessage);// 创建短信bean String mobile = sms.getOriginatingAddress();// 得到发送方的电话号码 String content = sms.getMessageBody();// 得到短信内容 Date date = new Date(sms.getTimestampMillis());// 得到发送短信的具体时间 // 2009-10-12 12:21:23 SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.US);// 为时间设置格式 String sendtime = format.format(date); Toast.makeText(context, mobile + content + sendtime, Toast.LENGTH_LONG).show(); } } }AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.broadcastreceiver" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" /> <uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.broadcastreceiver.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".MyBroadcastReceiver" > <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" > </action> </intent-filter> </receiver> </application> </manifest>这里关于收发短信的权限
<uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.RECEIVE_SMS" />不能忘记