Android SMS(二)—— 读取短信保存到 SQLite

Android 之 SMS 短信在Android系统中是保存在SQLite数据库中的,但不让其它程序访问(Android系统的安全机制)

现在我们在读取手机内的SMS短信,先保存在我们自己定义的SQLite数据库中,然后读取SQLite数据库提取短信,并显示


SMS短信SQLite存取代码:

  1. package com.homer.sms;  
  2.   
  3. import java.sql.Date;  
  4. import java.text.SimpleDateFormat;  
  5.   
  6. import org.loon.wsi.R;  
  7.   
  8. import android.app.Activity;  
  9. import android.content.Context;  
  10. import android.database.Cursor;  
  11. import android.database.sqlite.SQLiteDatabase;  
  12. import android.graphics.Color;  
  13. import android.net.Uri;  
  14. import android.os.Bundle;  
  15. import android.util.Log;  
  16. import android.widget.TableLayout;  
  17. import android.widget.TableRow;  
  18. import android.widget.TableRow.LayoutParams;  
  19. import android.widget.TextView;  
  20.   
  21. /** 
  22.  * 读取手机短信, 先保存到SQLite数据,然后再读取数据库显示 
  23.  *  
  24.  * @author sunboy_2050 
  25.  * @since  http://blog.csdn.net/sunboy_2050 
  26.  * @date   2012.03.06 
  27.  */  
  28. public class smsRead4 extends Activity {  
  29.   
  30.     TableLayout tableLayout;  
  31.     int index = 0;  
  32.   
  33.     @Override  
  34.     public void onCreate(Bundle savedInstanceState) {  
  35.         super.onCreate(savedInstanceState);  
  36.   
  37.         setContentView(R.layout.main);  
  38.   
  39.         tableLayout = (TableLayout) findViewById(R.id.tableLayout);  
  40.         showSMS();  
  41.     }  
  42.   
  43.     private void showSMS() {  
  44.         SmsHander smsHander = new SmsHander(this);  
  45.   
  46.         smsHander.createSMSDatabase();                          // 创建SQLite数据库  
  47.         smsHander.insertSMSToDatabase();                        // 读取手机短信,插入SQLite数据库  
  48.         Cursor cursor = smsHander.querySMSInDatabase(100);      // 获取前100条短信(日期排序)  
  49.   
  50.         cursor.moveToPosition(-1);  
  51.         while (cursor.moveToNext()) {  
  52.             String strAddress = cursor.getString(cursor.getColumnIndex("address"));  
  53.             String strDate = cursor.getString(cursor.getColumnIndex("date"));  
  54.             String strBody = cursor.getString(cursor.getColumnIndex("body"));  
  55.   
  56.             SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  57.             Date date = new Date(Long.parseLong(strDate));  
  58.             strDate = dateFormat.format(date);  
  59.   
  60.             String smsTitle = strAddress + "\t\t" + strDate;  
  61.             String smsBody = strBody + "\n";  
  62.             Log.i("tableRow", smsTitle + smsBody);  
  63.   
  64.             // title Row   
  65.             TableRow trTitle = new TableRow(this);  
  66.             trTitle.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  
  67.   
  68.             TextView tvTitle = new TextView(this);  
  69.             tvTitle.setText(smsTitle);  
  70.             tvTitle.getPaint().setFakeBoldText(true); // 加粗字体  
  71.             tvTitle.setTextColor(Color.RED);  
  72.             tvTitle.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  
  73.             trTitle.addView(tvTitle);  
  74.             tableLayout.addView(trTitle, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));  
  75.   
  76.             // body Row   
  77.             TableRow trBody = new TableRow(this);  
  78.             trBody.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  
  79.   
  80.             TextView tvBody = new TextView(this);  
  81.             tvBody.setText(smsBody);  
  82.             tvBody.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  
  83.             trBody.addView(tvBody);  
  84.             tableLayout.addView(trBody, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));  
  85.         }  
  86.   
  87.         if (!cursor.isClosed()) {  
  88.             cursor.close();  
  89.             cursor = null;  
  90.         }  
  91.   
  92.         smsHander.closeSMSDatabase();  
  93.         index = 0;  
  94.     }  
  95.   
  96.     public class SmsHander {  
  97.   
  98.         SQLiteDatabase db;  
  99.         Context context;  
  100.   
  101.         public SmsHander(Context context) {  
  102.             this.context = context;  
  103.         }  
  104.   
  105.         public void createSMSDatabase() {  
  106.             String sql = "create table if not exists sms("  
  107.                     + "_id integer primary key autoincrement,"  
  108.                     + "address varchar(255)," + "person varchar(255),"  
  109.                     + "body varchar(1024)," + "date varchar(255),"  
  110.                     + "type integer)";  
  111.             db = SQLiteDatabase.openOrCreateDatabase(context.getFilesDir().toString() + "/data.db3"null);         // 创建数据库  
  112.             db.execSQL(sql);  
  113.         }  
  114.   
  115.         // 获取手机短信   
  116.         private Cursor getSMSInPhone() {  
  117.             Uri SMS_CONTENT = Uri.parse("content://sms/");  
  118.             String[] projection = new String[] { "_id""address""person""body""date""type" };  
  119.             Cursor cursor = context.getContentResolver().query(SMS_CONTENT, projection, nullnull"date desc");   // 获取手机短信  
  120.   
  121.             while (cursor.moveToNext()) {  
  122.                 System.out.println("--sms-- : " + cursor.getString(cursor.getColumnIndex("body")));  
  123.             }  
  124.   
  125.             return cursor;  
  126.         }  
  127.   
  128.         // 保存手机短信到 SQLite 数据库   
  129.         public void insertSMSToDatabase() {  
  130.             Long lastTime;  
  131.             Cursor dbCount = db.rawQuery("select count(*) from sms"null);  
  132.             dbCount.moveToFirst();  
  133.             if (dbCount.getInt(0) > 0) {  
  134.                 Cursor dbcur = db.rawQuery("select * from sms order by date desc limit 1"null);  
  135.                 dbcur.moveToFirst();  
  136.                 lastTime = Long.parseLong(dbcur.getString(dbcur.getColumnIndex("date")));  
  137.             } else {  
  138.                 lastTime = new Long(0);  
  139.             }  
  140.             dbCount.close();  
  141.             dbCount = null;  
  142.   
  143.             Cursor cur = getSMSInPhone(); // 获取短信(游标)  
  144.             db.beginTransaction(); // 开始事务处理  
  145.             if (cur.moveToFirst()) {  
  146.                 String address;  
  147.                 String person;  
  148.                 String body;  
  149.                 String date;  
  150.                 int type;  
  151.   
  152.                 int iAddress = cur.getColumnIndex("address");  
  153.                 int iPerson = cur.getColumnIndex("person");  
  154.                 int iBody = cur.getColumnIndex("body");  
  155.                 int iDate = cur.getColumnIndex("date");  
  156.                 int iType = cur.getColumnIndex("type");  
  157.   
  158.                 do {  
  159.                     address = cur.getString(iAddress);  
  160.                     person = cur.getString(iPerson);  
  161.                     body = cur.getString(iBody);  
  162.                     date = cur.getString(iDate);  
  163.                     type = cur.getInt(iType);  
  164.   
  165.                     if (Long.parseLong(date) > lastTime) {  
  166.                         String sql = "insert into sms values(null, ?, ?, ?, ?, ?)";  
  167.                         Object[] bindArgs = new Object[] { address, person, body, date, type };  
  168.                         db.execSQL(sql, bindArgs);  
  169.                     } else {  
  170.                         break;  
  171.                     }  
  172.                 } while (cur.moveToNext());  
  173.   
  174.                 cur.close();  
  175.                 cur = null;  
  176.                 db.setTransactionSuccessful();  // 设置事务处理成功,不设置会自动回滚不提交  
  177.                 db.endTransaction();            // 结束事务处理  
  178.             }  
  179.   
  180.         }  
  181.   
  182.         // 获取 SQLite 数据库中的全部短信   
  183.         public Cursor querySMSFromDatabase() {  
  184.             String sql = "select * from sms order by date desc";  
  185.             return db.rawQuery(sql, null);  
  186.         }  
  187.   
  188.         // 获取 SQLite 数据库中的最新 size 条短信   
  189.         public Cursor querySMSInDatabase(int size) {  
  190.             String sql;  
  191.   
  192.             Cursor dbCount = db.rawQuery("select count(*) from sms"null);  
  193.             dbCount.moveToFirst();  
  194.             if (size < dbCount.getInt(0)) { // 不足 size 条短信,则取前 size 条  
  195.                 sql = "select * from sms order by date desc limit " + size;  
  196.             } else {  
  197.                 sql = "select * from sms order by date desc";  
  198.             }  
  199.             dbCount.close();  
  200.             dbCount = null;  
  201.   
  202.             return db.rawQuery(sql, null);  
  203.         }  
  204.   
  205.         // 获取 SQLite数据库的前 second秒短信  
  206.         public Cursor getSMSInDatabaseFrom(long second) {  
  207.             long time = System.currentTimeMillis() / 1000 - second;  
  208.             String sql = "select * from sms order by date desc where date > " + time;  
  209.             return db.rawQuery(sql, null);  
  210.         }  
  211.   
  212.         // 关闭数据库   
  213.         public void closeSMSDatabase() {  
  214.             if (db != null && db.isOpen()) {  
  215.                 db.close();  
  216.                 db = null;  
  217.             }  
  218.         }  
  219.   
  220.     }  
  221. }  
