转载于:http://blog.csdn.net/JavaTiger427/archive/2010/10/11/5932751.aspx
1、 接受系统的短信广播,操作短信内容。
优点:操作方便,适合简单的短信应用。
缺点:来信会在状态栏显示通知信息。
AndroidManifest.xml :
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <!-- Receiver --> <receiver android:name=".sms.SMSReceiver"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>
code :
package org.anymobile.demo.sms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.gsm.SmsMessage;
import android.util.Log;
public class SMSReceiver extends BroadcastReceiver
{
public static final String TAG = "ImiChatSMSReceiver";
//android.provider.Telephony.Sms.Intents
public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(SMS_RECEIVED_ACTION))
{
SmsMessage[] messages = getMessagesFromIntent(intent);
for (SmsMessage message : messages)
{
Log.i(TAG, message.getOriginatingAddress() + " : " +
message.getDisplayOriginatingAddress() + " : " +
message.getDisplayMessageBody() + " : " +
message.getTimestampMillis());
}
}
}
public final SmsMessage[] getMessagesFromIntent(Intent intent)
{
Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
byte[][] pduObjs = new byte[messages.length][];
for (int i = 0; i < messages.length; i++)
{
pduObjs[i] = (byte[]) messages[i];
}
byte[][] pdus = new byte[pduObjs.length][];
int pduCount = pdus.length;
SmsMessage[] msgs = new SmsMessage[pduCount];
for (int i = 0; i <