Android 获取短信内容

2024-06-01 15:38
文章标签 android 获取 短信内容

本文主要是介绍Android 获取短信内容,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

小米手机需要去短信设置里,把系统短信优先关闭,不然短信广播是监听不到的。其他型号手机还没测试过。


首先注意权限

<uses-permissionandroid:name="android.permission.READ_SMS"/>

<uses-permissionandroid:name="android.permission.RECEIVE_SMS"/>


package com.example.smsreciver;import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.widget.ScrollView;
import android.widget.TextView;public class MainActivity extends Activity {final String SMS_URI_ALL = "content://sms/";  			//所有信息final String SMS_URI_INBOX = "content://sms/inbox";  	//收件箱final String SMS_URI_SEND = "content://sms/sent";  		//已发送final String SMS_URI_DRAFT = "content://sms/draft";  	//草稿final String SMS_URI_OUTBOX = "content://sms/outbox";  	//发件箱final String SMS_URI_FAILED = "content://sms/failed";  	//发送失败final String SMS_URI_QUEUED = "content://sms/queued";  	//待发送列表static TextView tv;private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//setContentView(R.layout.activity_main);tv = new TextView(this);  tv.setText(getSmsInPhone());  ScrollView sv = new ScrollView(this);  sv.addView(tv);  setContentView(sv);}@Overrideprotected void onStart() {// TODO Auto-generated method stubsuper.onStart();/*** 注册短信广播*/IntentFilter filter = new IntentFilter();filter.addAction("android.provider.Telephony.SMS_RECEIVED");filter.setPriority(Integer.MAX_VALUE);this.registerReceiver(SmsReciver, filter);}@Overrideprotected void onDestroy() {super.onDestroy();this.unregisterReceiver(SmsReciver);}@Overridepublic 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;}/*** 读取本机短信* @return*/public String getSmsInPhone() {  StringBuilder smsBuilder = new StringBuilder();  try {  Uri uri = Uri.parse(SMS_URI_INBOX);  String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };Cursor cur = getContentResolver().query(uri, projection, null, null, "date desc");if (cur.moveToFirst()) {  int index_Address = cur.getColumnIndex("address");  int index_Person = cur.getColumnIndex("person");  int index_Body = cur.getColumnIndex("body");  int index_Date = cur.getColumnIndex("date");  int index_Type = cur.getColumnIndex("type");  do {  String strAddress = cur.getString(index_Address); if(strAddress.equals("10086")){int intPerson = cur.getInt(index_Person);  String strbody = cur.getString(index_Body);  if(strbody.startsWith("尊敬的客户")){Log.e("", "getSmsInPhone"+strbody);long longDate = cur.getLong(index_Date);  int intType = cur.getInt(index_Type);  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");Date d = new Date(longDate);  String strDate = dateFormat.format(d);  String strType = "";  if (intType == 1) {  strType = "接收";  } else if (intType == 2) {strType = "发送";  } else {  strType = "null";  }  smsBuilder.append("[ ");  smsBuilder.append(strAddress + ", ");  smsBuilder.append(intPerson + ", ");  smsBuilder.append(strbody + ", ");  smsBuilder.append(strDate + ", ");  smsBuilder.append(strType);  smsBuilder.append(" ]\n\n");}}} while (cur.moveToNext());  if (!cur.isClosed()) {  cur.close();  cur = null;  }  } else {  smsBuilder.append("no result!"); }smsBuilder.append("End!");  } catch (SQLiteException ex) {  Log.d("SQLiteException in getSmsInPhone", ex.getMessage());  }  return smsBuilder.toString();  } /*** 广播监听器,接收新收到的短信*/BroadcastReceiver SmsReciver = new BroadcastReceiver() {@Override  public void onReceive(Context context, Intent intent) {Bundle bundle = intent.getExtras();  SmsMessage msg = null;if (null != bundle) {Object[] smsObj = (Object[]) bundle.get("pdus");  for (Object object : smsObj){msg = SmsMessage.createFromPdu((byte[]) object);  Date date = new Date(msg.getTimestampMillis());SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  String receiveTime = format.format(date);  System.out.println("number:" + msg.getOriginatingAddress()  + "   body:" + msg.getDisplayMessageBody() + "  time:"  + receiveTime); if (msg.getOriginatingAddress().equals("10086")){String number = extractNumber(msg.getDisplayMessageBody());handler.sendEmptyMessage(1);}}}}};Handler handler = new Handler() {public void handleMessage(android.os.Message msg) {tv.setText(getSmsInPhone());};};/*** 提取短信中的6个数字(验证码等)* * @param extractNumber* @return*/private String extractNumber(String content) {if (TextUtils.isEmpty(content)) {return null;}Pattern p = Pattern.compile(patternCoder);Matcher matcher = p.matcher(content);if (matcher.find()) {return matcher.group();}return null;}
}