package com.homer.sms;

import java.sql.Date;
import java.text.SimpleDateFormat;

import org.loon.wsi.R;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

/**
 * 读取手机短信, 先保存到SQLite数据,然后再读取数据库显示
 * 
 * @author sunboy_2050
 * @since  http://blog.csdn.net/sunboy_2050
 * @date   2012.03.06
 */
public class smsRead4 extends Activity {

	TableLayout tableLayout;
	int index = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		tableLayout = (TableLayout) findViewById(R.id.tableLayout);
		showSMS();
	}

	private void showSMS() {
		SmsHander smsHander = new SmsHander(this);

		smsHander.createSMSDatabase();							// 创建SQLite数据库
		smsHander.insertSMSToDatabase();						// 读取手机短信,插入SQLite数据库
		Cursor cursor = smsHander.querySMSInDatabase(100);		// 获取前100条短信(日期排序)

		cursor.moveToPosition(-1);
		while (cursor.moveToNext()) {
			String strAddress = cursor.getString(cursor.getColumnIndex("address"));
			String strDate = cursor.getString(cursor.getColumnIndex("date"));
			String strBody = cursor.getString(cursor.getColumnIndex("body"));

			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date(Long.parseLong(strDate));
			strDate = dateFormat.format(date);

			String smsTitle = strAddress + "\t\t" + strDate;
			String smsBody = strBody + "\n";
			Log.i("tableRow", smsTitle + smsBody);

			// title Row
			TableRow trTitle = new TableRow(this);
			trTitle.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

			TextView tvTitle = new TextView(this);
			tvTitle.setText(smsTitle);
			tvTitle.getPaint().setFakeBoldText(true); // 加粗字体
			tvTitle.setTextColor(Color.RED);
			tvTitle.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			trTitle.addView(tvTitle);
			tableLayout.addView(trTitle, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

			// body Row
			TableRow trBody = new TableRow(this);
			trBody.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

			TextView tvBody = new TextView(this);
			tvBody.setText(smsBody);
			tvBody.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			trBody.addView(tvBody);
			tableLayout.addView(trBody, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		}

		if (!cursor.isClosed()) {
			cursor.close();
			cursor = null;
		}

		smsHander.closeSMSDatabase();
		index = 0;
	}

	public class SmsHander {

		SQLiteDatabase db;
		Context context;

		public SmsHander(Context context) {
			this.context = context;
		}

		public void createSMSDatabase() {
			String sql = "create table if not exists sms("
					+ "_id integer primary key autoincrement,"
					+ "address varchar(255)," + "person varchar(255),"
					+ "body varchar(1024)," + "date varchar(255),"
					+ "type integer)";
			db = SQLiteDatabase.openOrCreateDatabase(context.getFilesDir().toString() + "/data.db3", null);			// 创建数据库
			db.execSQL(sql);
		}

		// 获取手机短信
		private Cursor getSMSInPhone() {
			Uri SMS_CONTENT = Uri.parse("content://sms/");
			String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };
			Cursor cursor = context.getContentResolver().query(SMS_CONTENT, projection, null, null, "date desc");	// 获取手机短信

			while (cursor.moveToNext()) {
				System.out.println("--sms-- : " + cursor.getString(cursor.getColumnIndex("body")));
			}

			return cursor;
		}

		// 保存手机短信到 SQLite 数据库
		public void insertSMSToDatabase() {
			Long lastTime;
			Cursor dbCount = db.rawQuery("select count(*) from sms", null);
			dbCount.moveToFirst();
			if (dbCount.getInt(0) > 0) {
				Cursor dbcur = db.rawQuery("select * from sms order by date desc limit 1", null);
				dbcur.moveToFirst();
				lastTime = Long.parseLong(dbcur.getString(dbcur.getColumnIndex("date")));
			} else {
				lastTime = new Long(0);
			}
			dbCount.close();
			dbCount = null;

			Cursor cur = getSMSInPhone(); // 获取短信(游标)
			db.beginTransaction(); // 开始事务处理
			if (cur.moveToFirst()) {
				String address;
				String person;
				String body;
				String date;
				int type;

				int iAddress = cur.getColumnIndex("address");
				int iPerson = cur.getColumnIndex("person");
				int iBody = cur.getColumnIndex("body");
				int iDate = cur.getColumnIndex("date");
				int iType = cur.getColumnIndex("type");

				do {
					address = cur.getString(iAddress);
					person = cur.getString(iPerson);
					body = cur.getString(iBody);
					date = cur.getString(iDate);
					type = cur.getInt(iType);

					if (Long.parseLong(date) > lastTime) {
						String sql = "insert into sms values(null, ?, ?, ?, ?, ?)";
						Object[] bindArgs = new Object[] { address, person, body, date, type };
						db.execSQL(sql, bindArgs);
					} else {
						break;
					}
				} while (cur.moveToNext());

				cur.close();
				cur = null;
				db.setTransactionSuccessful(); 	// 设置事务处理成功,不设置会自动回滚不提交
				db.endTransaction(); 			// 结束事务处理
			}

		}

		// 获取 SQLite 数据库中的全部短信
		public Cursor querySMSFromDatabase() {
			String sql = "select * from sms order by date desc";
			return db.rawQuery(sql, null);
		}

		// 获取 SQLite 数据库中的最新 size 条短信
		public Cursor querySMSInDatabase(int size) {
			String sql;

			Cursor dbCount = db.rawQuery("select count(*) from sms", null);
			dbCount.moveToFirst();
			if (size < dbCount.getInt(0)) { // 不足 size 条短信,则取前 size 条
				sql = "select * from sms order by date desc limit " + size;
			} else {
				sql = "select * from sms order by date desc";
			}
			dbCount.close();
			dbCount = null;

			return db.rawQuery(sql, null);
		}

		// 获取 SQLite数据库的前 second秒短信
		public Cursor getSMSInDatabaseFrom(long second) {
			long time = System.currentTimeMillis() / 1000 - second;
			String sql = "select * from sms order by date desc where date > " + time;
			return db.rawQuery(sql, null);
		}

		// 关闭数据库
		public void closeSMSDatabase() {
			if (db != null && db.isOpen()) {
				db.close();
				db = null;
			}
		}

	}
}
运行结果:


