|
首先建立两个类:一个是Activitiy一个是BroadcastReiver
第一activtiy类代码
import android.app.Activity;
import android.content.IntentFilter;
public class QTMessage extends Activity {
//调用BroadcastReceiver
private SMSBroadcastReceiver Receuver=null;
//和xml那个一样
private static final String SMS_ACTION="android.provider.Telephony.SMS_RECEIVED";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//调用BroadcastReceiver
Receuver = new SMSBroadcastReceiver();
//和该<intent-filter>匹配
IntentFilter fintent =new IntentFilter();
fintent.addAction(SMS_ACTION);
QTMessage.this.registerReceiver(Receuver, fintent);
}
}
复制代码
第二类BroadcastReiver
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("ok");
Object[] pdus = (Object[]) intent.getExtras().get("pdus");// 获取短信内容
for (Object pdu : pdus) {
byte[] data = (byte[]) pdu;// 获取单条短信内容,短信内容以pdu格式存在
SmsMessage message = SmsMessage.createFromPdu(data);// 使用pdu格式的短信数据生成短信对象
String content = message.getMessageBody();// 获取短信的内容
Date date = new Date(message.getTimestampMillis());// 获取短信的时间
SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String sendtime = format.format(date);
//显示短信信息
Toast.makeText(context, content, Toast.LENGTH_LONG).show();
}
}
}
复制代码 |
|