在做手机应用中,常常会碰到要求获取手机短信需求。所以记录下来,有需要的可以一看~!
因为获取短信肯定不止一条,所以我们定义的一个方法,获取返回一个list.
然后liist里面装一个javabean也就是实体类,我们创建一个实体类
public class SMSItem { private String phonenumber = null; private String content = null; private String time = null; private int type = -1; public SMSItem(String phonenumber, String content, String time, int type) { super(); this.phonenumber = phonenumber; this.content = content; this.time = time; this.type = type; }
}get,和set方法我就省去了。
定义一个返回list方法接收
public static ArrayList<SMSItem> getSMS(Context context) { final String SMS_URI_ALL = "content://sms/"; ArrayList<SMSItem> smeArrayList = new ArrayList<SMSItem>(); try { Uri uri = Uri.parse(SMS_URI_ALL); String[] projection = new String[]{"_id", "address", "person", "body", "date", "type"}; Cursor cur = context.getContentResolver().query(uri, projection, "date<=" + System.currentTimeMillis(), null, "date desc"); // 获取手机内部短信 if (null != cur && cur.moveToFirst()) { int indexAddress = cur.getColumnIndex("address"); int indexBody = cur.getColumnIndex("body"); int indexDate = cur.getColumnIndex("date"); int indexType = cur.getColumnIndex("type"); cur.getColumnIndex(Sms.PERSON); do { String strAddress = cur.getString(indexAddress); String strbody = cur.getString(indexBody); long longDate = cur.getLong(indexDate); int intType = cur.getInt(indexType); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date d = new Date(longDate); String strDate = dateFormat.format(d); smeArrayList.add(new SMSItem(strAddress, strbody, strDate, intType)); } while (cur.moveToNext()); if (!cur.isClosed()) { cur.close(); } }// end if } catch (SQLiteException ex) { ex.printStackTrace(); } return smeArrayList; }