代码示例


推荐参考:

Android 之 SMS 短信读取

以下是对提供的参考资料的总结,按照要求结构化多个要点分条输出: 4G/5G无线网络优化与网规案例分析: NSA站点下终端掉4G问题:部分用户反馈NSA终端频繁掉4G,主要因终端主动发起SCGfail导致。分析显示,在信号较好的环境下,终端可能因节能、过热保护等原因主动释放连接。解决方案建议终端侧进行分析处理,尝试关闭节电开关等。 RSSI算法识别天馈遮挡:通过计算RSSI平均值及差值识别天馈遮挡,差值大于3dB则认定有遮挡。不同设备分组规则不同,如64T和32T。此方法可有效帮助现场人员识别因环境变化引起的网络问题。 5G 160M组网小区CA不生效:某5G站点开启100M+60M CA功能后,测试发现UE无法正常使用CA功能。问题原因在于CA频点集标识配置错误,修正后测试正常。 5G网络优化与策略: CCE映射方式优化:针对诺基亚站点覆盖农村区域,通过优化CCE资源映射方式(交织、非交织),提升RRC连接建立成功率和无线接通率。非交织方式相比交织方式有显著提升。 5G AAU两扇区组网:与三扇区组网相比,AAU两扇区组网在RSRP、SINR、下载速率和上传速率上表现不同,需根据具体场景选择适合的组网方式。 5G语音解决方案:包括沿用4G语音解决方案、EPS Fallback方案和VoNR方案。不同方案适用于不同的5G组网策略,如NSA和SA,并影响语音连续性和网络覆盖。 4G网络优化与资源利用: 4G室分设备利旧:面对4G网络投资压减与资源需求矛盾,提出利旧多维度调优策略,包括资源整合、统筹调配既有资源,以满足新增需求和提质增效。 宏站RRU设备1托N射灯:针对5G深度覆盖需求,研究使用宏站AAU结合1托N射灯方案,快速便捷地开通5G站点,提升深度覆盖能力。 基站与流程管理: 爱立信LTE基站邻区添加流程:未提供具体内容,但通常涉及邻区规划、参数配置、测试验证等步骤,以确保基站间顺畅切换和覆盖连续性。 网络规划与策略: 新高铁跨海大桥覆盖方案试点:虽未提供详细内容,但可推测涉及高铁跨海大桥区域的4G/5G网络覆盖规划,需考虑信号穿透、移动性管理、网络容量等因素。 总结: 提供的参考资料涵盖了4G/5G无线网络优化、网规案例分析、网络优化策略、资源利用、基站管理等多个方面。 通过具体案例分析,展示了无线网络优化中的常见问题及解决方案,如NSA终端掉4G、RSSI识别天馈遮挡、CA不生效等。 强调了5G网络优化与策略的重要性,包括CCE映射方式优化、5G语音解决方案、AAU扇区组网选择等。 提出了4G网络优化与资源利用的策略,如室分设备利旧、宏站RRU设备1托N射灯等。 基站与流程管理方面,提到了爱立信LTE基站邻区添加流程,但未给出具体细节。 新高铁跨海大桥覆盖方案试点展示了特殊场景下的网络规划需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值