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

相关文章

MySQL 获取字符串长度及注意事项

《MySQL获取字符串长度及注意事项》本文通过实例代码给大家介绍MySQL获取字符串长度及注意事项,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql 获取字符串长度详解 核心长度函数对比⚠️ 六大关键注意事项1. 字符编码决定字节长度2

python3如何找到字典的下标index、获取list中指定元素的位置索引

《python3如何找到字典的下标index、获取list中指定元素的位置索引》:本文主要介绍python3如何找到字典的下标index、获取list中指定元素的位置索引问题,具有很好的参考价值,... 目录enumerate()找到字典的下标 index获取list中指定元素的位置索引总结enumerat

Android DataBinding 与 MVVM使用详解

《AndroidDataBinding与MVVM使用详解》本文介绍AndroidDataBinding库,其通过绑定UI组件与数据源实现自动更新,支持双向绑定和逻辑运算,减少模板代码,结合MV... 目录一、DataBinding 核心概念二、配置与基础使用1. 启用 DataBinding 2. 基础布局

Android ViewBinding使用流程

《AndroidViewBinding使用流程》AndroidViewBinding是Jetpack组件,替代findViewById,提供类型安全、空安全和编译时检查,代码简洁且性能优化,相比Da... 目录一、核心概念二、ViewBinding优点三、使用流程1. 启用 ViewBinding (模块级

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

C++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操

SpringBoot服务获取Pod当前IP的两种方案

《SpringBoot服务获取Pod当前IP的两种方案》在Kubernetes集群中,SpringBoot服务获取Pod当前IP的方案主要有两种,通过环境变量注入或通过Java代码动态获取网络接口IP... 目录方案一:通过 Kubernetes Downward API 注入环境变量原理步骤方案二:通过

使用Python实现获取屏幕像素颜色值

《使用Python实现获取屏幕像素颜色值》这篇文章主要为大家详细介绍了如何使用Python实现获取屏幕像素颜色值,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 一、一个小工具,按住F10键,颜色值会跟着显示。完整代码import tkinter as tkimport pyau

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio