package com.example.smstest;
import javax.security.auth.PrivateCredentialPermission;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.gsm.SmsMessage;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView sender;
private TextView content;
private IntentFilter receiveFilter;
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);
receiveFilter=new IntentFilter();
Log.v("sss","success0");
receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
Log.v("sss","success1");
messageReceiver=new MessageReceiver();
Log.v("sss","success2");
registerReceiver(messageReceiver,receiveFilter);
Log.v("sss","success3");
}
class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.v("sss","success4");
Bundle bundle=intent.getExtras();//从intent中取出一个bundle对象
Object[] pdus=(Object[])bundle.get("pdus");
//提取短信消息使用pdus密钥提取一个SMS pdus数组;
SmsMessage[] messages=new SmsMessage[pdus.length];
//将每一字节数组转换为SmsMessage对象
for(int i=0;i<messages.length;i++)
{
messages[i]=SmsMessage.createFromPdu((byte[])pdus[i]);
}
String address=messages[0].getOriginatingAddress();
//调用message对象的getOriginatingAddress()方法
//获取发送方号码;
String fullMessage=" ";
for(SmsMessage message: messages)
{
fullMessage+=message.getMessageBody();//获取短信内容将短信内容拼接起来
}
sender.setText(address);//显示在TextView上
content.setText(fullMessage);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(messageReceiver);
}
}