前言
前段時(shí)間要求項(xiàng)目中需要實(shí)現(xiàn)一個(gè)刷卡考勤的功能,因?yàn)樯婕暗缴蟼鲌D片文件,為加快考勤的速度,封裝了一個(gè)異步輪詢上傳文件的幫助類(lèi)
效果
先上效果圖

image
設(shè)計(jì)思路

image
數(shù)據(jù)庫(kù)使用的框架是GreenDao,一個(gè)非常好用的東西
先創(chuàng)建一個(gè)GreenDao的數(shù)據(jù)表的實(shí)體
來(lái)保存我們的考勤記錄,我這邊只寫(xiě)了一下幾個(gè)參數(shù),方便大家觀看,使用的時(shí)候大家記得要編譯一下來(lái)生成Dao文件跟get,set方法
@Entity
public class Attendance {
@Id(autoincrement = true)
public Long id;
/**
* 是否已上傳
* */
public Boolean isUpload;
/**
* 文件路徑
* */
public String path;
/**
* 姓名
* */
private String name;
/**
* 考勤時(shí)間
* */
private Date attendanceDate;
}
幫助類(lèi)的實(shí)現(xiàn)
首先是輪詢線程判斷是否運(yùn)行
/**
* 開(kāi)啟上傳線程
*/
public void startUpThread() {
if (!isRun) {
return;
}
singleThreadExecutor.execute(upRunnable);
}
線程需要注意內(nèi)存泄露,這個(gè)是必須的
/**
* 自建一個(gè)Runnable判斷activity是否銷(xiāo)毀,防止內(nèi)存泄露
* */
private class UpRunnable implements Runnable {
private WeakReference<Activity> activityWeakReference;
public UpRunnable(Activity activity) {
//使用弱引用賦值
activityWeakReference = new WeakReference<>(activity);
}
@Override
public void run() {
//判斷activity是否已銷(xiāo)毀
if (activityWeakReference.get() != null){
upRecord();
}
}
}
先查詢隊(duì)列判斷是否有數(shù)據(jù)需要上傳
沒(méi)有需要上傳的數(shù)據(jù)延遲兩秒后從數(shù)據(jù)庫(kù)查詢并填充隊(duì)列
開(kāi)始下一次的輪詢
private void upRecord() {
Attendance Attendance = queue.poll();
if (null == Attendance) {
//沒(méi)有需要上傳的文件
LogUtils.d("上傳隊(duì)列為空 2秒后開(kāi)始 檢查是否存在上報(bào)");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handleLocalAttendance();
startUpThread();
} else {
//有需要上傳的文件,回調(diào)給頁(yè)面
if (onUploadListener != null) {
onUploadListener.onUpload(Attendance);
} else {
startUpThread();
}
}
}
查詢數(shù)據(jù)庫(kù)的代碼
/**
* 查詢是否有上傳任務(wù)
*/
private void handleLocalAttendance() {
List<Attendance> attendances = DBHelper.getInstance().getSession().getAttendanceDao()
.queryBuilder().where(AttendanceDao.Properties.IsUpload.eq(false))
.list();
if (null != attendances && attendances.size() > 0) {
queue.addAll(attendances);
}
}
幫助類(lèi)的使用
首先是先在初始化幫助類(lèi)
UploadHelper uploadHelper = new UploadHelper(this);
uploadHelper.setOnUploadListener(new OnUploadListener() {
@Override
public void onUpload(Attendance attendance) {
//有需要上傳的文件
uploadToServer(attendance);
}
});
uploadHelper.startUpThread();
接口調(diào)用成功后標(biāo)記成功,開(kāi)始下一次的輪詢
uploadHelper.uploadSuccess(dataModel);
在打卡回調(diào)中添加數(shù)據(jù)庫(kù)記錄,這樣輪詢線程就會(huì)查到
//數(shù)據(jù)庫(kù)
Attendance attendance = new Attendance();
attendance.setPath(Environment.getExternalStorageDirectory() + "/" + "Images/picture.png");
attendance.setIsUpload(false);
attendance.setName("張三");
attendance.setAttendanceDate(new Date());
uploadHelper.addRecord(attendance);
updateDataList();