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

相关文章

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

Android协程高级用法大全

《Android协程高级用法大全》这篇文章给大家介绍Android协程高级用法大全,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友跟随小编一起学习吧... 目录1️⃣ 协程作用域(CoroutineScope)与生命周期绑定Activity/Fragment 中手

Android 缓存日志Logcat导出与分析最佳实践

《Android缓存日志Logcat导出与分析最佳实践》本文全面介绍AndroidLogcat缓存日志的导出与分析方法,涵盖按进程、缓冲区类型及日志级别过滤,自动化工具使用,常见问题解决方案和最佳实... 目录android 缓存日志(Logcat)导出与分析全攻略为什么要导出缓存日志?按需过滤导出1. 按

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

Python获取浏览器Cookies的四种方式小结

《Python获取浏览器Cookies的四种方式小结》在进行Web应用程序测试和开发时,获取浏览器Cookies是一项重要任务,本文我们介绍四种用Python获取浏览器Cookies的方式,具有一定的... 目录什么是 Cookie?1.使用Selenium库获取浏览器Cookies2.使用浏览器开发者工具

Java获取当前时间String类型和Date类型方式

《Java获取当前时间String类型和Date类型方式》:本文主要介绍Java获取当前时间String类型和Date类型方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录Java获取当前时间String和Date类型String类型和Date类型输出结果总结Java获取

C#监听txt文档获取新数据方式

《C#监听txt文档获取新数据方式》文章介绍通过监听txt文件获取最新数据,并实现开机自启动、禁用窗口关闭按钮、阻止Ctrl+C中断及防止程序退出等功能,代码整合于主函数中,供参考学习... 目录前言一、监听txt文档增加数据二、其他功能1. 设置开机自启动2. 禁止控制台窗口关闭按钮3. 阻止Ctrl +

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期