sms主要结构: 

  1. _id => 短消息序号 如100  
  2. thread_id => 对话的序号 如100  
  3. address => 发件人地址,手机号.如+8613811810000  
  4. person => 发件人,返回一个数字就是联系人列表里的序号,陌生人为null  
  5. date => 日期  long型。如1256539465022  
  6. protocol => 协议 0 SMS_RPOTO, 1 MMS_PROTO   
  7. read => 是否阅读 0未读, 1已读   
  8. status => 状态 -1接收,0 complete, 64 pending, 128 failed   
  9. type => 类型 1是接收到的,2是已发出   
  10. body => 短消息内容   
  11. service_center => 短信服务中心号码编号。如+8613800755500  


这篇关于Android 获取短信内容的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1021413

相关文章

Android Mainline基础简介

《AndroidMainline基础简介》AndroidMainline是通过模块化更新Android核心组件的框架,可能提高安全性,本文给大家介绍AndroidMainline基础简介,感兴趣的朋... 目录关键要点什么是 android Mainline?Android Mainline 的工作原理关键

Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案

《Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案》:本文主要介绍Vue3组件中getCurrentInstance()获取App实例,但是返回nu... 目录vue3组件中getCurrentInstajavascriptnce()获取App实例,但是返回n

如何解决idea的Module:‘:app‘platform‘android-32‘not found.问题

《如何解决idea的Module:‘:app‘platform‘android-32‘notfound.问题》:本文主要介绍如何解决idea的Module:‘:app‘platform‘andr... 目录idea的Module:‘:app‘pwww.chinasem.cnlatform‘android-32

SpringMVC获取请求参数的方法

《SpringMVC获取请求参数的方法》:本文主要介绍SpringMVC获取请求参数的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下... 目录1、通过ServletAPI获取2、通过控制器方法的形参获取请求参数3、@RequestParam4、@

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

Android Studio 配置国内镜像源的实现步骤

《AndroidStudio配置国内镜像源的实现步骤》本文主要介绍了AndroidStudio配置国内镜像源的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、修改 hosts,解决 SDK 下载失败的问题二、修改 gradle 地址,解决 gradle

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

在Android平台上实现消息推送功能

《在Android平台上实现消息推送功能》随着移动互联网应用的飞速发展,消息推送已成为移动应用中不可或缺的功能,在Android平台上,实现消息推送涉及到服务端的消息发送、客户端的消息接收、通知渠道(... 目录一、项目概述二、相关知识介绍2.1 消息推送的基本原理2.2 Firebase Cloud Me

golang获取当前时间、时间戳和时间字符串及它们之间的相互转换方法

《golang获取当前时间、时间戳和时间字符串及它们之间的相互转换方法》:本文主要介绍golang获取当前时间、时间戳和时间字符串及它们之间的相互转换,本文通过实例代码给大家介绍的非常详细,感兴趣... 目录1、获取当前时间2、获取当前时间戳3、获取当前时间的字符串格式4、它们之间的相互转化上篇文章给大家介

Python获取中国节假日数据记录入JSON文件

《Python获取中国节假日数据记录入JSON文件》项目系统内置的日历应用为了提升用户体验,特别设置了在调休日期显示“休”的UI图标功能,那么问题是这些调休数据从哪里来呢?我尝试一种更为智能的方法:P... 目录节假日数据获取存入jsON文件节假日数据读取封装完整代码项目系统内置的日历应用为了提升用户体验,