public class App extends Application {
	private static App mAppApplication;
	public static final String SP_FILE_NAME = "qiquying_msg_sp";
	private static SharePreferenceUtil mSpUtil;
	public static User currentUser = null;
	public static List<Activity> activities = new ArrayList<Activity>(); //用于记录已经开启的activity,便于退出应用时全部关闭
	// Tencent类是SDK的主要实现类，开发者可通过Tencent类访问腾讯开放的OpenAPI。
	// 其中APP_ID是分配给第三方应用的appid，类型为String。
	public static Tencent mTencent;
	public static Map<String, Long> smsCodeRecode;  //注册验证码发送记录
	public static Map<String, Long> smsCodeRecodeFindPwd;  //找回密码验证码发送记录
	public static boolean isStart = false;
	public static boolean isStartOtherActivity = false;
	@Override
	public void onCreate() {
		super.onCreate();
		mAppApplication = this;
		mSpUtil = new SharePreferenceUtil(this, SP_FILE_NAME);
		CrashHandler crashHandler = CrashHandler.getInstance();   
        crashHandler.init(getApplicationContext());
	}
	
	/** 获取Application */
    public static App getInstance() {
        return mAppApplication;
    }
    
    /** 获取mSpUtil */
    public synchronized SharePreferenceUtil getSpUtil() {
		if (mSpUtil == null)
			mSpUtil = new SharePreferenceUtil(this, SP_FILE_NAME);
		return mSpUtil;
	}


	/*添加activity*/
	public static void addActivity(Activity activity) {
		activities.add(activity);
	}
	
	/*添加activity*/
	public static void removeActivity(Activity activity) {
		if(activities.contains(activity)) {
			activities.remove(activity);
		}
	}
	
	/*关闭所有已打开的activity*/
	public static void clearActivitys() {
		for (Activity ac : activities) {
			if(ac!=null && !ac.isFinishing()) {
				ac.finish();
			}
		}
	}
	
