短信 short message service,简称SMS 是用户通过手机或其他电信终端直接发送或接收的文字或数字信息,用户每次能接收和发送短信的字符数,是160个英文或数字字符,或者70个中文字符。现在我通过Emulator Control向5554发送短信,如果5554收到短信将会提示,下面我们先看一下发来的短信提示图:
我们看一下方法类:
- package com.smart.sms;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.os.Bundle;
- import android.telephony.SmsMessage;
- import android.widget.Toast;
- public class SmsReceiver extends BroadcastReceiver{
- @Override
- public void onReceive(Context context, Intent intent) {
- if("android.provider.Telephony.SMS_RECEIVED".equals(intent.getAction())){
- StringBuilder sb=new StringBuilder();
- // 接收由SMS传过来的数据
- Bundle bundle=intent.getExtras();
- // 判断是否有数据
- if(bundle!=null){
- //通过pdus可以获得接收到的所有短信消息
- Object[] objArray=(Object[]) bundle.get("pdus");
- //构建短信对象array,并依据收到的对象长度来创建array的大小
- SmsMessage[] message=new SmsMessage[objArray.length];
- for (int i = 0; i < objArray.length; i++) {
- message[i]=SmsMessage.createFromPdu((byte[])objArray[i]);
- }
- // 将送来的短信合并自定义信息于StringBuilder当中
- for (SmsMessage currentMessage:message) {
- sb.append("短信来源");
- // 获得接收短信的电话号码
- sb.append(currentMessage.getDisplayMessageBody());
- sb.append("\n------短信内容------\n");
- // 获得短信的内容
- sb.append(currentMessage.getDisplayMessageBody());
- }
- Intent mainIntent=new Intent(context,SmsActivity.class);
- mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- context.startActivity(mainIntent);
- Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
- }
- }
- }
- }
main.xml文件编写代码:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id="@+id/textview"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:textSize="15dp"
- android:text="SMART收短信提示"
- />
- </LinearLayout>
附件:http://down.51cto.com/data/2357601
本文转自 llb988 51CTO博客,原文链接:http://blog.51cto.com/llb988/498644,如需转载请自行联系原作者