Android編程之SMS讀取簡訊並儲存到SQLite的方法_Android

來源:互聯網
上載者:User

本文執行個體講述了Android編程之SMS讀取簡訊並儲存到SQLite的方法。分享給大家供大家參考,具體如下:

Android 之 SMS 簡訊在Android系統中是儲存在SQLite資料庫中的,但不讓其它程式訪問(Android系統的安全機制)

現在我們在讀取手機內的SMS簡訊,先儲存在我們自己定義的SQLite資料庫中,然後讀取SQLite資料庫提取簡訊,並顯示

SMS簡訊SQLite存取代碼:

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程式設計有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.