Android有条件的读取短信-json的包装与解析

----------------------------------------很久没有写Android了,工作项目需要,大晚上写着试试,明天要用到!!

package com.qlj.smsreadtest;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;


public class SmsService {


private Context context;


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

public List<Map<String, String>> getSmsInfos(){
List<Map<String, String>> list = new ArrayList<Map<String,String>>();
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.parse("content://sms/");
String json = "[{\"num\":\"15802292526\",\"time\":\"1414981422121\"},{\"num\":\"13821041382\",\"time\":\"1414981422121\"},{\"num\":\"1065830011\",\"time\":\"1414981422121\"}]";
JSONArray jsonArr = null;
StringBuffer sb = new StringBuffer();
try {
jsonArr = new JSONArray(json);
if(jsonArr.length() > 0){
for(int i =0 ; i<jsonArr.length() ; i++){
JSONObject jsonObj = (JSONObject) jsonArr.get(i);
sb.append("(");
sb.append("address like '%").append(jsonObj.get("num")).append("%'");
sb.append(" and date > ").append(jsonObj.get("time"));
sb.append(")");
sb.append(" or ");
}
sb.delete(sb.length()-4, sb.length()-1);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("showSms",sb.toString());
Cursor cursor = resolver.query(uri, new String[]{"_id","address","date","body"},sb.length()==0?null:sb.toString(), null, " date desc");
while(cursor.moveToNext()){
Map<String, String> map = new HashMap<String, String>();
map.put("id",cursor.getString(0));
map.put("address",cursor.getString(1));
map.put("date",cursor.getString(2));
map.put("body",cursor.getString(3));
list.add(map);
}
return list;
}

public void showSms(){
try {
List<Map<String, String>> list = getSmsInfos();
Log.i("showSms",list.size()+"");
if(list != null && list.size() > 0){
JSONArray arr = new JSONArray();
for(Map<String, String> map : list) {
Log.i("showSms", map.get("id")+"===" + map.get("address")+"===" + map.get("date")+"==="+ map.get("body"));
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", map.get("id"));
jsonObj.put("address", map.get("address"));
jsonObj.put("date", map.get("date"));
jsonObj.put("body", map.get("body"));
arr.put(jsonObj);
}
Log.i("showSms",arr.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
发布了34 篇原创文章 · 获赞 1 · 访问量 5万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览