	@SuppressLint("NewApi")
	@Override
	public void onTrimMemory(int level) {
		super.onTrimMemory(level);
		if(Constants.DEBUG) Log.w("App", "onTrimMemory");
		if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
			BitmapUtil.cleanMemCache();  //清除图片内存的中缓存
	    }
	}
} public class CommentAdapter extends BaseAdapter{
	
	private List<Comment> mList;
	private Context mContext;
	
    public CommentAdapter(Context context) {
    	mContext = context;
	}
    
    public void setList(List<Comment> lists) {
		this.mList = lists;
	}
    
    public void onDataChange(List<Comment> lists) {
		this.mList = lists;
		notifyDataSetChanged();
	}
    
	@Override
	public int getCount() {
		if(mList == null) {
			return 0;
		}
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		if(mList == null) {
			return null;
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
        if (convertView == null) {
        	holder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(
                    R.layout.listitem_comment, null);
            holder.comment_user_img = (ImageView) convertView.findViewById(R.id.comment_user_img);
            holder.comment_user_name = (TextView) convertView.findViewById(R.id.comment_user_nick);
            holder.comment_time = (TextView) convertView.findViewById(R.id.comment_time);
//            holder.comment_support_num = (TextView) convertView.findViewById(R.id.comment_support_num);
            holder.comment_content = (TextView) convertView.findViewById(R.id.comment_content);
            convertView.setTag(holder);
        } else {
        	holder = (ViewHolder) convertView.getTag();
        }
        Comment comment = mList.get(position);
        //是自己发的
        if(App.currentUser != null && App.currentUser.getId()==comment.getUserId()) {
        	BitmapUtil.display(holder.comment_user_img, App.currentUser.getPortraitUrl());
            holder.comment_user_name.setText(App.currentUser.getUserNike());
        } else {
        	BitmapUtil.display(holder.comment_user_img, comment.getPortraitUrl());
            holder.comment_user_name.setText(comment.getUserNike());
        }
        
        holder.comment_time.setText(Util.getFormatDate(comment.getCreateDate()));
        holder.comment_content.setText(comment.getContent());
        /*holder.comment_support_num.setText(String.valueOf(comment.getSupportsNum()));
        holder.comment_support_num.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ToastUtils.showMessage(mContext, "加1");
			}
		});*/
        
        return convertView;
	}

	
	private class ViewHolder {
		private ImageView comment_user_img;
		private TextView comment_user_name;
		private TextView comment_time;
//		private TextView comment_support_num;
//		private ImageView comment_support_img;
		private TextView comment_content;
    }
	
} public class Comment implements Serializable {

	private static final long serialVersionUID = -8116039067400484215L;

	/**
	 * 评论id
	 */
	private int id;
	
	/**
	 * 评论笑话id
	 */
	private int jokeId;
	
	/**
	 * 评论内容
	 */
	private String content;
	
	/**
	 * 评论支持数
	 */
	private int supportsNum;
	
	/**
	 * 创建时间
	 */
	private Date createDate;
	
	/**
	 * 评论用户id
	 */
	private int userId;
	
	/**
	 * 评论用户头像
	 */
	private String portraitUrl;

	/**
	 * 评论用户昵称
	 */
	private String userNike;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getJokeId() {
		return jokeId;
	}

	public void setJokeId(int jokeId) {
		this.jokeId = jokeId;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public int getSupportsNum() {
		return supportsNum;
	}

	public void setSupportsNum(int supportsNum) {
		this.supportsNum = supportsNum;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getPortraitUrl() {
		return portraitUrl;
	}

	public void setPortraitUrl(String portraitUrl) {
		this.portraitUrl = portraitUrl;
	}

	public String getUserNike() {
		return userNike;
	}

	public void setUserNike(String userNike) {
		this.userNike = userNike;
	}
	
} @Table(name="user_ding_cai")
public class DingOrCai implements Serializable{
	
	private static final long serialVersionUID = -2565933558042038491L;
	//是否上传服务器标记
	public static final int NOT_UPLOAD = 0;
	public static final int UPLOAD = 1;
	
	//顶踩标记
	public static final int CAI = 0;
	public static final int DING = 1;
	
	/**
	 * id
	 */
	@Id(column="id")
	private int id;
	
	/**
	 * 笑话id
	 */
	@Column(column="joke_id")
	private int jokeId;
	
	/**
	 * 用户id，游客为-1
	 */
	@Column(column="user_id")
	private int userId;
	
	/**
	 * 标记顶和踩
	 * 1：顶
	 * 0：踩
	 */
	@Column(column="ding_or_cai")
	private int dingOrCai;
	
	/**
	 * 顶或者踩之后的数量
	 */
	@Column(column="num")
	private int num;
	
	/**
	 * 是否上传数据
	 * 1：是
	 * 0：否
	 */
	@Column(column="is_upload", defaultValue="0")
	private int isUpload;

	public int getJokeId() {
		return jokeId;
	}

	public void setJokeId(int jokeId) {
		this.jokeId = jokeId;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public int getIsUpload() {
		return isUpload;
	}

	public void setIsUpload(int isUpload) {
		this.isUpload = isUpload;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getDingOrCai() {
		return dingOrCai;
	}

	public void setDingOrCai(int dingOrCai) {
		this.dingOrCai = dingOrCai;
	}
	
	public boolean isDing() {
		return dingOrCai == DING;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}
	
	
} public class Joke implements Serializable{

	private static final long serialVersionUID = 4646260119535165219L;

	//type标记
	public static final int TYPE_QUSHI = 1;
	public static final int TYPE_QUTU = 2;
	public static final int TYPE_MEITU = 3;
	public static final int TYPE_GIF = 4;
	
	//是否通过审核标记
	public static final int NOT_PASS = 0;
	public static final int PASS = 1;
	
	//是否被删除标记
	public static final int NOT_DELETE = 0;
	public static final int DELETE = 1;
	
	//最新最热排序标记
	public static final int SORT_NEW = 0;
	public static final int SORT_HOT = 1;
	
	/**
	 * 笑话id
	 */
	private int id;
	
	/**
	 * 笑话标题
	 */
	private String title;
	
	/**
	 * 笑话内容
	 */
	private String content;
	
	/**
	 * 图片地址
	 */
	private String ImgUrl;
	
	/**
	 * gif地址
	 */
	private String GifUrl;
	
	/**
	 * 笑话支持数
	 */
	private int supportsNum;
	
	/**
	 * 笑话反对数
	 */
	private int opposesNum;
	
	/**
	 * 笑话评论数
	 */
	private int commentNum;
	
	/**
	 * 笑话创建日期
	 */
	private Date createDate;
	
	/**
	 * 是否删除标记（0：未删除、1：已删除）
	 */
	private int isDelete;
	
	/**
	 * 笑话类别（1：趣事、2：趣图、3：美图、4：gif）
	 */
	private int type;
	
	/**
	 * 是否审核通过（0：未通过、1：已通过）
	 */
	private int isPass;
	
	/**
	 * 发表用户
	 */
	private int userId;
	
	/**
	 * 发表用户头像
	 */
	private String portraitUrl;

	/**
	 * 用户昵称
	 */
	private String userNike;
	
	/**
	 * 图片宽度
	 */
	private int imgWidth;
	
	/**
	 * 图片高度
	 */
	private int imgHeight;
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getImgUrl() {
		return ImgUrl;
	}

	public void setImgUrl(String imgUrl) {
		ImgUrl = imgUrl;
	}

	public String getGifUrl() {
		return GifUrl;
	}

	public void setGifUrl(String gifUrl) {
		GifUrl = gifUrl;
	}

	public int getSupportsNum() {
		return supportsNum;
	}

	public void setSupportsNum(int supportsNum) {
		this.supportsNum = supportsNum;
	}

	public int getOpposesNum() {
		return opposesNum;
	}

	public void setOpposesNum(int opposesNum) {
		this.opposesNum = opposesNum;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public int getIsDelete() {
		return isDelete;
	}

	public void setIsDelete(int isDelete) {
		this.isDelete = isDelete;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public int getIsPass() {
		return isPass;
	}

	public void setIsPass(int isPass) {
		this.isPass = isPass;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getPortraitUrl() {
		return portraitUrl;
	}

	public void setPortraitUrl(String portraitUrl) {
		this.portraitUrl = portraitUrl;
	}

	public String getUserNike() {
		return userNike;
	}

	public void setUserNike(String userNike) {
		this.userNike = userNike;
	}

	public int getCommentNum() {
		return commentNum;
	}

	public void setCommentNum(int commentNum) {
		this.commentNum = commentNum;
	}

	public int getImgWidth() {
		return imgWidth;
	}

	public void setImgWidth(int imgWidth) {
		this.imgWidth = imgWidth;
	}

	public int getImgHeight() {
		return imgHeight;
	}

	public void setImgHeight(int imgHeight) {
		this.imgHeight = imgHeight;
	}
	
} public class User implements Serializable {

	private static final long serialVersionUID = -1371659645448329097L;

	/**
	 * 用户id
	 */
	private int id;
	
	/**
	 * 用户名,手机号码
	 */
	private String userName;
	
	/**
	 * 用户登陆密码
	 * 加上transient关键字让改字段不参与序列化
	 */
	private transient String password;
	
	/**
	 * 用户昵称
	 */
	private String userNike;
	
	/**
	 * 用户性别(0：女、1：男)
	 */
	private int sex;
	
	/**
	 * 用户头像URL
	 */
	private String portraitUrl;
	
	/**
	 * 是否接受推送消息（0：否、1：是）
	 */
	private int isReceivePush;
	
	/**
	 * 是否禁用（0：否、1：是）
	 */
	private int isForbid;

	/**
	 * 创建日期
	 */
	private Date createDate;
	
	/**
	 * 腾讯openId
	 */
	private String tecentOpenId;
	
	/**
	 * 新浪uid
	 */
	private String sinaUid;
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUserNike() {
		return userNike;
	}

	public void setUserNike(String userNike) {
		this.userNike = userNike;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getSex() {
		return sex;
	}

	public void setSex(int sex) {
		this.sex = sex;
	}

	public String getPortraitUrl() {
		return portraitUrl;
	}

	public void setPortraitUrl(String portraitUrl) {
		this.portraitUrl = portraitUrl;
	}

	public int getIsReceivePush() {
		return isReceivePush;
	}

	public void setIsReceivePush(int isReceivePush) {
		this.isReceivePush = isReceivePush;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public int getIsForbid() {
		return isForbid;
	}

	public void setIsForbid(int isForbid) {
		this.isForbid = isForbid;
	}
	
	public String getTecentOpenId() {
		return tecentOpenId;
	}

	public void setTecentOpenId(String tecentOpenId) {
		this.tecentOpenId = tecentOpenId;
	}

	public String getSinaUid() {
		return sinaUid;
	}

	public void setSinaUid(String sinaUid) {
		this.sinaUid = sinaUid;
	}
	
} public class Constants {
	
	public static final boolean DEBUG = false;

	//SplashActivity
	public static final String FIRST_USE = "firstUse";
	public static final String IS_RECEIVE_PUSH = "isReceivePush";
	public static final String IS_LOAD_IMG = "isLoadImg";
	
	//http请求超时时间
	public static final int REQUEST_TIME_OUT = 15 * 1000;
	
	public static final int SUCCESS = 200;
	public static final int FAILURE = 500;
	public static final int SUCCESS_1 = 201;
	public static final int FAILURE_1 = 501;
	public static final int SUCCESS_2 = 202;
	public static final int FAILURE_2 = 502;
	
	public static final String SERVER_EXCEPTION = "500";
	public static final String PARAM_INVALUD = "501";
	public static final String SOURCE_EXISTS = "502";
	public static final String SOURCE_NOT_EXISTS = "503";
	public static final String OTHER_ERROR = "504";
	
	public static final String UPLOADFILE_PRE = "http://7xjehg.com1.z0.glb.clouddn.com/";
	public static final String LOGP_URL = "http://7xjehg.com1.z0.glb.clouddn.com/logo.png";
	
	public static final String CACHE_ALL_NEW = "cache_all_new";
	public static final String CACHE_ALL_HOT = "cache_all_hot";
	public static final String CACHE_QUSHI_NEW = "cache_qushi_new";
	public static final String CACHE_QUSHI_HOT = "cache_qushi_hot";
	public static final String CACHE_QUTU_NEW = "cache_qutu_new";
	public static final String CACHE_QUTU_HOT = "cache_qutu_hot";
	public static final String CACHE_MEITU_NEW = "cache_meitu_new";
	public static final String CACHE_MEITU_HOT = "cache_meitu_hot";
	
	//广点通
	public static final boolean TESTAD = false;   //标记测试
	public static final String GDT_APPId = "1104671631";
	public static final String GDT_APPWallPosId = "9050601571008638";
	public static final String GDT_SPLASHPosId = "5040000561500800";
	public static final String GDT_BANNERPosId = "7040104593531094";
	public static final String GDT_MEITU_BANNERPosId = "1030305547810972";
	
	//验证码发送短信
	public static final String SMS_SENDER = "10657120610111";
	
} public class PageResult<T> implements Serializable {

	private static final long serialVersionUID = -8689423380671812808L;

	public static final int DEFAULT_PAGE_SIZE = 10;
	
	private int pageIndex;
	private int pageSize;
	private int totalCount;
	private int pageCount;
	private List<T> list;

	public PageResult() {
		pageIndex = 1;
		pageSize = DEFAULT_PAGE_SIZE;
	}

	public PageResult(String _pageIndex) {
		this(_pageIndex, "");
	}

	public PageResult(String _pageIndex, String _pageSize) {
		int pageIndex = 1;
		int pageSize = DEFAULT_PAGE_SIZE;
		if (null == _pageIndex || "".equals(_pageIndex)) {
			pageIndex = 1;
		} else {
			try {
				pageIndex = Integer.parseInt(_pageIndex);
			} catch (Exception e) {
				pageIndex = 1;
			}
		}

		if (null == _pageSize || "".equals(_pageSize)) {
			pageSize = DEFAULT_PAGE_SIZE;
		} else {
			try {
				pageSize = Integer.parseInt(_pageSize);
			} catch (Exception e) {
				pageSize = DEFAULT_PAGE_SIZE;
			}
		}
		if (pageIndex < 1) {
			pageIndex = 1;
		}
		if (pageSize < 1) {
			pageSize = 1;
		}
		this.pageIndex = pageIndex;
		this.pageSize = pageSize;

	}

	public PageResult(int totalCount, Limit limit, List<T> list) {
		this.list = list;
        if(null == limit){
        	return;
        }
		this.pageIndex = limit.getPageId();
		this.pageSize = limit.getSize();
		this.setTotalCount(totalCount);
	}

	public PageResult(int pageIndex, int pageSize) {
		if (pageIndex < 1) {
			pageIndex = 1;
		}
		if (pageSize < 1) {
			pageSize = 1;
		}
		this.pageIndex = pageIndex;
		this.pageSize = pageSize;

	}

	/**
	 * @return the list
	 */
	public List<T> getList() {
		return list;
	}

	/**
	 * @param list the list to set
	 */
	public void setList(List<T> list) {
		this.list = list;
	}

	public PageResult(int pageIndex) {
		this(pageIndex, DEFAULT_PAGE_SIZE);
	}

	public int getPageIndex() {
		return pageIndex;
	}

	public int getPageSize() {
		return pageSize;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public int getPageCount() {
		return pageCount;
	}

	public int getFirstResult() {
		return (pageIndex - 1) * pageSize;
	}

	public boolean getHasPrevious() {
		return pageIndex > 1;
	}

	public boolean getHasNext() {
		return pageIndex < pageCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
		pageCount = totalCount / pageSize + (totalCount % pageSize == 0 ? 0 : 1);
		if (0 == totalCount) {
			if (pageIndex != 1) {
				pageIndex = 1;
			}
		} else {
			if (pageIndex > pageCount) {
				pageIndex = pageCount;
			}
		}
	}

	public int getPrev() {
		return this.pageIndex - 1;
	}

	public int getNext() {
		return this.pageIndex + 1;
	}

	public boolean isEmpty() {
		return 0 == totalCount;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public void setPageCount(int countInPage) {
		this.pageCount = countInPage;
	}

} public class DingCaiDAO {
	
	private static final String TAG = "PraiseDAO";
	private Context context;
	public DingCaiDAO(Context context) {
		this.context = context;
	}
	
	/**
	 * 检查是否点过赞
	 * @param userId
	 * @param jokeId
	 * @return
	 */
	public DingOrCai getDingOrCai(int userId, int jokeId) {
		DbUtils db = DbUtils.create(context);
		DingOrCai dingOrCai = null;
		try {
			dingOrCai = db.findFirst(Selector.from(DingOrCai.class).where(WhereBuilder.b("user_id", "=", userId).and("joke_id", "=", jokeId)));
			Log.d(TAG, "getDingOrCai success");
		} catch (DbException e) {
			Log.d(TAG, "getDingOrCai failure", e);
		}
		return dingOrCai;
	}
	
	/**
	 * 用户顶或者踩
	 * @param userId
	 * @param jokeId
	 * @param dingOrCai  标记是顶是踩
	 */
	public void dingOrCai(int userId, int jokeId, int dingOrCai, int num) {
		DbUtils db = DbUtils.create(context);
		DingOrCai praise = new DingOrCai();
		praise.setJokeId(jokeId);
		praise.setUserId(userId);
		praise.setDingOrCai(dingOrCai);
		praise.setNum(num);
		praise.setIsUpload(DingOrCai.NOT_UPLOAD);
		try {
			db.save(praise);
			Log.d(TAG, "dingOrCai success");
		} catch (DbException e) {
			Log.d(TAG, "dingOrCai failure", e);
		}
	}
	
	/**
	 * 查找未同步到服务器的点赞数据
	 * @return
	 */
	public List<DingOrCai> getUnUpload() {
		DbUtils db = DbUtils.create(context);
		List<DingOrCai> dbModels = null;
		try {
			dbModels = db.findAll(Selector.from(DingOrCai.class).where(WhereBuilder.b("is_upload", "=", DingOrCai.NOT_UPLOAD)));
			Log.d(TAG, "getUnUpload success");
		} catch (DbException e) {
			Log.d(TAG, "getUnUpload failure", e);
		}
		return dbModels;
	}
	
	/**
	 * 修改同步后的数据
	 * @param praises
	 */
	public void upload(List<DingOrCai> praises) {
		for (DingOrCai praise : praises) {
			praise.setIsUpload(DingOrCai.UPLOAD);
		}
		DbUtils db = DbUtils.create(context);
		try {
			db.updateAll(praises, "is_upload");
			Log.d(TAG, "upload praise success");
		} catch (DbException e) {
			Log.d(TAG, "upload praise failure", e);
		}
	}
	
} public interface ApiCallBack {
	
	void onSuccess(Object data);
	
	void onFailure(String msg);
	
	void onError(Exception e, String msg);
} public interface IJokeService {

	/**
	 * 获取趣事列表
	 * @param handler
	 * @param newOrHotFlag
	 * @param offset
	 * @param count
	 */
	public void getList(Handler handler, int type, int newOrHotFlag, int offset, int count);
	
	/**
	 * 刷新趣事列表
	 * @param handler
	 * @param newOrHotFlag
	 * @param count
	 */
	public void refush(Handler handler, int type, int newOrHotFlag, int count);
	
	/**
	 * 获取所有内容列表
	 * @param handler
	 * @param newOrHotFlag
	 * @param offset
	 * @param count
	 */
	public void getAll(Handler handler, int newOrHotFlag, int offset, int count);
	
	/**
	 * 刷新所有内容列表
	 * @param handler
	 * @param newOrHotFlag
	 * @param count
	 */
	public void refushAll(Handler handler, int newOrHotFlag, int count);
	
	/**
	 * 根据jokeid获取评论列表
	 * @param handler
	 * @param jokeId
	 * @param offset
	 * @param count
	 */
	public void getCommentByJokeId(Handler handler, int jokeId, int offset, int count);
	
	/**
	 * 顶joke
	 * @param dingOrCais
	 */
	public void ding(List<DingOrCai> dingOrCais);
	
	/**
	 * 踩joke
	 * @param dingOrCais
	 */
	public void cai(List<DingOrCai> dingOrCais);
	
	/**
	 * 用户评论joke
	 * @param handler
	 * @param jokeId
	 * @param userId
	 * @param userPortrait
	 * @param userNick
	 * @param content
	 */
	public void addComment(Handler handler, Integer jokeId, String content);
	
	/**
	 * 根据jokeId获取joke对象
	 * @param apiCallBack
	 * @param jokeId
	 */
	public void getJokeById(ApiCallBack apiCallBack, Integer jokeId);
} public class JokeServiceImpl implements IJokeService {
	private static final String TAG = "QuShiServiceImpl";
	private Context mContext;
	private DingCaiDAO mDingCaiDAO;
	
	public JokeServiceImpl(Context context) {
		mContext = context;
		mDingCaiDAO = new DingCaiDAO(context);
	}
	
	@Override
	public void getAll(final Handler handler, int newOrHotFlag, int offset, int count) {
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(1000 * 60 * 10); //缓存超期时间10分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
		params.addQueryStringParameter("offset", String.valueOf(offset));
		params.addQueryStringParameter("count", String.valueOf(count));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_LIST, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						String rs = responseInfo.result;
						Map map = FastjsonUtil.json2Map(rs);
						int code = Integer.parseInt(String.valueOf(map.get("code")));
						if (code != 200) {
							//请求失败
							handler.sendEmptyMessage(Constants.FAILURE);
							return;
						}
						PageResult page = FastjsonUtil.deserialize(
								map.get("data").toString(), PageResult.class);
						Message message = new Message();
						Bundle bundle = new Bundle();
						bundle.putSerializable("pageResult", page);
						message.what = Constants.SUCCESS;
						message.setData(bundle);
						handler.sendMessage(message);
					} catch (Exception e) {
						handler.sendEmptyMessage(Constants.FAILURE);
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			});
	}

	@Override
	public void refushAll(final Handler handler, int newOrHotFlag, int count) {
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(0); //缓存超期时间0分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
		params.addQueryStringParameter("count", String.valueOf(count));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_LIST, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						String rs = responseInfo.result;
						Map map = FastjsonUtil.json2Map(rs);
						int code = Integer.parseInt(String.valueOf(map.get("code")));
						if (code != 200) {
							//请求失败
							handler.sendEmptyMessage(Constants.FAILURE);
							return;
						}
						PageResult page = FastjsonUtil.deserialize(
								map.get("data").toString(), PageResult.class);
						Message message = new Message();
						Bundle bundle = new Bundle();
						bundle.putSerializable("pageResult", page);
						message.what = Constants.SUCCESS_1;
						message.setData(bundle);
						handler.sendMessage(message);
					} catch (Exception e) {
						handler.sendEmptyMessage(Constants.FAILURE);
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			});
	}
	
	@Override
	public void getList(final Handler handler, int type, int newOrHotFlag, int offset,
			int count) {
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(1000 * 60 * 10); //缓存超期时间10分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("type", String.valueOf(type));
		params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
		params.addQueryStringParameter("offset", String.valueOf(offset));
		params.addQueryStringParameter("count", String.valueOf(count));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_LIST, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						String rs = responseInfo.result;
						Map map = FastjsonUtil.json2Map(rs);
						int code = Integer.parseInt(String.valueOf(map.get("code")));
						if (code != 200) {
							//请求失败
							handler.sendEmptyMessage(Constants.FAILURE);
							return;
						}
						PageResult page = FastjsonUtil.deserialize(
								map.get("data").toString(), PageResult.class);
						Message message = new Message();
						Bundle bundle = new Bundle();
						bundle.putSerializable("pageResult", page);
						message.what = Constants.SUCCESS;
						message.setData(bundle);
						handler.sendMessage(message);
					} catch (Exception e) {
						handler.sendEmptyMessage(Constants.FAILURE);
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			});
	}

	@Override
	public void refush(final Handler handler, int type, int newOrHotFlag, int count) {
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(0); //缓存超期时间0分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("type", String.valueOf(type));
		params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
		params.addQueryStringParameter("count", String.valueOf(count));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_LIST, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						String rs = responseInfo.result;
						Map map = FastjsonUtil.json2Map(rs);
						int code = Integer.parseInt(String.valueOf(map.get("code")));
						if (code != 200) {
							//请求失败
							handler.sendEmptyMessage(Constants.FAILURE);
							return;
						}
						PageResult page = FastjsonUtil.deserialize(
								map.get("data").toString(), PageResult.class);
						Message message = new Message();
						Bundle bundle = new Bundle();
						bundle.putSerializable("pageResult", page);
						message.what = Constants.SUCCESS_1;
						message.setData(bundle);
						handler.sendMessage(message);
					} catch (Exception e) {
						handler.sendEmptyMessage(Constants.FAILURE);
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			});
	}

	@Override
	public void getCommentByJokeId(final Handler handler, int jokeId, int offset,
			int count) {
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(60); //缓存超期时间10分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("qushiId", String.valueOf(jokeId));
		params.addQueryStringParameter("offset", String.valueOf(offset));
		params.addQueryStringParameter("count", String.valueOf(count));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_GET_COMMENTS, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if (code != 200) {
						//请求失败
						handler.sendEmptyMessage(Constants.FAILURE);
						return;
					}
					PageResult page = FastjsonUtil.deserialize(
							map.get("data").toString(), PageResult.class);
					Message message = new Message();
					Bundle bundle = new Bundle();
					bundle.putSerializable("pageResult", page);
					message.what = Constants.SUCCESS;
					message.setData(bundle);
					handler.sendMessage(message);
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			});
	}

	@Override
	public void ding(final List<DingOrCai> dingOrCais) {
		if(dingOrCais == null || dingOrCais.size() == 0) {
			return;
		}
		StringBuilder sb = new StringBuilder();
		for (DingOrCai dingOrCai : dingOrCais) {
			sb.append(dingOrCai.getJokeId()).append(",");
		}
		String ids = sb.toString().substring(0, sb.toString().length() - 1);
		HttpUtils http = new HttpUtils();
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("ids", ids);
		http.send(HttpRequest.HttpMethod.POST,
			RcpUri.INTERFACE_URI_DING, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if (code != 200) {
						//请求失败
						Log.e(TAG, "ding failure:" + map.get("desc"));
						return;
					}
					//修改本地数据库
					TaskExecutor.executeTask(new Runnable() {
						@Override
						public void run() {
							mDingCaiDAO.upload(dingOrCais);
						}
					});
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					Log.e(TAG, "ding failure", error);
				}
			});
	}

	@Override
	public void cai(final List<DingOrCai> dingOrCais) {
		if(dingOrCais == null || dingOrCais.size() == 0) {
			return;
		}
		StringBuilder sb = new StringBuilder();
		for (DingOrCai dingOrCai : dingOrCais) {
			sb.append(dingOrCai.getJokeId()).append(",");
		}
		String ids = sb.toString().substring(0, sb.toString().length() - 1);
		HttpUtils http = new HttpUtils();
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("ids", ids);
		http.send(HttpRequest.HttpMethod.POST,
			RcpUri.INTERFACE_URI_CAI, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if (code != 200) {
						//请求失败
						Log.e(TAG, "cai failure:" + map.get("desc"));
						return;
					}
					//修改本地数据库
					TaskExecutor.executeTask(new Runnable() {
						@Override
						public void run() {
							mDingCaiDAO.upload(dingOrCais);
						}
					});
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					Log.e(TAG, "cai failure", error);
				}
			});
	}

	@Override
	public void addComment(final Handler handler, Integer jokeId, String content) {
		if(App.currentUser == null || Util.isEmpty(content)) {
			return;
		}
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(1000 * 60 * 10); //缓存超期时间10分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("jokeId", String.valueOf(jokeId));
		params.addQueryStringParameter("userId", String.valueOf(App.currentUser.getId()));
		params.addQueryStringParameter("userPortrait", App.currentUser.getPortraitUrl());
		try {
			params.addQueryStringParameter("userNick", 
					URLEncoder.encode(App.currentUser.getUserNike(), "UTF-8"));
			params.addQueryStringParameter("content", 
					URLEncoder.encode(content, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		http.send(HttpRequest.HttpMethod.POST,
			RcpUri.INTERFACE_URI_COMMENT, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if (code != 200) {
						//请求失败
						Log.e(TAG, "comment failure");
						ToastUtils.showMessage(mContext, R.string.comment_fail);
						handler.sendEmptyMessage(Constants.FAILURE_1);
						return;
					}
					Log.e(TAG, "comment success");
					handler.sendEmptyMessage(Constants.SUCCESS_1);
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					Log.e(TAG, "comment failure", error);
					handler.sendEmptyMessage(Constants.FAILURE_1);
					if(!HttpUtil.isNetworkAvailable(mContext)) {
						ToastUtils.showMessage(mContext, R.string.no_net);
					} else {
						ToastUtils.showMessage(mContext, R.string.comment_fail);
					}
				}
			});
	}

	@Override
	public void getJokeById(final ApiCallBack apiCallBack, Integer jokeId) {
		HttpUtils http = new HttpUtils();
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		http.configDefaultHttpCacheExpiry(0); 
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("jokeId", String.valueOf(jokeId));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_GET_JOKE, params,
			new RequestCallBack<String>() {
				@SuppressWarnings("rawtypes")
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if(code == Constants.SUCCESS) {
						Log.e(TAG, "getJokeById success");
						Joke joke = FastjsonUtil.deserialize(
								map.get("data").toString(), Joke.class);
						apiCallBack.onSuccess(joke);
					} else {
						Log.e(TAG, "getJokeById fail, fail msg is " + map.get("msg"));
						apiCallBack.onFailure(String.valueOf(code));
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					Log.e(TAG, "getJokeById error", error);
					if(!HttpUtil.isNetworkAvailable(mContext)) {
						ToastUtils.showMessage(mContext, R.string.no_net);
					} else {
						apiCallBack.onError(error, msg);
					}
				}
			});
	}

} public class LoadListView extends ListView implements
		OnScrollListener {

    private LayoutInflater inflater;  
  
    //上啦加载布局
    private View footView;
    
    private ImageView footerProgressImg;
    private Animation progressAnimation;
    
    private boolean haveScrollbar = true;  
  
    public LoadListView(Context context) {  
        super(context);  
        init(context);  
    }  
  
    public LoadListView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        init(context);  
    }  
  
    private void init(Context context) { 
    	progressAnimation = AnimationUtils.loadAnimation(context,
				R.anim.progress_anim);
    	inflater = LayoutInflater.from(context);
        footView = inflater.inflate(R.layout.footer, null);
//        footView.findViewById(R.id.load_layout).setVisibility(View.GONE);
        footerProgressImg = (ImageView) footView.findViewById(R.id.progress);
        footerProgressImg.startAnimation(progressAnimation);
        addFooterView(footView, null, false);
        // 设置滚动监听事件  
//        setOnScrollListener(this);  
        //设置listview加载时不滚动
		setOnScrollListener(new PauseOnScrollListener(BitmapUtil.mBitmapUtils, false, true, this));
  
    }  
	private boolean isLoadingable = false; //是否可以加载更多
	private boolean hasMoreData = false;  //有更多数据
	//正在加载底部数据
	private boolean isFootLoading = false;
	
	public void setHasMoreData(boolean hasMoreData) {
		this.hasMoreData = hasMoreData;
		if(!hasMoreData) {
			footView.findViewById(R.id.load_layout).setVisibility(View.GONE);
		}
	}
    @Override  
    public void onScrollStateChanged(AbsListView view, int scrollState) {  
    	if(isFootLoading)
			return;		
		if(isLoadingable && scrollState==SCROLL_STATE_IDLE && hasMoreData){
			prepareFootLoading();
		}
    }  
    
    public void prepareFootLoading() {
    	if(isFootLoading) {
    		return;
    	}
    	footerProgressImg.startAnimation(progressAnimation);
		footView.findViewById(R.id.load_layout).setVisibility(View.VISIBLE);
		isFootLoading = true;
		setSelectionFromTop(getCount()-1, 0);  //滚动到最底端
		onFootLoading();
    }
  
    @Override  
    public void onScroll(AbsListView view, int firstVisibleItem,  
        int visibleItemCount, int totalItemCount) {  
		//因为刚进入的时候,lastPos=-1,count=0,这个时候不能让它执行onAddFoot方法
		if(getLastVisiblePosition()==totalItemCount-1 && !isLoadingable && getLastVisiblePosition() != -1){
			isLoadingable = true;
		}	
    }  
  
    /**
	 * 上拉刷新监听器
	 *
	 */
	public interface OnFootLoadingListener{
		/**
		 * 这里是执行后台获取数据的过程
		 */
		void onFootLoading();
	}
	private OnFootLoadingListener onFootLoadingListener;
	public void setOnFootLoadingListener(
			OnFootLoadingListener onFootLoadingListener) {
		this.onFootLoadingListener = onFootLoadingListener;
	}
	
	//加载更多
	private void onFootLoading() {
		if(onFootLoadingListener != null) {
			onFootLoadingListener.onFootLoading();
		}
	}
	
	/**
	 * 底部数据加载完成,用户需要加入一个removeFootView的操作
	 */
	public void onFootLoadingComplete(boolean goneFooter){
		isLoadingable = false;
		isFootLoading = false;
		if(goneFooter){
			if(progressAnimation != null) {
				progressAnimation.cancel();
			}
			footView.findViewById(R.id.load_layout).setVisibility(View.GONE);
		}		
	}
  
    public void setMoreDataMsg(String moreDataMsg) {
    	if(footView != null) {
    		((TextView) footView.findViewById(R.id.more_data_msg)).setText(moreDataMsg);
    	}
	}
    
    public void setHaveScrollbar(boolean haveScrollbar) {   
        this.haveScrollbar = haveScrollbar;   
    }  
	
	@Override   
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {   
        if (haveScrollbar == false) {   
            int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);   
            super.onMeasure(widthMeasureSpec, expandSpec);   
        } else {   
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);   
        }   
    } 
}   public interface OnFootLoadingListener{
	/**
	 * 这里是执行后台获取数据的过程
	 */
	void onFootLoading();
} public class Scroll2BottomListenerScrollView extends ScrollView {

	private LoadListView mListView;
	
	public Scroll2BottomListenerScrollView(Context context) {  
        super(context);  
    }  
  
    public Scroll2BottomListenerScrollView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
    }  
    
    
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
    	if(t + getHeight() >=  computeVerticalScrollRange()) {
    		if(mListView != null) {
    			mListView.prepareFootLoading();
    		}
    	}
    }
    
    
    public void setmListView(LoadListView mListView) {
		this.mListView = mListView;
	}
    

} public class SharePopWindow extends PopupWindow implements OnClickListener, IWeiboHandler.Response {
	private final String TAG = "SharePopWindow";
	private Context context;
	private Joke mJoke;  //要分享的内容
	private CollectDAO collectDAO;
	private Collect collect;
	IWXAPI api;   //微信api
	private WeiboAPI weiBoAPI;//qq微博API
	private String accessToken = null;  //qq微博token
	
	/** 微博微博分享接口实例 */
    private IWeiboShareAPI  mWeiboShareAPI = null;
	
	//分享时app Logo地址
	private String appLogoUrl = com.lling.qiqu.commons.Constants.LOGP_URL;
	//分享时点击链接地址
	private String targetUrl = RcpUri.INTERFACE_URI_SHARE;
	private int userId = -1;
	private String title;
	private String description; 
	
	public SharePopWindow(Context context) {
		this.context = context;
		collectDAO = new CollectDAO(context);
		api = WXAPIFactory.createWXAPI(context, com.lling.qiqu.wxapi.Constants.APP_ID);
		LayoutInflater inflater = (LayoutInflater) context
	                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    View view = inflater.inflate(R.layout.popup_share, null);
	    view.findViewById(R.id.share_weixin).setOnClickListener(this);
	    view.findViewById(R.id.share_pengyouquan).setOnClickListener(this);
	    view.findViewById(R.id.share_qqfriends).setOnClickListener(this);
	    view.findViewById(R.id.share_qqzone).setOnClickListener(this);
	    view.findViewById(R.id.share_qqweibo).setOnClickListener(this);
	    view.findViewById(R.id.share_sinaweibo).setOnClickListener(this);
	    view.findViewById(R.id.share_sms).setOnClickListener(this);
	    view.findViewById(R.id.share_copy).setOnClickListener(this);
	    view.findViewById(R.id.share_collect).setOnClickListener(this);
		initWindow();
		this.setContentView(view);
	}
	
	/**
     * 初始化窗口
     */
    private void initWindow() {
    	this.setClippingEnabled(false);
    	this.setWidth(LayoutParams.MATCH_PARENT);
        //设置弹出窗体的高
        this.setHeight(LayoutParams.WRAP_CONTENT);
        //设置弹出窗体可点击
        this.setFocusable(true);
        //设置弹出窗体动画效果
        this.setAnimationStyle(R.style.inoutformbottom);
        //实例化一个ColorDrawable颜色为半透明   (在此设置背景后此窗口不会出现黑色边框)
        ColorDrawable dw = new ColorDrawable(0xFFFFFFFF);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        
		//popupwindow消失的时候让窗口背景恢复
		this.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				Activity activity = ((Activity) context).getParent();
				if (activity == null) {
					activity = ((Activity) context);
				}
				WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
				lp.alpha = 1f;
				activity.getWindow().setAttributes(lp);
			}
		});
    }
    
    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
    	if(App.currentUser != null) {
			userId = App.currentUser.getId();
    	}
    	collect = collectDAO.getCollect(userId, mJoke.getId());
    	if(collect != null) {  //收藏过
    		getContentView().findViewById(R.id.share_collect).setSelected(true);
    	} else {
    		getContentView().findViewById(R.id.share_collect).setSelected(false);
    	}
    	Activity activity = ((Activity)context).getParent();
    	if(activity == null) {
    		activity = ((Activity)context);
    	}
    	WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.alpha = 0.4f;
		activity.getWindow().setAttributes(lp);
		activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		super.showAtLocation(parent, gravity, x, y);
    }

	@Override
	public void onClick(View v) {
		if(mJoke == null) {
			return;
		}
		switch (v.getId()) {
		case R.id.share_weixin:   //微信
			share2WeiXin(SendMessageToWX.Req.WXSceneSession);
			MobclickAgent.onEvent(context, "share_weixin");
			saveShareTimes();
			break;
		case R.id.share_pengyouquan:  //朋友圈
			share2WeiXin(SendMessageToWX.Req.WXSceneTimeline);
			MobclickAgent.onEvent(context, "share_pengyouquan");
			saveShareTimes();
			break;
		case R.id.share_qqfriends:  //QQ好友
			share2QQFriends();
			MobclickAgent.onEvent(context, "share_qq");
			saveShareTimes();
			break;
		case R.id.share_qqzone:  //QQ空间
			share2QZone();
			MobclickAgent.onEvent(context, "share_qqzone");
			saveShareTimes();
			break;
		case R.id.share_qqweibo:  //QQ微博
			share2QQWeibo();
			MobclickAgent.onEvent(context, "share_qqweibo");
			saveShareTimes();
			break;
		case R.id.share_sinaweibo:  //新浪微博
			share2SinaWeibo();
			MobclickAgent.onEvent(context, "share_sina_weibo");
			saveShareTimes();
			break;
		case R.id.share_sms:  //短信
			sendSms();
			MobclickAgent.onEvent(context, "share_sms");
			break;
		case R.id.share_copy:  //复制
			copy();
			MobclickAgent.onEvent(context, "share_copy");
			break;
		case R.id.share_collect:  //收藏
			if(collect == null) {  
				v.setSelected(true);
				collect();
			} else {   //取消收藏
				v.setSelected(false);
				cancelCollect();
			}
			break;
		}
		this.dismiss();
	}
	
	/**
	 * 分享到微信朋友或者朋友圈
	 * @param scene 标记是发送朋友圈还是微信好友
	 */
	private void share2WeiXin(int scene) {
		if(!api.isWXAppInstalled()) {
			if(scene == SendMessageToWX.Req.WXSceneSession) {
				ToastUtils.showMessageInCenter(context, "您没有安装【微信】\n安装后才能分享到微信好友");
			} else {
				ToastUtils.showMessageInCenter(context, "您没有安装【微信】\n安装后才能分享到朋友圈");
			}
		}
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = targetUrl + mJoke.getId();
		WXMediaMessage msg = new WXMediaMessage(webpage);
		Bitmap thumb = null;
		switch (mJoke.getType()) {
		case Joke.TYPE_QUSHI:
			msg.title = context.getString(R.string.share_title_qushi);
			msg.description = mJoke.getContent();
			thumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
			break;
		case Joke.TYPE_QUTU:
			msg.title = context.getString(R.string.share_title_qutu);
			msg.description = mJoke.getTitle();
			//微信分享缩略图最大不能超过32K,否则无法调开微信界面
			thumb = BitmapUtil.getThumbBitmapFromCache(mJoke.getImgUrl(), 100, 100);
			break;
		case Joke.TYPE_MEITU:
			msg.title = context.getString(R.string.share_title_meitu);
			msg.description = mJoke.getTitle();
			thumb = BitmapUtil.getThumbBitmapFromCache(mJoke.getImgUrl(), 100, 100);
			break;
		}
		msg.thumbData = ImgUtil.bmpToByteArray(thumb, true);
		
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;
		req.scene = scene;
		api.sendReq(req);
		thumb.recycle();
	}
	
	/**
	 * 分享到QQ好友
	 */
	private void share2QQFriends() {
		final Bundle params = new Bundle();
	    params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
	    switch (mJoke.getType()) {
		case Joke.TYPE_QUSHI:
			params.putString(QQShare.SHARE_TO_QQ_TITLE, context.getString(R.string.share_title_qushi));
			params.putString(QQShare.SHARE_TO_QQ_SUMMARY,  mJoke.getContent().trim());
			//这里应该填写应用图标的图片
			params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, appLogoUrl);
			break;
		case Joke.TYPE_QUTU:
			params.putString(QQShare.SHARE_TO_QQ_TITLE, context.getString(R.string.share_title_qutu));
			params.putString(QQShare.SHARE_TO_QQ_SUMMARY, mJoke.getTitle());
			params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, mJoke.getImgUrl());
			break;
		case Joke.TYPE_MEITU:
			params.putString(QQShare.SHARE_TO_QQ_TITLE, context.getString(R.string.share_title_meitu));
			params.putString(QQShare.SHARE_TO_QQ_SUMMARY, mJoke.getTitle());
			params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, mJoke.getImgUrl());
			break;
		}
	    //加入点击链接
	    params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, targetUrl + mJoke.getId());
	    params.putString(QQShare.SHARE_TO_QQ_APP_NAME, context.getString(R.string.app_name));
	    App.mTencent.shareToQQ((Activity)context, params, iUiListener);
	}
	
	/**
	 * 分享到QQ空间
	 */
	private void share2QZone() {
		ArrayList<String> imgList = new ArrayList<String>();
		//分享类型
		final Bundle params = new Bundle();
		params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
		switch (mJoke.getType()) {
		case Joke.TYPE_QUSHI:
			params.putString(QzoneShare.SHARE_TO_QQ_TITLE, context.getString(R.string.share_title_qushi));
			params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,  mJoke.getContent().trim());
			//这里应该填写应用图标的图片
			imgList.add(appLogoUrl);
			params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imgList);
			break;
		case Joke.TYPE_QUTU:
			params.putString(QzoneShare.SHARE_TO_QQ_TITLE, context.getString(R.string.share_title_qutu));
			params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,  mJoke.getTitle());
			imgList.add(mJoke.getImgUrl());
			params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imgList);
			break;
		case Joke.TYPE_MEITU:
			params.putString(QzoneShare.SHARE_TO_QQ_TITLE, context.getString(R.string.share_title_meitu));
			params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, mJoke.getTitle());
			imgList.add(mJoke.getImgUrl());
			params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imgList);
			break;
		}
		params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, targetUrl + mJoke.getId());//必填
		App.mTencent.shareToQzone((Activity)context, params, iUiListener);
	}
	
	private IUiListener iUiListener = new IUiListener() {
		@Override
		public void onError(UiError arg0) {
			ToastUtils.showMessageInCenter(context, "分享失败，请重试");
			Log.e("IUiListener", "qq share error" + arg0.errorCode + arg0.errorMessage + arg0.errorDetail);
		}
		@Override
		public void onComplete(Object arg0) {
			ImgToastUtils.showMessage(context, "分享成功", R.drawable.center_ok_tip);
		}
		@Override
		public void onCancel() {
		}
	};
	
	/**
	 * 分享到新浪微博
	 */
	private void share2SinaWeibo() {
		Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(context);
		if(accessToken != null && accessToken.isSessionValid()) {
			initShareWeiboAPI();
	        share2weibo();
		} else {   //需要授权登录
			initSinaWeiBo();
			initShareWeiboAPI();
			mSsoHandler.authorize(new AuthListener());   //授权后再分享
		}
	}
	
	private void initShareWeiboAPI() {
		if(mWeiboShareAPI == null) {
			mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(context, com.sina.weibo.Constants.APP_KEY);
		}
		// 注册第三方应用到微博客户端中，注册成功后该应用将显示在微博的应用列表中。
        // 但该附件栏集成分享权限需要合作申请，详情请查看 Demo 提示
        // NOTE：请务必提前注册，即界面初始化的时候或是应用程序初始化时，进行注册
        mWeiboShareAPI.registerApp();
        mWeiboShareAPI.handleWeiboResponse(((Activity)context).getIntent(), this);
	}
	
	//新浪微博登录
	private AuthInfo mAuthInfo;
    /** 封装了 "access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能  */
    private Oauth2AccessToken mAccessToken;
    /** 注意：SsoHandler 仅当 SDK 支持 SSO 时有效 */
    private SsoHandler mSsoHandler;
	// 创建微博实例
    private void initSinaWeiBo() {
        //mWeiboAuth = new WeiboAuth(this, Constants.APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE);
        // 快速授权时，请不要传入 SCOPE，否则可能会授权不成功
    	if(mAuthInfo == null) {
    		mAuthInfo = new AuthInfo(context, com.sina.weibo.Constants.APP_KEY, com.sina.weibo.Constants.REDIRECT_URL, com.sina.weibo.Constants.SCOPE);
    	}
        if(mSsoHandler == null) {
        	mSsoHandler = new SsoHandler((Activity)context, mAuthInfo);
        }
    }
	
	private void share2weibo() {
		setShareContent();
		// 1. 初始化微博的分享消息
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.mediaObject = getWebpageObj();
        weiboMessage.textObject = getTextObj();    //这里可以设置文本
        if(mJoke.getType() != Joke.TYPE_QUSHI) {
        	weiboMessage.imageObject = getImageObj();
        }
       // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        
        AuthInfo authInfo = new AuthInfo(context, com.sina.weibo.Constants.APP_KEY, com.sina.weibo.Constants.REDIRECT_URL, com.sina.weibo.Constants.SCOPE);
        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(context);
        String token = "";
        if (accessToken != null) {
            token = accessToken.getToken();
        }
        mWeiboShareAPI.sendRequest((Activity)context, request, authInfo, token, new WeiboAuthListener() {
            @Override
            public void onWeiboException( WeiboException arg0 ) {
            	Log.e(TAG, "share sina weibo error", arg0);
            	ToastUtils.showMessage(context, "分享失败");
            }
            @Override
            public void onComplete( Bundle bundle ) {
                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
                AccessTokenKeeper.writeAccessToken(context, newToken);
                ImgToastUtils.showMessage(context, "分享成功", R.drawable.center_ok_tip);
            }
            @Override
            public void onCancel() {
            }
        });
	}
	
	/**
     * 创建多媒体（网页）消息对象。
     * 
     * @return 多媒体（网页）消息对象。
     */
    private WebpageObject getWebpageObj() {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = "";
        mediaObject.description = "";
        // 设置 Bitmap 类型的图片到视频对象里
        mediaObject.setThumbImage(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher));
        mediaObject.actionUrl = targetUrl + mJoke.getId();
        mediaObject.schema = "";
        return mediaObject;
    }
    /**
     * 创建文本消息对象。
     * 
     * @return 文本消息对象。
     */
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = "分享自#奇趣营#" + description;
        return textObject;
    }
    /**
     * 创建图片消息对象。
     * 
     * @return 图片消息对象。
     */
    private ImageObject getImageObj() {
    	Bitmap bitmap = BitmapUtil.getBitmapFromCache(mJoke.getImgUrl());
    	if(bitmap == null) {
    		return null;
    	}
        ImageObject imageObject = new ImageObject();
        imageObject.setImageObject(bitmap);
        imageObject.title = title;
        imageObject.description = description;
        imageObject.actionUrl = targetUrl + mJoke.getId();
        return imageObject;
    }
    
    private void setShareContent() {
    	switch (mJoke.getType()) {
		case Joke.TYPE_QUSHI:
			title = context.getString(R.string.share_title_qushi);
			description = mJoke.getContent().trim();
			break;
		case Joke.TYPE_QUTU:
			title = context.getString(R.string.share_title_qutu);
			description = mJoke.getTitle();
			break;
		case Joke.TYPE_MEITU:
			title = context.getString(R.string.share_title_meitu);
			description = mJoke.getTitle();
			break;
		}
    }
	
	/**
	 * 收藏
	 */
	private void collect() {
		if(mJoke == null) {
			return;
		}
		String jokeContent = FastjsonUtil.serialize(mJoke);
		collectDAO.collect(userId, mJoke.getId(), jokeContent);
		ImgToastUtils.showMessage(context, "收藏成功", R.drawable.ic_toast_fav);
		MobclickAgent.onEvent(context, "collect");
	}
	
	/**
	 * 取消收藏
	 */
	private void cancelCollect() {
		if(mJoke == null) {
			return;
		}
		collectDAO.cancelCollect(mJoke.getId());
		ImgToastUtils.showMessage(context, "已取消收藏", R.drawable.ic_toast_unfav);
		if(context instanceof MyCollectActivity) {
			((MyCollectActivity)context).cancelCollect(mJoke);
		}
	}
	
	/**
	 * 调用短消息
	 */
	private void sendSms() {
		StringBuffer sb = new StringBuffer();
		sb.append("分享自#奇趣营#");
		if(mJoke.getType() == Joke.TYPE_QUSHI) {
			sb.append(mJoke.getContent());
		} else {
			sb.append(mJoke.getTitle());
		}
		sb.append(targetUrl + mJoke.getId());
		String content = sb.toString().trim();
		Uri smsToUri = Uri.parse("smsto:");// 联系人地址 
        Intent mIntent = new Intent(android.content.Intent.ACTION_SENDTO, 
                smsToUri); 
        mIntent.putExtra("sms_body", 
        		content);// 短信内容 
        context.startActivity(mIntent); 
	}
	
	/**
	 * 复制内容
	 * 分享自#奇趣营#+内容+url
	 */
	@SuppressLint("NewApi")
	private void copy() {
		StringBuffer sb = new StringBuffer();
		sb.append("分享自#奇趣营#");
		if(mJoke.getType() == Joke.TYPE_QUSHI) {
			sb.append(mJoke.getContent());
		} else {
			sb.append(mJoke.getTitle());
		}
		sb.append(targetUrl + mJoke.getId());
		String content = sb.toString().trim();
		if (android.os.Build.VERSION.SDK_INT > 11) {
			android.content.ClipboardManager c = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
			c.setPrimaryClip(ClipData.newPlainText(content, content));
		} else {
			android.text.ClipboardManager c = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
			c.setText(content);
		}
		ToastUtils.showMessageInCenter(context, "已复制到剪贴板");
	}
	
	/**
	 * 分享到QQ微博
	 */
	private void share2QQWeibo() {
		accessToken = Util.getSharePersistent(context, "ACCESS_TOKEN");
		if(com.lling.qiqu.utils.Util.isEmpty(accessToken)) {
			auth(Constants.APP_KEY, Constants.APP_KEY_SEC);
		} else {
			qqWeiboReAdd();
		}
	}
	
	/**
	 * qq微博授权
	 * @param appid
	 * @param app_secket
	 */
	private void auth(final long appid, final String app_secket) {
		//注册当前应用的appid和appkeysec，并指定一个OnAuthListener
		//OnAuthListener在授权过程中实施监听
		AuthHelper.register(context, appid, app_secket, new OnAuthListener() {
			//如果当前设备没有安装腾讯微博客户端，走这里
			@Override
			public void onWeiBoNotInstalled() {
				AuthHelper.unregister(context);
				Intent i = new Intent(context, Authorize.class);
				context.startActivity(i);
			}
			//如果当前设备没安装指定版本的微博客户端，走这里
			@Override
			public void onWeiboVersionMisMatch() {
				AuthHelper.unregister(context);
				Intent i = new Intent(context, Authorize.class);
				context.startActivity(i);
			}
			//如果授权失败，走这里
			@Override
			public void onAuthFail(int result, String err) {
				ToastUtils.showMessage(context, "授权失败");
				AuthHelper.unregister(context);
			}
			//授权成功，走这里
			//授权成功后，所有的授权信息是存放在WeiboToken对象里面的，可以根据具体的使用场景，将授权信息存放到自己期望的位置，
			//在这里，存放到了applicationcontext中
			@Override
			public void onAuthPassed(String name, WeiboToken token) {
				Util.saveSharePersistent(context, "ACCESS_TOKEN", token.accessToken);
				Util.saveSharePersistent(context, "EXPIRES_IN", String.valueOf(token.expiresIn));
				Log.e("String.valueOf(token.expiresIn)", String.valueOf(token.expiresIn));
				Util.saveSharePersistent(context, "OPEN_ID", token.openID);
//				Util.saveSharePersistent(context, "OPEN_KEY", token.omasKey);
				Util.saveSharePersistent(context, "REFRESH_TOKEN", "");
//				Util.saveSharePersistent(context, "NAME", name);
//				Util.saveSharePersistent(context, "NICK", name);
				Util.saveSharePersistent(context, "CLIENT_ID", appid+"");
				Util.saveSharePersistent(context, "AUTHORIZETIME",
						String.valueOf(System.currentTimeMillis() / 1000l));
				AuthHelper.unregister(context);
				accessToken = token.accessToken;
				qqWeiboReAdd();
			}
		});

		AuthHelper.auth(context, "");
	}
	
	/**
	 * 分享到qq微博
	 */
	private void qqWeiboReAdd() {
		AccountModel account = new AccountModel(accessToken);
		weiBoAPI = new WeiboAPI(account);
		StringBuffer sb = new StringBuffer();
		sb.append("分享自#奇趣营#");
		String imgPath = null;
		switch (mJoke.getType()) {
		case Joke.TYPE_QUSHI:
			sb.append(mJoke.getContent());
			break;
		case Joke.TYPE_QUTU:
			sb.append(mJoke.getTitle());
			imgPath = mJoke.getImgUrl();
			break;
		case Joke.TYPE_MEITU:
			sb.append(mJoke.getTitle());
			imgPath = mJoke.getImgUrl();
			break;
		case Joke.TYPE_GIF:
			sb.append(mJoke.getTitle());
			imgPath = mJoke.getGifUrl();
			break;
		}
		sb.append(targetUrl + mJoke.getId());
		weiBoAPI.reAddWeibo(context, sb.toString(), imgPath, null ,null, null, null, mCallBack, null, BaseVO.TYPE_JSON);
	}
	
	/**
	 * 分享到qq微博回调
	 */
	private HttpCallback mCallBack = new HttpCallback() {
   		@Override
   		public void onResult(Object object) {
   			ModelResult result = (ModelResult) object;
   			if(result.isExpires()){  //授权超期了，重新进行授权
   				auth(Constants.APP_KEY, Constants.APP_KEY_SEC);
   			}else{
   				if(result.isSuccess()){
   	   				ImgToastUtils.showMessage(context, "分享成功", R.drawable.center_ok_tip);
   	   			}else{
   	   				ToastUtils.showMessageInCenter(context, "分享失败");
   	   			}
   			}
   		}
	};
	
	
	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
	}
	
	/**
	 * 设置分享内容
	 * @param mJoke
	 */
	public void setmJoke(Joke mJoke) {
		this.mJoke = mJoke;
	}

	/**
	 * 新浪微博分享回调
	 */
	@Override
	public void onResponse(BaseResponse baseResp) {
		switch (baseResp.errCode) {
        case WBConstants.ErrorCode.ERR_OK:
            Toast.makeText(context, R.string.weibosdk_demo_toast_share_success, Toast.LENGTH_LONG).show();
            break;
        case WBConstants.ErrorCode.ERR_CANCEL:
            Toast.makeText(context, R.string.weibosdk_demo_toast_share_canceled, Toast.LENGTH_LONG).show();
            break;
        case WBConstants.ErrorCode.ERR_FAIL:
            Toast.makeText(context, 
            		context.getString(R.string.weibosdk_demo_toast_share_failed) + "Error Message: " + baseResp.errMsg, 
                    Toast.LENGTH_LONG).show();
            break;
        }
	}
	
	/**
     * 微博认证授权回调类。
     * 1. SSO 授权时，需要在 {@link #onActivityResult} 中调用 {@link SsoHandler#authorizeCallBack} 后，
     *    该回调才会被执行。
     * 2. 非 SSO 授权时，当授权结束后，该回调就会被执行。
     * 当授权成功后，请保存该 access_token、expires_in、uid 等信息到 SharedPreferences 中。
     */
    class AuthListener implements WeiboAuthListener {
        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            if (mAccessToken.isSessionValid()) {
                // 保存 Token 到 SharedPreferences
                AccessTokenKeeper.writeAccessToken(context, mAccessToken);
                UsersAPI usersAPI = new UsersAPI(context, com.sina.weibo.Constants.APP_KEY, mAccessToken);
                share2weibo();
                usersAPI.show(Long.parseLong(mAccessToken.getUid()), new RequestListener() {
					@Override
					public void onWeiboException(WeiboException arg0) {
						Log.e(TAG, "sina get userInfo fail", arg0);
						ToastUtils.showMessage(context, R.string.weibosdk_demo_toast_auth_failed);
					}
					@Override
					public void onComplete(String arg0) {
						Log.e(TAG, arg0);
						/** 通过JSON获取到新浪微博用户信息,且解析相关内容信息 */
					    try {
							JSONObject jsonObj = new JSONObject(arg0);
							//uid
							String uid = jsonObj.getString("id");
							// 用户昵称
							String wb_screen_name = jsonObj.getString("screen_name");
							// 用户头像地址，50×50像素
							String wb_profile_image_url = jsonObj.getString("profile_image_url");
							IUserService mUserService = new UserServiceImpl(context);
							mUserService.addSinaUser(null, uid, wb_profile_image_url, wb_screen_name);
						} catch (JSONException e) {
							Log.e(TAG, "sina get userInfo fail", e);
						}
					}
				});
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
                String message = context.getString(R.string.weibosdk_demo_toast_auth_failed);
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancel() {
            Toast.makeText(context, 
                   R.string.weibosdk_demo_toast_auth_canceled, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(context, 
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 统计趣事、趣图、美图分享次数
     * @param joke
     */
    private void saveShareTimes() {
    	if(mJoke == null) {
    		return;
    	}
    	switch (mJoke.getType()) {
		case Joke.TYPE_QUSHI:
			MobclickAgent.onEvent(context, "qushi_share");
			break;
		case Joke.TYPE_QUTU:
			MobclickAgent.onEvent(context, "qutu_share");
			break;
		case Joke.TYPE_MEITU:
			MobclickAgent.onEvent(context, "meitu_share");
			break;
		}
    }
	
} public class BitmapUtil {
	
	public static BitmapUtils mBitmapUtils;
	
	static {
		mBitmapUtils = new BitmapUtils(App.getInstance());
		mBitmapUtils.configDefaultLoadingImage(R.drawable.default_portrait);
		mBitmapUtils.configDefaultLoadFailedImage(R.drawable.default_portrait);
		mBitmapUtils.configDefaultBitmapConfig(Bitmap.Config.RGB_565);
		mBitmapUtils.configMemoryCacheEnabled(true);
		mBitmapUtils.configDiskCacheEnabled(true);
	}
	
	/**
	 * 加载图片
	 * @param container
	 * @param uri
	 * @param callBack
	 */
	public static void display(ImageView container, String uri, BitmapLoadCallBack<ImageView> callBack) {
		mBitmapUtils.display(container, uri, callBack);
	}
	
	/**
	 * 加载图片
	 * @param container
	 * @param uri
	 */
	public static void display(ImageView container, String uri) {
		mBitmapUtils.display(container, uri);
	}
	
	/**
	 * 从缓存中获取原图
	 * @param uri
	 * @return
	 */
	public static Bitmap getBitmapFromCache(String uri) {
		BitmapDisplayConfig config = new BitmapDisplayConfig();
		config.setBitmapConfig(Bitmap.Config.ARGB_8888);
		config.setShowOriginal(true);
		Bitmap bitmap = mBitmapUtils.getBitmapFromMemCache(uri, config);
		if(bitmap != null) {
			return bitmap;
		}
		try {
			return BitmapFactory.decodeStream(new FileInputStream(mBitmapUtils.getBitmapFileFromDiskCache(uri)));
		} catch (FileNotFoundException e) {
			Log.e("getBitmapFileFromCache", "get bitmap error", e);
		}
		return null;
	}
	
	/**
	 * 获取缓存中图片的缩略图
	 * @param uri
	 * @return
	 */
	public static Bitmap getThumbBitmapFromCache(String uri, int width, int height) {
		BitmapDisplayConfig config = new BitmapDisplayConfig();
		config.setBitmapConfig(Bitmap.Config.ARGB_8888);
		config.setShowOriginal(false);
		BitmapSize bitmapSize = new BitmapSize(width, height);
		config.setBitmapMaxSize(bitmapSize);
		Bitmap bitmap = mBitmapUtils.getBitmapFromMemCache(uri, config);
		if(bitmap != null) {
			return bitmap;
		}
		try {
//			Bitmap bitmap2 = BitmapFactory.decodeStream(new FileInputStream());
			File file = mBitmapUtils.getBitmapFileFromDiskCache(uri);
	        BitmapFactory.Options options = new BitmapFactory.Options();  
	        options.inJustDecodeBounds = true;  
	        // 获取这个图片的宽和高，注意此处的bitmap为null  
	        bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);  
	        options.inJustDecodeBounds = false; // 设为 false  
	        // 计算缩放比  
	        int h = options.outHeight;  
	        int w = options.outWidth;  
	        int beWidth = w / width;  
	        int beHeight = h / height;  
	        int be = 1;  
	        if (beWidth < beHeight) {  
	            be = beWidth;  
	        } else {  
	            be = beHeight;  
	        }  
	        if (be <= 0) {  
	            be = 1;  
	        }  
	        options.inSampleSize = be;  
	        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false  
	        bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);  
	        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象  
	        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,  
	                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);  
	        return bitmap;
		} catch (Exception e) {
			Log.e("getBitmapFileFromCache", "get bitmap error", e);
		}
		return null;
	}
	
	/**
	 * 清除吃盘缓存
	 */
	public static void cleanDiskCache() {
		mBitmapUtils.clearDiskCache();
	}
	
	/**
	 * 清除内存缓存
	 */
	public static void cleanMemCache() {
		mBitmapUtils.clearMemoryCache();
	}
    
} public class FastjsonUtil {
	
	private static SerializeConfig mapping = new SerializeConfig(); static { 
        mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss")); 
	} 

	/** 
	 * @Title: main 
	 * @Description: TODO 
	 * @param @param args  
	 * @return void 
	 */

	public static void main(String[] args) {
	}
	
	/**
      * 将java类型的对象转换为JSON格式的字符串
      * @param object java类型的对象
      * @return JSON格式的字符串
    */
    public static <T> String serialize(T object) {
        return JSON.toJSONString(object);
    }
    
    /**
     * 将JSON格式的字符串转换成任意Java类型的对象或者java数组类型的对象，不包括java集合类型
     * @param json JSON格式的字符串
     * @param clz java类型或者java数组类型，不包括java集合类型
     * @return java类型的对象或者java数组类型的对象，不包括java集合类型的对象
     */
    public static <T> T deserialize(String json, Class<T> clz) {
       return JSON.parseObject(json, clz);
    }
	
    /**
    * 将JSON格式的字符串转换成任意Java类型的对象
    * @param json JSON格式的字符串
    * @param type 任意Java类型
    * @return 任意Java类型的对象
    */
    public static <T> T deserializeAny(String json, TypeReference<T> type) {
       return JSON.parseObject(json, type);
    }
   
    /**
    * 将JSON格式的字符串转换成任意Java类型的对象
    * @param json JSON格式的字符串
    * @param type 任意Java类型
    * @return 任意Java类型的对象
    */
    public static <T> List<T> deserializeList(String json, Class<T> clz) {
       return JSON.parseArray(json, clz);
    }
	
    /**
    * 将JSON格式的字符串转换为List<T>类型的对象
    * @param json JSON格式的字符串
    * @param clz 指定泛型集合里面的T类型
    * @return List<T>类型的对象
    */
    public static <T> List<T> json2List(String json, Class<T> clz){ 
        //JSON array -> List 
	   return JSON.parseArray(json, clz); 
    } 
	
    /**
     * 将JSON格式的字符串转换为Map类型的对象
     * @param json JSON格式的字符串
     * @return Map类型的对象
     */
	public static Map json2Map(String json){ 
		//JSON -> Map 
		return (Map)JSON.parse(json); 
	} 
	
	/**
     * 将数组格式的转换为String类型的对象
     * @param 数组格式的字符串
     * @return String类型的对象
     */
	public static String array2json(Object[] obj){ 
		return JSON.toJSONString(obj,true); 
	} 
	
	/**
     * 将Map格式的转换为String类型的对象
     * @param Map格式的字符串
     * @return String类型的对象
     */
	public static String map2json(Map map){ 
	    return JSON.toJSONString(map); 
	} 
	
	/**
     * 将List格式的转换为String类型的对象
     * @param List格式的字符串
     * @return String类型的对象
     */
	public static String list2json(List list){ 
	    return JSON.toJSONString(list); 
	} 

} public class ProgressDialogUtils {
	
	private static Dialog dialog;
	
	public static void showProgressDialog(Context context, String text) {
		LayoutInflater inflater = LayoutInflater.from(context);
		View v = inflater.inflate(R.layout.ct_progressdialog, null);
		TextView content = (TextView) v.findViewById(R.id.dialog_content);
		content.setText(text);
		ImageView spaceshipImage = (ImageView) v.findViewById(R.id.dialog_img);
		// 加载动画
		Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(context,
				R.anim.progress_anim);
		// 使用ImageView显示动画
		spaceshipImage.startAnimation(hyperspaceJumpAnimation);
		dialog = new Dialog(context, R.style.CustomDialog);
		dialog.setCanceledOnTouchOutside(false); //触摸外面不消失
		dialog.setContentView(v, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));
		dialog.getWindow().setWindowAnimations(R.style.dialogAnim); 
		dialog.show();
		/*//设置progressdilog的高度和宽度
		int sreenWidth = DensityUtil.getWidthInPx(context);
		dialog.getWindow().setLayout(sreenWidth - 64, DensityUtil.dip2px(context, 48));*/
	}
	
	public static void dismiss() {
		if(dialog != null && dialog.isShowing()) {
			dialog.dismiss();
			dialog = null;
		}
	}
	
} public class TaskExecutor {
    private static ScheduledThreadPoolExecutor gScheduledThreadPoolExecutor = null;
    private static Handler gMainHandler = null;

    //不包含网络传输处理过程的线程池执行对象
    private static ExecutorService gThreadPoolExecutor = null;

    //包含网络传输处理过程的线程池执行对象
    private static ExecutorService gNetProcessThreadPoolExecutor = null;

    //执行不包含网络传输处理过程的线程
    public static void executeTask(Runnable task) {
        ensureThreadPoolExecutor();
        gThreadPoolExecutor.execute(task);
    }

    //执行包含网络传输处理过程的线程，可能存在等待阻塞的状况
    public static void executeNetTask(Runnable task) {
        ensureNetProcessThreadPoolExecutor();
        gNetProcessThreadPoolExecutor.execute(task);
    }

    public static <T> Future<T> submitTask(Callable <T> task) {
        ensureThreadPoolExecutor();
        return gThreadPoolExecutor.submit(task);
    }

    public static void scheduleTask(long delay, Runnable task) {
        ensureScheduledThreadPoolExecutor();
        gScheduledThreadPoolExecutor.schedule(task, delay, TimeUnit.MILLISECONDS);
    }

    public static void scheduleTaskAtFixedRateIgnoringTaskRunningTime(long initialDelay, long period, Runnable task) {
        ensureScheduledThreadPoolExecutor();
        gScheduledThreadPoolExecutor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS);
    }

    public static void scheduleTaskAtFixedRateIncludingTaskRunningTime(long initialDelay, long period, Runnable task) {
        ensureScheduledThreadPoolExecutor();
        gScheduledThreadPoolExecutor.scheduleWithFixedDelay(task, initialDelay, period, TimeUnit.MILLISECONDS);
    }

    public static void scheduleTaskOnUiThread(long delay, Runnable task) {
        ensureMainHandler();
        gMainHandler.postDelayed(task, delay);
    }

    public static void runTaskOnUiThread(Runnable task) {
        ensureMainHandler();
        gMainHandler.post(task);
    }

    private static void ensureMainHandler() {
        if (gMainHandler == null) {
            gMainHandler = new Handler(Looper.getMainLooper());
        }
    }

    private static void ensureThreadPoolExecutor() {
        if (gThreadPoolExecutor == null) {
            gThreadPoolExecutor = new ThreadPoolExecutor(5, 10,
                    60L, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>(),
                    Executors.defaultThreadFactory());

        }
    }

    private static void ensureNetProcessThreadPoolExecutor() {
        if (gNetProcessThreadPoolExecutor == null) {
            gNetProcessThreadPoolExecutor = new ThreadPoolExecutor(10, 15,
                    60L, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>(),
                    Executors.defaultThreadFactory());

        }
    }

    private static void ensureScheduledThreadPoolExecutor() {
        if (gScheduledThreadPoolExecutor == null) {
            gScheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);
        }
    }

    public static void shutdown() {
        if (gThreadPoolExecutor != null) {
            gThreadPoolExecutor.shutdown();
            gThreadPoolExecutor = null;
        }

        if (gScheduledThreadPoolExecutor != null) {
            gScheduledThreadPoolExecutor.shutdown();
            gScheduledThreadPoolExecutor = null;
        }
    }
} public class ToastUtils {  
    private static Handler mHandler = new Handler(Looper.getMainLooper());  
    private static Toast mToast;
    protected static LayoutInflater inflater;
    private static int marginBottem = 48;

    /** 
     * Toast发送消息，默认Toast.LENGTH_SHORT 
     * @param act 
     * @param msg 
     */ 
    public static void showMessage(final Context act, final String msg) {  
        showMessage(act, msg, Toast.LENGTH_SHORT);  
    }
    
    /** 
     * Toast发送消息，默认Toast.LENGTH_SHORT 
     * @param act 
     * @param msg 
     */ 
    public static void showMessageInCenter(final Context act, final String msg) {  
    	/*new Thread(new Runnable() {  
            public void run() {  */
            	mHandler.post(new Runnable() {  
                    @Override 
                    public void run() {  
                    	if (mToast != null) {
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    		mToast.setText(msg);
                    	} else {
                    		mToast = Toast.makeText(act, msg, Toast.LENGTH_SHORT);
                    		if(inflater == null) {
                    			inflater = (LayoutInflater) act
                        	            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    		}
                    		mToast.setView(inflater.inflate(R.layout.toast, null));
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    		mToast.setText(msg);
                    	}
                    	mToast.show();
                    }  
                });  
           /* }  
        }).start();  */
    }  
       
    /** 
     * Toast发送消息，默认Toast.LENGTH_LONG 
     * @param act 
     * @param msg 
     */ 
    public static void showMessageLong(final Context act, final String msg) {  
        showMessage(act, msg, Toast.LENGTH_LONG);  
    }  
   
    /** 
     * Toast发送消息，默认Toast.LENGTH_SHORT 
     * @param act 
     * @param msg 
     */ 
    public static void showMessage(final Context act, final int msg) {  
        showMessage(act, msg, Toast.LENGTH_SHORT);  
    }  
       
    /** 
     * Toast发送消息，默认Toast.LENGTH_LONG 
     * @param act 
     * @param msg 
     */ 
    public static void showMessageLong(final Context act, final int msg) {  
        showMessage(act, msg, Toast.LENGTH_LONG);  
    }  
   
    /** 
     * Toast发送消息 
     * @param act 
     * @param msg 
     * @param len 
     */ 
    public static void showMessage(final Context act, final int msg,  
            final int len) {  
        /*new Thread(new Runnable() {  
            public void run() {  */
            	mHandler.post(new Runnable() {  
                    @Override 
                    public void run() {  
                    	if (mToast != null) {
                    		mToast.setText(msg);
//                    		mToast.setGravity(Gravity.BOTTOM, 0, marginBottem);
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    	} else {
                    		mToast = Toast.makeText(act, msg, len);
                    		if(inflater == null) {
                    			inflater = (LayoutInflater) act
                        	            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    		}
                    		mToast.setView(inflater.inflate(R.layout.toast, null));
//                    		mToast.setGravity(Gravity.BOTTOM, 0, marginBottem);
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    		mToast.setText(msg);
                    	}
                    	mToast.show();
                    }  
                });  
           /* }  
        }).start();*/  
    }  
       
    /** 
     * Toast发送消息 
     * @param act 
     * @param msg 
     * @param len 
     */ 
    public static void showMessage(final Context act, final String msg,  
            final int len) {  
        /*new Thread(new Runnable() {  
            public void run() {*/  
            	mHandler.post(new Runnable() {  
                    @Override 
                    public void run() {  
                    	if (mToast != null) {
                    		mToast.setText(msg);
//                    		mToast.setGravity(Gravity.BOTTOM, 0, marginBottem);
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    	} else {
                    		mToast = Toast.makeText(act, msg, len);
                    		if(inflater == null) {
                    			inflater = (LayoutInflater) act
                        	            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    		}
                    		mToast.setView(inflater.inflate(R.layout.toast, null));
//                    		mToast.setGravity(Gravity.BOTTOM, 0, marginBottem);
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    		mToast.setText(msg);
                    	}
                    	mToast.show();
                    }  
                });  
            /*}  
        }).start();  */
    }  
   
}   public class ToolsUtils {

	public ToolsUtils() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 检查是否存在SDCard
	 * 
	 * @return
	 */
	public static boolean hasSdcard() {
		String state = Environment.getExternalStorageState();

		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 查看SD卡的剩余空间
	 * @return
	 */
	public long getSDFreeSize(){  
	     //取得SD卡文件路径  
	     File path = Environment.getExternalStorageDirectory();   
	     StatFs sf = new StatFs(path.getPath());   
	     //获取单个数据块的大小(Byte)  
	     long blockSize = sf.getBlockSize();   
	     //空闲的数据块的数量  
	     long freeBlocks = sf.getAvailableBlocks();  
	     //返回SD卡空闲大小  
	     return (freeBlocks * blockSize)/1024 /1024; //单位MB  
	   } 
	
	/**
	 * 查看SD卡总容量
	 * @return
	 */
	public long getSDAllSize(){
	      //取得SD卡文件路径
	      File path = Environment.getExternalStorageDirectory(); 
	      StatFs sf = new StatFs(path.getPath()); 
	      //获取单个数据块的大小(Byte)
	      long blockSize = sf.getBlockSize(); 
	      //获取所有数据块数
	      long allBlocks = sf.getBlockCount();
	      //返回SD卡大小
	      return (allBlocks * blockSize)/1024/1024; //单位MB
	    }   
	
	/**
	 * 获取屏幕的宽
	 * @param context
	 * @return
	 */
	public static int getScreenWidth(Context context) {
		WindowManager manager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
	    DisplayMetrics dm=new DisplayMetrics();
	    manager.getDefaultDisplay().getMetrics(dm);
	    return dm.widthPixels;
	}

	/**
	 * 获取版本号
	 * 
	 * @param context
	 * @return
	 */
	public static int getVersionCode(Context context) {
		int versionCode = 0;
		try {
			// 获取软件版本号
			versionCode = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 1).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	/**
	 * 获取版本名称
	 * 
	 * @param context
	 * @return
	 */
	public static String getVersionName(Context context) {
		String versionName = "";
		try {
			// 获取软件版本名称
			versionName = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 1).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionName;
	}
	
	/**
	 * 隐藏键盘
	 * 
	 * @param v
	 * @return
	 */
	public static void hideKeyboard(View v) {
		InputMethodManager imm = (InputMethodManager) v.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm.isActive()) {
			imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);

		}
	}
	
	 /**
     * 打卡软键盘
     * @param mEditText输入框
     * @param mContext上下文
     */
    public static void openKeybord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
    
    /**
     * 判断软键盘是否显示
     * @param context
     * @return
     */
    public static boolean isKeybordShow(Context context) {
    	InputMethodManager imms = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        return imms.isActive();
    }
	
	/**
	 * 判断某个service是否正在运行
	 * @param context
	 * @param serviceName
	 * @return
	 */
	public static boolean isServiceWorked(Context context, String serviceName) {
		ActivityManager myManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
				.getRunningServices(30);
		for (int i = 0; i < runningService.size(); i++) {
			if (runningService.get(i).service.getClassName().toString()
					.equals(serviceName)) {
				return true;
			}
		}
		return false;
	} 
	
	/**
	 * 设置dialog背景和动画
	 * @param dialig
	 */
	public static void setDialogBgAndAnim(Dialog dialig) {
		// 设置背景变暗
		WindowManager.LayoutParams lp = dialig.getWindow()
				.getAttributes();
		lp.dimAmount = 0.7f; // 设置30%暗度
		dialig.getWindow().setAttributes(lp);
		// 设置对话框弹出动画
		dialig.getWindow().setWindowAnimations(R.style.dialogAnim);
	}
	
	/**
	 * 将字节转换为图像
	 * @param bytes
	 * @param opts
	 * @return
	 */
	public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}
	
	/**
	 * 将流转换为字节
	 * 
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}
	
	public static String Html2Text(String inputString) {    
        String htmlStr = inputString; // 含html标签的字符串    
        String textStr = "";    
        java.util.regex.Pattern p_script;    
        java.util.regex.Matcher m_script;    
        java.util.regex.Pattern p_style;    
        java.util.regex.Matcher m_style;    
        java.util.regex.Pattern p_html;    
        java.util.regex.Matcher m_html;    
        java.util.regex.Pattern p_html1;    
        java.util.regex.Matcher m_html1;    
       try {    
            String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[//s//S]*?<///script>    
            String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[//s//S]*?<///style>    
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式    
            String regEx_html1 = "<[^>]+";    
            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);    
            m_script = p_script.matcher(htmlStr);    
            htmlStr = m_script.replaceAll(""); // 过滤script标签    
  
            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);    
            m_style = p_style.matcher(htmlStr);    
            htmlStr = m_style.replaceAll(""); // 过滤style标签    
  
            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);    
            m_html = p_html.matcher(htmlStr);    
            htmlStr = m_html.replaceAll(""); // 过滤html标签    
  
            p_html1 = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);    
            m_html1 = p_html1.matcher(htmlStr);    
            htmlStr = m_html1.replaceAll(""); // 过滤html标签    
  
            textStr = htmlStr;    
  
        } catch (Exception e) {    
            Log.e("Html2Text" , e.getMessage());    
        }    
  
       return textStr;// 返回文本字符串    
    }   
	
	/**
	 * 手动设置listview的高度，包裹所有元素
	 * @param listView
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) {  
        ListAdapter listAdapter = listView.getAdapter();   
        if (listAdapter == null) {  
            // pre-condition  
            return;  
        }  
  
        int totalHeight = 0;  
        for (int i = 0; i < listAdapter.getCount(); i++) {  
            View listItem = listAdapter.getView(i, null, listView);  
            listItem.measure(0, 0);  
            totalHeight += listItem.getMeasuredHeight();  
        }  
  
        ViewGroup.LayoutParams params = listView.getLayoutParams();  
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));  
        listView.setLayoutParams(params);  
    }  
} @SuppressWarnings("unchecked")
public class Util {

	public static java.util.Date addYear(java.util.Date date, int year) {
		GregorianCalendar gdate = new GregorianCalendar();
		gdate.setTime(date);
		gdate.add(GregorianCalendar.YEAR, year);
		return gdate.getTime();
	}

	public static java.util.Date addMonth(java.util.Date date, int month) {
		GregorianCalendar gdate = new GregorianCalendar();
		gdate.setTime(date);
		gdate.add(GregorianCalendar.MONTH, month);
		return gdate.getTime();
	}

	public static java.util.Date addDay(java.util.Date date, int day) {
		GregorianCalendar gdate = new GregorianCalendar();
		gdate.setTimeInMillis(date.getTime());
		gdate.add(GregorianCalendar.DAY_OF_MONTH, day);
		return gdate.getTime();
	}

	public static java.util.Date addSecond(java.util.Date date, int second) {
		GregorianCalendar gdate = new GregorianCalendar();
		gdate.setTimeInMillis(date.getTime());
		gdate.add(GregorianCalendar.SECOND, second);
		return gdate.getTime();
	}
	
	public static java.util.Date addMinute(java.util.Date date, int minute) {
		GregorianCalendar gdate = new GregorianCalendar();
		gdate.setTimeInMillis(date.getTime());
		gdate.add(GregorianCalendar.MINUTE, minute);
		return gdate.getTime();
	}

	/**
	 * @Title: formatDate
	 * @Description: 获取指定格式日期字符串
	 * @param @param date
	 * @param @param patter
	 * @param @return
	 * @return String
	 */
	public static String formatDate(Date date, String patter) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(patter);
			return sdf.format(date);
		} catch (RuntimeException e) {
			return "";
		}
	}

	/**
	 * @Title: formatDate
	 * @Description: 按默认格式格式化时间
	 * @param @param date
	 * @param @return
	 * @return String
	 */
	public static String formatDate(Date date) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.format(date);
		} catch (RuntimeException e) {
			return "";
		}
	}

	/**
	 * 按照指定的格式来解析字符串成为时间
	 * 
	 * @param date
	 * @param patter
	 * @return
	 */
	public static Date parseDate(String strDate, String patter) {
		Date date = null;
		SimpleDateFormat sdf = new SimpleDateFormat(patter);
		try {
			date = sdf.parse(strDate);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
		return date;
	}

	/**
	 * @Title: parseDate
	 * @Description: 按默认格式解析时间
	 * @param @param strDate
	 * @param @return
	 * @return Date
	 */
	public static Date parseDate(String strDate) {
		Date date = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			date = sdf.parse(strDate);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
		return date;
	}

	/**
	 * 获得现在的时间(格式:yyyy-MM-dd)
	 * 
	 * @return
	 */
	public static Date getNow() {
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return dateFormat.parse(dateFormat.format(now));
		} catch (ParseException e) {
			return null;
		}
	}
	
	public static Date getTimeDate() {
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return dateFormat.parse(dateFormat.format(now));
		} catch (ParseException e) {
			return null;
		}
	}
	
	public static int weeksBetween(Date date1, Date date2){
		int days = daysBetween(date1, date2);
		return (days%7) == 0 ? (days/7) : (days/7)+1;
	}
	

	/**
	 * 计算两个时间相差的天数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int daysBetween(Date date1, Date date2) {
		if (date1 == null || date2 == null) {
			return 0;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date1);
		long time1 = cal.getTimeInMillis();
		cal.setTime(date2);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);
		return Integer.parseInt(String.valueOf(between_days));
	}

	/**
	 * @Title: getTimestamp
	 * @Description: 获取1-2的时间差，单位为ms
	 * @param @param time1
	 * @param @param time2
	 * @param @return
	 * @return int
	 */
	public static int getTimestamp(Date time1, Date time2) {
		if (time1 == null || time2 == null) {
			return 0;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(time1);
		long m1 = cal.getTimeInMillis();
		cal.setTime(time2);
		long m2 = cal.getTimeInMillis();
		long between_sec = (m2 - m1);
		return Integer.parseInt(String.valueOf(between_sec));
	}
	
	public static long getTimestampl(Date time1, Date time2) {
		if (time1 == null || time2 == null) {
			return 0;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(time1);
		long m1 = cal.getTimeInMillis();
		cal.setTime(time2);
		long m2 = cal.getTimeInMillis();
		long between_sec = (m2 - m1);
		return between_sec;
	}

	/**
	 * @Title: getWeekTimesBE
	 * @Description: 获取一周的起止时间
	 * @param @param offset 星期偏移量，0为本周，-1为上周，1为下周，如此类推
	 * @param @return date[0]：开始时间，格式2012-03-04
	 *        00:00:00；date[1]：结束时间，格式2012-03-10 23:59:59；异常为null
	 * @return Date[]
	 */
	public static Date[] getWeekTimesBE(int offset) {
		try {
			Date[] dates = new Date[2];
			SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat f2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// 得到当前日期
			Calendar cal = Calendar.getInstance();

			// 得到本周第一天日期
			int day_of_week = cal.get(Calendar.DAY_OF_WEEK);
			cal.add(Calendar.DATE, -day_of_week + 1 + (7 * offset));
			Date begin = cal.getTime();
			String weekFirstStr = f1.format(begin);
			begin = f2.parse(weekFirstStr + " 00:00:00");

			// 得到本周最后一天
			cal.add(Calendar.DATE, 6);
			Date end = cal.getTime();
			String weekLastStr = f1.format(end);
			end = f2.parse(weekLastStr + " 23:59:59");
			dates[0] = begin;
			dates[1] = end;
			return dates;
		} catch (Exception e) {
			return null;
		}
	}
	
	public static Date[] getDayBE(Date date){
		Date[] dates = new Date[2];
		String strDate = Util.formatDate(date, "yyyy-MM-dd");//今天
		Date start = Util.parseDate(strDate+" 00:00:00", "yyyy-MM-dd HH:mm:ss");
		Date end = Util.parseDate(strDate+" 23:59:59", "yyyy-MM-dd HH:mm:ss");
		dates[0] = start;
		dates[1] = end;
		return dates;
	}
	
	/**
	 * @Title: getMonthTimesBE
	 * @Description: 获取一月的起止时间
	 * @param @param offset 月份偏移量，0为本月，-1为上月，1为下月，如此类推
	 * @param @return date[0]：开始时间，格式2012-03-01
	 *        00:00:00；date[1]：结束时间，格式2012-03-31 23:59:59；异常为null
	 * @return Date[]
	 */
	public static Date[] getMonthTimesBE(int offset) {
		try {
			Date[] dates = new Date[2];
			// 得到当前日期
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.MONTH, offset);

			int MaxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
			// 按你的要求设置时间
			cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), MaxDay,
					23, 59, 59);
			Date end = cal.getTime();
			cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 1, 00, 00,
					00);
			Date begin = cal.getTime();
			dates[0] = begin;
			dates[1] = end;
			return dates;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * @Title: getDayTimesBE
	 * @Description: 获取一天的开始结束时间
	 * @param @param date
	 * @param @return
	 * @return Date[]
	 */
	public static Date[] getDayTimesBE(Date date) {
		Date[] dates = new Date[2];
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		// 按你的要求设置时间
		cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal
				.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
		Date end = cal.getTime();
		cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal
				.get(Calendar.DAY_OF_MONTH), 00, 00, 00);
		Date begin = cal.getTime();
		dates[0] = begin;
		dates[1] = end;
		return dates;
	}

	/**
	 * @Title: isNotEmpty
	 * @Description: 判断列表是否为空
	 * @param @param list
	 * @param @return
	 * @return boolean
	 */
	public static boolean isNotEmpty(List list) {
		boolean returnBoolean = false;
		if (list != null && list.size() > 0) {
			returnBoolean = true;
		}

		return returnBoolean;
	}
	
	/**
	 * 判断列表是否为空
	 * @param list
	 * @return
	 */
	public static boolean isEmpty(List list) {
		boolean returnBoolean = true;
		if (list != null && list.size() > 0) {
			returnBoolean = false;
		}
		return returnBoolean;
	}

	/**
	 * @Title: isNotEmpty
	 * @Description: 判断数组是否为空
	 * @param @param ObjectArray
	 * @param @return
	 * @return boolean
	 */
	public static boolean isNotEmpty(Object[] ObjectArray) {
		boolean returnBoolean = false;
		if (ObjectArray != null && ObjectArray.length > 0) {
			returnBoolean = true;
		}

		return returnBoolean;
	}

	/**
	 * @Title: isEmpty
	 * @Description: 判断字符串是否为空
	 * @param @param strings
	 * @param @return
	 * @return boolean
	 */
	public static boolean isEmpty(String string) {
		if(string == null || "".equals(string)) {
			return true;
		}
		return false;
	}
	
	/**
	 * @Title: isNotEmpty
	 * @Description: 判断字符串是否不为空
	 * @param @param strings
	 * @param @return
	 * @return boolean
	 */
	public static boolean isNotEmpty(String string) {
		return !isEmpty(string);
	}

	/*
	 * @purpose:calculate the page count using the count and pagesize @params:
	 * int ,int @return: int
	 */
	public static int count2PageCount(int count, int pageSize) {
		int pageCount = count / pageSize;
		if (count % pageSize != 0) {
			pageCount++;
		}

		return pageCount;
	}

	/*
	 * @purpose:calculate the page count using the count and pagesize @params:
	 * int ,int @return: int
	 */
	public static int count2PageCount(long countLong, int pageSize) {
		int count = Long.valueOf(countLong).intValue();
		int pageCount = count / pageSize;
		if (count % pageSize != 0) {
			pageCount++;
		}

		return pageCount;
	}

	/*
	 * @purpose:put a List to String use the specified pattern ";" @params: List
	 * 
	 * @return: String
	 */
	public static String listToString(List list) {
		StringBuffer stringBuffer = new StringBuffer();

		if (Util.isNotEmpty(list)) {
			for (Object object : list) {
				if (object != null) {
					stringBuffer.append(object.toString());
					stringBuffer.append(";");
				}
			}
		}

		if (stringBuffer.length() == 0) {
			return null;
		} else {
			return stringBuffer.toString();
		}
	}

	/*
	 * @purpose:put a List to String use the specified pattern @params: List
	 * 
	 * @return: String
	 */
	public static String listToString(List list, String pattern) {
		StringBuffer stringBuffer = new StringBuffer();

		if (Util.isNotEmpty(list)) {
			for (Object object : list) {
				if (object != null) {
					stringBuffer.append(object.toString());
					stringBuffer.append(pattern);
				}
			}
		}

		if (stringBuffer.length() == 0) {
			return null;
		} else {
			return stringBuffer.toString();
		}
	}

	/*
	 * @purpose:put a array to a String using the specified pattern ";" @params:
	 * Object[] @return: String
	 */
	public static String array2String(Object[] objects) {
		String string = null;

		StringBuffer stringBuffer = new StringBuffer();
		if (Util.isNotEmpty(objects)) {
			for (Object object : objects) {
				if (object != null) {
					stringBuffer.append(object.toString());
					stringBuffer.append(";");
				}
			}
		}

		if (stringBuffer.length() > 0) {
			string = stringBuffer.toString();
		}

		return string;
	}

	/*
	 * @purpose:put a Object Array to List @params: Object[] @return: List
	 */
	public static List arrayToList(Object[] objects) {
		List list = null;

		if (Util.isNotEmpty(objects)) {
			list = new ArrayList();
			for (Object object : objects) {
				if (object != null) {
					list.add(object);
				}
			}
		}

		return list;
	}

	/*
	 * @purpose:put a String array to List<Integer> @params: String[] @return:
	 * List<Integer>
	 */
	public static List<Integer> stringArrayToListInteger(String[] strings) {
		List<Integer> list = null;

		try {
			if (Util.isNotEmpty(strings)) {
				list = new ArrayList<Integer>();
				for (String string : strings) {
					if (string != null) {
						list.add(Integer.parseInt(string));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			list = null;
		}

		return list;
	}

	/*
	 * @purpose:put a String to List<String> based on the specified pattern ";"
	 * 
	 * @params: String @return: List<String>
	 */
	public static List<String> stringToList(String string) {
		List<String> list = null;

		if (Util.isNotEmpty(string)) {
			String[] stringArray = string.split(";");
			list = arrayToList(stringArray);
		}

		return list;
	}

	// 解析输入流成byte数组
	public static byte[] recvMsg(InputStream inputstream, int length)
			throws Exception {
		try {
			byte content[] = new byte[length];
			int readCount = 0; // 已经成功读取的字节的个数
			while (readCount < length) {
				int size = (length - readCount) > 1024 ? 1024
						: (length - readCount);
				readCount += inputstream.read(content, readCount, size);
			}
			return content;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @Title: isNumeric
	 * @Description: 判断字符串是否为数字
	 * @Param @param str
	 * @Param @return
	 * @return boolean
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}
	
	/**
	 * 密码验证（包含数字和字母）
	   * @author zhr
	   * @create_date 2014-8-29 上午9:16:02
	   * @param pwd
	   * @param minLen:最新长度
	   * @param maxLen:最大长度
	   * @return
	 */
	public static boolean isOK2Pwd(String pwd,int minLen,int maxLen) {
		String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{"+minLen+","+maxLen+"}$";
		Pattern pattern = Pattern.compile(regex);
		return pattern.matcher(pwd).matches();
	}	
	
	/**
	 * 匹配纯字符
	   * @author zhr
	   * @create_date 2014-9-26 下午5:37:57
	   * @param pwd
	   * @param minLen
	   * @param maxLen
	   * @return
	 */
	public static boolean isOK2Pwd2(String pwd,int minLen,int maxLen) {
		String regex = "^[A-Za-z]{"+minLen+","+maxLen+"}$";
		Pattern pattern = Pattern.compile(regex);
		return pattern.matcher(pwd).matches();
	}	
	
	/**
	 * 匹配纯数字
	   * @author zhr
	   * @create_date 2014-9-26 下午5:36:59
	   * @param pwd
	   * @param minLen
	   * @param maxLen
	   * @return
	 */
	public static boolean isOK2Pwd3(String pwd,int minLen,int maxLen) {
		String regex = "^[0-9]{"+minLen+","+maxLen+"}$";
		Pattern pattern = Pattern.compile(regex);
		return pattern.matcher(pwd).matches();
	}

	/**
	 * 判断手机号是否合法
	 * 
	 * @param phone
	 * @return
	 */
	public static boolean isPhone(String phone) {
		if (null == phone || "".equals(phone)) {
			return false;
		}
		String regExp = "^1[3,5,8]{1}[0-9]{1}[0-9]{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(phone);
		return m.find();
	}
	
	/**
	 * 判断邮箱号是否合法
	 * 
	 * @param mPhone
	 * @return
	 */
	public static boolean isEmail(String email) {
		if (null == email || "".equals(email)) {
			return false;
		}
		String regExp = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(email);
		return m.find();
	}

	/**
	 * @Title: parseListToString
	 * @Description: 列表转换为字符串
	 * @param @param list 要转换的对象
	 * @param @param split 分隔符
	 * @param @return
	 * @return String
	 */
	public static String parseListToString(List list, String split) {
		if (list != null && list.size() > 0) {
			String str = "";
			int len = list.size();
			for (int i = 0; i < len; i++) {
				if (i != (len - 1)) {
					str += (list.get(i) + split);
				} else {
					str += list.get(i);
				}
			}
			return str;
		}
		return null;
	}

	/**
	 * @Title: pasreArrayToString
	 * @Description: 数组转字符串
	 * @param @param arr
	 * @param @param split
	 * @param @return
	 * @return String
	 */
	public static String pasreArrayToString(Object[] arr, String split) {
		if (arr != null && arr.length > 0) {
			String str = "";
			for (int i = 0; i < arr.length; i++) {
				if (i != (arr.length - 1)) {
					str += (arr[i] + split);
				} else {
					str += arr[i];
				}
			}
			return str;
		}
		return null;
	}

	/**
	 * @Title: getFileSuffix
	 * @Description: 获取文件后缀，返回如：.jpg
	 * @param @param name
	 * @param @return
	 * @return String
	 */
	public static String getFileSuffix(String name) {
		int loc = name.lastIndexOf('.');
		if (loc != -1) {
			return name.substring(loc);
		}
		return null;
	}

	/**
	 * @Title: getTimeFileName
	 * @Description: 获取默认的以是时间命名的文件名
	 * @param @return
	 * @return String
	 */
	public static String getTimeFileName(String suffix) {
		return formatDate(new Date(), "yyyyMMddHHmmssSSS") + suffix;
	}

	/**
	 * @Title: getAgeByBirthday
	 * @Description: 计算年龄
	 * @param @param birthday
	 * @param @return
	 * @return String
	 */
	public static String getAgeByBirthday(Date birthday) {
		int days = daysBetween(birthday, new Date());
		int year = days / 365;
		int month = (days % 365) / 30;
		String age = "";
		if (year > 0) {
			age = year + "岁";
			if (month > 0) {
				age = age + month + "个月";
			}
		} else if (month > 0) {
			age = month + "个月";
		}
		return age;
	}

	/**
	 * @Title: deleteFile
	 * @Description: 删除文件或文件夹
	 * @param @param realPath
	 * @return void
	 */
	public static void deleteFile(String realPath) {
		File file = new File(realPath);
		if (file.isFile() && file.exists()) {
			file.delete();
		} else {
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					files[i].delete();
				}
			}
			file.delete();
		}
	}

	/**
	 * @Title: getFileSize
	 * @Description: 根据路径获取文件大小
	 * @param @param path
	 * @param @return
	 * @return long
	 */
	public static long getFileSize(String path) {
		File file = new File(path);
		if (file.isFile() && file.exists()) {
			return file.length();
		}
		return 0;
	}

	/**
	 * @Title: makeDir
	 * @Description: 创建目录，如果存在则不创建
	 * @param @param path
	 * @return void
	 */
	public static boolean makeDir(String path) {
		return new File(path).mkdirs();
	}
	
	
	public static byte[] getImageToBytes(String imgPath) {  
	    byte[] bytes = null;  
	    ByteArrayOutputStream out = new ByteArrayOutputStream();  
	  
	    try {  
	        //创建URL  
	        URL url = new URL(imgPath);  
	        //得到连接  
	        HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();  
	        //得到连接地址的输入流  
	        InputStream in = urlConn.getInputStream();  
	  
	        int size;  
	        //缓冲值  
	        bytes = new byte[1024];  
	        if(in != null){  
	            //循环读输入流至read返回-1为止，并写到缓存中  
	            while((size=in.read(bytes)) != -1){  
	                out.write(bytes, 0, size);  
	            }  
	        }  
	        out.close();//关闭输出流  
	        in.close();//关闭输入流  
	        urlConn.disconnect();//断开连接  
	  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	  
	        return out.toByteArray();  
	}
	
	public static void bytesToImgSave(byte[] bytes, String imgFile) throws Exception{  
	    //UUID序列号作为保存图片的名称  
	    
	    File f = new File(imgFile);  
	  
	    try {
			DataOutputStream out = new DataOutputStream(new FileOutputStream(f));
			for (int i = 0; i < bytes.length; i++){
				out.write(bytes[i]);
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @Title: getDateTreeDir
	 * @Description: 组装根据年/月/日格式的文件目录 如：2012/04/20/
	 * @param @param date
	 * @param @return
	 * @return String
	 */
	public static String getDateTreeDir(Date date) {
		return Util.formatDate(date, "yyyy") + "/"
				+ Util.formatDate(date, "MM") + "/"
				+ Util.formatDate(date, "dd") + "/";
	}
	
	public static byte[] getFile2Bytes(String filePath){  
        byte[] buffer = null;  
        try {  
            File file = new File(filePath);  
            FileInputStream fis = new FileInputStream(file);  
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
            byte[] b = new byte[1000];  
            int n;  
            while ((n = fis.read(b)) != -1) {  
                bos.write(b, 0, n);  
            }  
            fis.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return buffer;  
    }
	
	/**
	 * 判断当前操作系统是不是window
	   * @create_date 2014-6-20 下午7:15:07
	   * @return
	 */
	public static boolean isWindows() {
		boolean flag = false;
		if (System.getProperties().getProperty("os.name").toUpperCase()
				.indexOf("WINDOWS") != -1) {
			flag = true;
		}
		return flag;
	}
	
	/**
	 * 文件复制
	   * @create_date 2014-6-25 下午4:28:43
	   * @param pathOld
	   * @param pathNew
	   * @return
	 */
	public static File copyFile(String pathOld,String pathNew){
		File fileOld = new File(pathOld);  
        File fileNew = new File(pathNew);  
        if(fileOld.exists()){  
            try {  
                FileInputStream fis = new FileInputStream(fileOld);  
                FileOutputStream fos = new FileOutputStream(fileNew);  
                int read = 0;  
                while ((read = fis.read()) != -1) {  
                    fos.write(read);  
                    fos.flush();  
                }  
                fos.close();  
                fis.close();  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }
        }
        return fileNew;
	}
	
	public static void writeLog(String log, String filePath) {
		FileWriter writer = null;
		try {
			writer = new FileWriter(filePath, true);
			writer.write(log);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				writer = null;
			}
		}
	}
	
	public static Integer string2Integer(String s){
		Integer rs = null;
		try{
			if(s!=null&&Pattern.compile("[0-9]*").matcher(s).matches()){
				rs = Integer.parseInt(s);
			}
		}catch(Exception e){
			return null;
		}		
		return rs;
	}
	
	/** 
     * 去掉开头和结尾的空格，合并中间的空格 
     */
	public static String mergeSpace(String str){        
        String result = "";          
        for(int i=0;i<str.length();i++){  
            if(str.substring(i, i+1).equals(" ")==true){  
                if(result.equals("")==true){      
                }else{  
                    if(result.equals("")!=true && result.substring(result.length()-1).equals(" ")==true){  
                        continue;  
                    }else{  
                        result = result+str.substring(i, i+1).toString();  
                    }  
                }                  
            }else{  
                result = result+str.substring(i, i+1).toString();  
            }              
            if(i==str.length()-1){  
                if(result.substring(result.length()-1).equals(" ")==true){  
                    result = result.substring(0, result.length()-1).toString();  
                }  
            }  
        }              
        return result;        
    }
	
	/**
	 * 获取文件名，并去掉扩展
	   * @create_date 2014-9-11 下午6:33:03
	   * @param filename
	   * @return
	 */
	public static String trimExtension(String filename) {   
	    if ((filename != null) && (filename.length() > 0)) {   
	        int i = filename.lastIndexOf('.');   
	        if ((i >-1) && (i < (filename.length()))) {   
	            return filename.substring(0, i);   
	        }   
	    }   
	    return filename;   
	}
	/**
	 * 获取文件扩展名
	   * @author zhr
	   * @create_date 2014-10-8 上午11:58:18
	   * @param fileName
	   * @return
	 */
	public static String getFileExtension(String fileName){
	      return fileName.substring(fileName.lastIndexOf(".")+1);
	  }
	
	/**
	 * 生成随机的字符串
	   * @author zhr
	   * @create_date 2014-10-13 下午6:41:17
	   * @param length
	   * @return
	 */
    public static String getCharacterAndNumber(int length)  
    {  
        String val = "";              
        Random random = new Random();  
        for(int i = 0; i < length; i++)  
        {  
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字                   
            if("char".equalsIgnoreCase(charOrNum)) // 字符串
            {
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母  
                val += (char) (choice + random.nextInt(26));  
            }  
            else if("num".equalsIgnoreCase(charOrNum)) // 数字  
            {  
                val += String.valueOf(random.nextInt(10));  
            }  
        }        
        return val;  
    }
    /**
     * 生成带时间因子的唯一字符串
       * @author zhr
       * @create_date 2014-10-14 下午6:02:20
       * @param childrandom
       * @return
     */
    public static String getUuid(String childrandom){
    	String child = getCharacterAndNumber(6);
    	String time = new Date().getTime()+"";
    	return time.substring(0, 8)+child+time.substring(9, time.length()-1);
    	
    }
    
    public static Map<String,String> getUrlInfo(String url){
    	if(url==null)
    		return null;
    	Map<String,String> map = new HashMap<String,String>();
		try {
			URL hp = new URL(url);
			map.put("protocol",hp.getProtocol()); // 协议
			map.put("port",hp.getPort()+""); // 端口
			map.put("host",hp.getHost()); // 主机
			map.put("filename",hp.getFile()); // url对应的文件名
			map.put("ext",hp.toExternalForm());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}        
    	return map;
    }
    
    
    public static int getWeeks(){
		Date now = new Date();
		/*Date start = addMonth(now, 2);
		start = addDay(start, 1);*/
		return weeksBetween(now, now);
	}
    
    /**
     * 获取百分数
       * @author zhr
       * @create_date 2014-11-13 下午3:16:20
       * @param d
       * @param point：小数点后的位数
       * @return
     */
    public static String getPercent(double d,int point){
    	NumberFormat nt = NumberFormat.getPercentInstance();	    	   
    	nt.setMinimumFractionDigits(point);//设置百分数精确度2即保留两位小数
    	return nt.format(d);
    }
    
    /**
	* 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指 定精度，以后的数字四舍五入。
	* @param v1 除数
	* @param v2 被除数
	* @param scale 表示表示需要精确到小数点以后几位。
	* @return 两个参数的商
	*/
	public static double div(double v1, double v2, int scale) {
	   if (scale < 0) {
	    throw new IllegalArgumentException("The scale must be a positive integer or zero");
	   }
	   BigDecimal b1 = new BigDecimal(Double.toString(v1));
	   BigDecimal b2 = new BigDecimal(Double.toString(v2));
	   double rs = b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	   BigDecimal bg = new BigDecimal(rs);
	   return bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	
	/**
	  * 将长整型数字转换为日期格式的字符串
	  *
	  * @param time
	  * @param format
	  * @return
	  */
	public static String getTimeString(long timelnMillis){
	    Calendar calendar = Calendar.getInstance();
	    calendar.setTimeInMillis(timelnMillis);
	    Date date = calendar.getTime();
	    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
	    String newTypeDate = f.format(date);
	    return newTypeDate;    
	}
	
	public static String getRootPath(String userPath) {		
		String classPath = Util.class.getClassLoader().getResource("/")
				.getPath();
		System.out.println("classPath---" + classPath);
		String rootPath = "";
		// windows下
		if ("\\".equals(File.separator)) {
			System.out.println("windows");
			rootPath = classPath.substring(1,
					classPath.indexOf("/WEB-INF/classes"));
			if (userPath != null) {
				rootPath += userPath;
			}
			rootPath = rootPath.replace("/", "\\");			
		}
		// linux下
		if ("/".equals(File.separator)) {
			System.out.println("linux");
			rootPath = classPath.substring(0,
					classPath.indexOf("/WEB-INF/classes"));
			if (userPath != null) {
				rootPath += userPath;
			}
			rootPath = rootPath.replace("\\", "/");			
		}
		return rootPath;	
	}
	
	/**
	 * 从字符串中截取连续6位数字组合 ([0-9]{" + 4 + "})截取六位数字 进行前后断言不能出现数字 用于从短信中获取动态密码
	 * 
	 * @param str
	 *            短信内容
	 * @return 截取得到的6位动态密码
	 */
	public static String getDynamicPassword(String str) {
		// 6是验证码的位数一般为六位
		Pattern continuousNumberPattern = Pattern.compile("(?<![0-9])([0-9]{"
				+ 4 + "})(?![0-9])");
		Matcher m = continuousNumberPattern.matcher(str);
		String dynamicPassword = "";
		while (m.find()) {
			System.out.print(m.group());
			dynamicPassword = m.group();
		}

		return dynamicPassword;
	}
	
	/**
	 * 格式化日期
	 * @param date
	 * @return
	 */
	public static String getFormatDate(Date date) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			return sdf.format(date);
		} catch (RuntimeException e) {
			return "";
		}
	}

}
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.smssdk.SMSSDK;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lling.qiqu.App;
import com.lling.qiqu.R;
import com.lling.qiqu.adapters.CommentAdapter;
import com.lling.qiqu.beans.Comment;
import com.lling.qiqu.beans.DingOrCai;
import com.lling.qiqu.beans.Joke;
import com.lling.qiqu.beans.User;
import com.lling.qiqu.commons.Constants;
import com.lling.qiqu.commons.PageResult;
import com.lling.qiqu.dao.DingCaiDAO;
import com.lling.qiqu.interfaces.ApiCallBack;
import com.lling.qiqu.service.IJokeService;
import com.lling.qiqu.service.impl.JokeServiceImpl;
import com.lling.qiqu.ui.LoadListView;
import com.lling.qiqu.ui.LoadListView.OnFootLoadingListener;
import com.lling.qiqu.ui.Scroll2BottomListenerScrollView;
import com.lling.qiqu.ui.popwindows.SharePopWindow;
import com.lling.qiqu.utils.BitmapUtil;
import com.lling.qiqu.utils.FastjsonUtil;
import com.lling.qiqu.utils.ProgressDialogUtils;
import com.lling.qiqu.utils.TaskExecutor;
import com.lling.qiqu.utils.ToastUtils;
import com.lling.qiqu.utils.ToolsUtils;
import com.lling.qiqu.utils.Util;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
					ToastUtils.showMessage(QuShiDetailActivity.this, R.string.has_cai);
					return;
				}
				View dingView = ((LinearLayout)v.getParent().getParent()).findViewById(R.id.ding_tv);
				if(dingView.isSelected()) {
					ToastUtils.showMessage(QuShiDetailActivity.this, R.string.has_ding);
					return;
				}
				final View view = ((RelativeLayout)v.getParent()).getChildAt(1);
				Animation addOneAnimation = AnimationUtils.loadAnimation(
						QuShiDetailActivity.this, R.anim.add_one);
				addOneAnimation.setAnimationListener(new AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {
						view.setVisibility(View.VISIBLE);
					}
					@Override
					public void onAnimationRepeat(Animation animation) {
					}
					@Override
					public void onAnimationEnd(Animation animation) {
						view.setVisibility(View.GONE);
					}
				});
				view.startAnimation(addOneAnimation);
				v.setSelected(true);
				mJoke.setOpposesNum(mJoke.getOpposesNum()+1);
				((TextView)v).setText(String.valueOf(mJoke.getOpposesNum()));
				mDingOrCaiDAO.dingOrCai(mUserId, mJokeId, DingOrCai.CAI, mJoke.getOpposesNum());
			}
		});
        mShareTV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSharePopWindow.setmJoke(mJoke);
				mSharePopWindow.showAtLocation(v.getRootView(), Gravity.LEFT | Gravity.BOTTOM, 0, 0);
			}
		});
        mCommentTV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mCommentContentET.requestFocus();
				ToolsUtils.openKeybord(mCommentContentET, QuShiDetailActivity.this);
			}
		});
	}
	
	/**
	 * 加载趣事评论
	 */
	private void loadComments() {
		if(!mHasNext){
			mListView.onFootLoadingComplete(true);
			return;
		}
		mQuShiService.getCommentByJokeId(mHandler, mJokeId, mPageId, mCount);
	}
	
	/**
	 * 加载数据成功，更新界面
	 * @param pageResult
	 */
	private void loadSuccess(PageResult pageResult) {
		mScrollView.setmListView(mListView);
		if(pageResult == null || pageResult.isEmpty()) {
			if(Constants.DEBUG) Log.w(TAG, "load qushi success, but no data!");
			mHasNext = false;
			return;
		}
		
		String tmp = FastjsonUtil.serialize(pageResult.getList());
		List<Comment> list = FastjsonUtil.deserializeList(tmp,
				Comment.class);
		mCommentLists.addAll(list);
		
		if(mCommentLists.size() <= 0) {   //无数据，显示无数据布局
		} else {
			mCommentAdapter.onDataChange(mCommentLists);
			mListView.setVisibility(View.VISIBLE);
		}
//		ToolsUtils.setListViewHeightBasedOnChildren(mListView);
		if(isCommnet && mPageId == 1) {   //如果点击评论进来的，则滚动到评论处
			TaskExecutor.scheduleTaskOnUiThread(150, new Runnable() {
				@Override
				public void run() {
					int height = mQushiLayout.getHeight();
					mScrollView.scrollTo(0, height);
				}
			});
		}
		mHasNext = pageResult.getHasNext();
		mListView.setHasMoreData(mHasNext);  //设置是否还有更多数据
		if (pageResult.getHasNext()) {
			mPageId = pageResult.getNext();
		}
	}
	
	@OnClick(R.id.add_comment_btn)
	private void sendComment(View view) {
		ToolsUtils.hideKeyboard(mCommentTV);
		if(App.currentUser == null) {  //用户未登录
			Intent intent = new Intent(this, LoginActivity.class);
			startActivityWithAnimation(intent);
			return;
		}
		String content = mCommentContentET.getText().toString().trim();
		if(Util.isEmpty(content)) {
			ToastUtils.showMessage(getApplicationContext(), 
					R.string.comment_content_null);
			return;
		}
		content = ToolsUtils.Html2Text(content);
		if(Util.isEmpty(content)) {
			ToastUtils.showMessage(getApplicationContext(), 
					R.string.input_invalide);
			return;
		}
		if(mJoke == null) {
			return;
		}
		ProgressDialogUtils.showProgressDialog(this, getString(R.string.commenting));