以前做的点赞功能,一般都是在当前activity里开辟一个新线程执行网络交互点赞成功,失败功能。但是问题来了,点赞的东西在很多歌activity里都会有相同的线程操作,比如文章点赞,视频点赞,主界面点赞。 所以功能点可以进行封装。防止代码的冗余,并且修改一处就可以修改多处。java 面向对象封装,好处多多。
(封装性的好处)
实例:
package cdv.cq.mobilestation.Activity.praise; import android.content.Context; import cdv.cq.mobilestation.tools.JsonBean; import cdv.cq.mobilestation.tools.ResultObject; /** * 点赞工具类 * */ public class PraiseProvider { private Context mcontext; private String clickId; private String clickType; private ResultObject resJson = new ResultObject(); private JsonBean jsben = new JsonBean(); private int count; private Dao dao; public PraiseProvider(Context context,String clickId,String clickType) { this.mcontext = context; this.clickId = clickId; this.clickType = clickType; dao = Dao.getInstance(mcontext); Dao.createTable(); } /** * 点赞 * return 点赞成功后的数目 * */ public int goPraise(){ Thread thread = new Thread(PraiseRunnable); thread.start(); try { //等待子线程完毕执行后续方法 thread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return count; } /** * 查询点赞数 * return 点赞数 * */ public int queryCount(){ Thread thread = new Thread(QueryPraiseCountRunnable); thread.start(); try { thread.join(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return count; } /** * 查询是否点过赞 * */ public boolean Praised(){ int id = dao.isHasInfors(clickId,clickType); int operation = dao.queryUserPraise(String.valueOf(id)); if(operation == 1){ //点过赞 return true; } else{ return false; } } //读取数据库点赞数 Runnable QueryPraiseCountRunnable = new Runnable() { @Override public void run() { int id = dao.isHasInfors(clickId,clickType); if(id == -1){ //表中没有点赞 读取网络点赞数 int operation = 0; //数目查询 resJson = (ResultObject) jsben.getPraiseCount (mcontext, clickType, clickId, operation); if(resJson.result){ count = Integer.parseInt((String)resJson.obj); }else{ count = -1; } }else{ //读取数据库中的缓存值 count = dao.queryPraiseCount(String.valueOf(id)); } } }; //点赞 Runnable PraiseRunnable = new Runnable() { @Override public void run() { int id = dao.isHasInfors(clickId, clickType); if(id == -1){ //新增数目 int operation = 1; //数目添加1 resJson = (ResultObject) jsben.getPraiseCount (mcontext, clickType, clickId, operation); if(resJson.result){ count = Integer.parseInt((String)resJson.obj); dao.insert(clickId, clickType,count); //强转 }else{ count = -1; } } } }; }
PraiseProvider praiseProvider = new PraiseProvider(HomeTypeNewsActivity.this, cannlId, clickType); count = praiseProvider.queryCount(); if(praiseProvider.Praised()){ //点过赞 mHandler.sendEmptyMessage(Constant.CONSTANT_FIVE); }else{ mHandler.sendEmptyMessage(Constant.CONSTANT_FOUR); }