码迷,mamicode.com
首页 > 移动开发 > 详细

Android 短信箱操作

时间:2016-04-21 22:01:00      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:

package blackice.android.product;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SmsAssistantActivity extends ListActivity {
    private List<Map<String, Object>> mData;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        /*
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        */
        super.onCreate(savedInstanceState);
        mData = GetSmsData();
        MyAdapter adapter = new MyAdapter(this);
        setListAdapter(adapter);
    }
    //菜单操作
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, Menu.FIRST + 1, 3, "退出").setIcon(android.R.drawable.ic_delete);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case Menu.FIRST + 1:
            //Toast.makeText(this, "删除菜单被点击了", Toast.LENGTH_LONG).show();
            finish();
            break;
        }
        return false;

    }
    //列表点击
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

    }
    public void showInfo(){
        new AlertDialog.Builder(this)
        .setTitle("自定义listview")
        .setMessage("自定义内容!")
        .setPositiveButton("关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        })
        .show();
    }
    public void SendMessageToServer(int position){
        Toast.makeText(this, (String)mData.get(position).get("title"), Toast.LENGTH_LONG).show();

        
    }
    //////////////////////////////////自定义列表///////////////////////////////////////////
    public class MyAdapter extends BaseAdapter
    {
        private LayoutInflater mInflater;    
        public MyAdapter(Context context){
            this.mInflater = LayoutInflater.from(context);
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mData.size();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            
            ViewHolder holder = null;
            if (convertView == null) {
                
                holder=new ViewHolder();  
                
                convertView = mInflater.inflate(R.layout.vlist2, null);
                holder.img = (ImageView)convertView.findViewById(R.id.img);
                holder.title = (TextView)convertView.findViewById(R.id.title);
                holder.info = (TextView)convertView.findViewById(R.id.info);
                holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);
                convertView.setTag(holder);
                
            }else {
                holder = (ViewHolder)convertView.getTag();
            }
            
            
            holder.img.setBackgroundResource((Integer)mData.get(position).get("img"));
            holder.title.setText((String)mData.get(position).get("title"));
            holder.info.setText((String)mData.get(position).get("info"));
            
            holder.viewBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SendMessageToServer(position);
                }
            });
            return convertView;
        }
        
    }
    public final class ViewHolder{
        public ImageView img;
        public TextView title;
        public TextView info;
        public Button viewBtn;
    }
    ///////////////////////////////////短信读取//////////////////////////////////////////
    protected List<Map<String, Object>> GetSmsData() 
    {
        SmsHander smsHander = new SmsHander(this,"15802023933");

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

        cursor.moveToPosition(-1);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
        while (cursor.moveToNext()) {
            //短信内容
            //String strAddress = cursor.getString(cursor.getColumnIndex("address"));
            String strDate = cursor.getString(cursor.getColumnIndex("date"));
            String strBody = cursor.getString(cursor.getColumnIndex("body"));
            String strAddress = cursor.getString(cursor.getColumnIndex("address"));

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(Long.parseLong(strDate));
            strDate = dateFormat.format(date);
            Map<String, Object> map = new HashMap<String, Object>();  
            map.put("img", android.R.drawable.ic_menu_add);//图像资源的ID  
            map.put("title", strDate);  
            map.put("info", strBody);  
            list.add(map);  
        }

        //smsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,getData()));
        if (!cursor.isClosed()) {
            cursor.close();
            cursor = null;
        }

        smsHander.closeSMSDatabase();
        return list;
    }
    public class SmsHander {

        SQLiteDatabase db;
        Context context;
        String phoneNumber;

        public SmsHander(Context context) {
            this.context = context;
        }
        public SmsHander(Context context,String mobile){
            this.context = context;
            this.phoneNumber = mobile;
        }
        //建库
        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,isnew 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, "address=?", new String[]{this.phoneNumber}, "date desc");    // 获取手机短信
            //Cursor cursor = context.getContentResolver().query(SMS_CONTENT, projection, null,null, "date desc");    // 获取手机短信
            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;
                long intDate;

                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");
                int IsNew = 0;
                do {
                    
                    address = cur.getString(iAddress);
                    person = cur.getString(iPerson);
                    body = cur.getString(iBody);
                    date = cur.getString(iDate);
                    type = cur.getInt(iType);
                    intDate = Long.parseLong(date);
                    /*                     */
                    if((!ExistSms(address,date))&&address.equalsIgnoreCase(this.phoneNumber)){
                        System.out.println("此日期此短信不在库中");
                        if (intDate > lastTime) {
                            String sql = "insert into sms values(null, ?, ?, ?, ?, ?,?)";
                            Object[] bindArgs = new Object[] { address, person, body, date, type,IsNew};
                            db.execSQL(sql, bindArgs);
                        } else {
                            break;
                        }
                    }else
                    {
                        System.out.println("此日期此短信已在库中或不是此号码");
                    }

                } 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 数据库中指定号码的最新 size 条短信
        public Cursor querySMSInDatabase(int size,String mobile) {
            String sql;
            String testSql = "select count(*) from sms where address=‘"+ mobile +"%‘";

            Cursor dbCount = db.rawQuery(testSql, null);

            dbCount.moveToFirst();
            if (size < dbCount.getInt(0)) { // 不足 size 条短信,则取前 size 条
                sql = "select * from sms where address=‘"+ mobile ;
                sql += "‘ order by date desc";
                sql += " limit " + size;
            } else {
                sql = "select * from sms where address=‘"+ mobile +"‘";
                sql += " 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);
        }
        //检查此日期此号码是否有过短信
        protected boolean ExistSms(String mobile,String time){
            String sql = "select * from sms where address=‘"+mobile+"‘ and date=‘" +time +"‘";
            Cursor dbCount = db.rawQuery(sql, null);
            return dbCount.getCount()>0;

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

 

Android 短信箱操作

标签:

原文地址:http://www.cnblogs.com/blackice/p/5418828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!