|
package com.sms.test;
//IncomingSMSReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
public class IncomingSMSReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("onReceive");
if (intent.getAction().equals(SMS_RECEIVED)) {
SmsManager sms = SmsManager.getDefault();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) messages = SmsMessage.createFromPdu((byte[]) pdus);
for (SmsMessage message : messages){
String msg = message.getMessageBody();
String to = message.getOriginatingAddress();
sms.sendTextMessage(to, null, msg, null, null);
}}}}
}
package com.sms.test;
//SmsTestActivity.java
import android.app.Activity;
import android.os.Bundle;
public class SmsTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IncomingSMSReceiver incomingSMSReceiver = new IncomingSMSReceiver();
}
}
在AndroidManifest.xml文件中的<application>节点里对接收到短信的广播Intent进行订阅:
<receiver android:name=".IncomingSMSReceiver">
<intent-filter><action android:name="android.provider.Telephony.SMS_RECEIVED"/></intent-filter></receiver>
在AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.RECEIVE_SMS"/><!-- 接收短信权限 -->
<uses-permission android:name="android.permission.SEND_SMS"/><!-- 发送短信权限 -->
SetClass.zip 2011-9-7 11:34:22 上传下载积分: 下载豆 -1
67.57 KB, 下载次数: 12, 下载积分: 下载豆 -1 |
|