gtask/remote中4个代码都注释好了

src
zhangjinhan 8 months ago
parent 13da0ed7b2
commit 5c7de6cf58

@ -1,4 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
@ -28,67 +27,95 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
* GTaskASyncTask Google Task
* Android AsyncTask
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 定义 Google Task 同步的通知 ID
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
/**
* OnCompleteListener
*/
public interface OnCompleteListener {
void onComplete();
}
// 上下文环境
private Context mContext;
// 通知管理器
private NotificationManager mNotifiManager;
// Google Task 管理器
private GTaskManager mTaskManager;
// 同步完成后的监听器
private OnCompleteListener mOnCompleteListener;
/**
* Google Task
* @param context
* @param listener
*/
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotifiManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mTaskManager = GTaskManager.getInstance();
}
/**
*
*/
public void cancelSync() {
mTaskManager.cancelSync();
}
/**
*
* @param message
*/
public void publishProgess(String message) {
publishProgress(new String[] {
message
});
publishProgress(new String[]{message});
}
/**
*
* @param tickerId ID
* @param content
*/
private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis());
Notification notification = new Notification(R.drawable.notification, mContext.getString(tickerId), System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_LIGHTS;
notification.flags = Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesPreferenceActivity.class), 0);
} else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesListActivity.class), 0);
}
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, pendingIntent);
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
/**
* 线
* @param unused
* @return
*/
@Override
protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity.getSyncAccountName(mContext)));
return mTaskManager.sync(mContext, this);
}
/**
*
* @param progress
*/
@Override
protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]);
@ -97,23 +124,24 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
}
}
/**
*
* @param result
*/
@Override
protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount()));
showNotification(R.string.ticker_success, mContext.getString(R.string.success_sync_account, mTaskManager.getSyncAccount()));
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
} else if (result == GTaskManager.STATE_NETWORK_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled));
showNotification(R.string.ticker_cancel, mContext.getString(R.string.error_sync_cancelled));
}
if (mOnCompleteListener != null) {
new Thread(new Runnable() {
public void run() {
mOnCompleteListener.onComplete();
}

@ -61,6 +61,7 @@ import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
// GTaskClient 类用于与 Google Tasks 远程服务进行交互
public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName();
@ -90,6 +91,7 @@ public class GTaskClient {
private JSONArray mUpdateArray;
// 私有构造函数,确保只能通过 getInstance 方法获取实例
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
@ -102,6 +104,7 @@ public class GTaskClient {
mUpdateArray = null;
}
// 获取 GTaskClient 的单例实例
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -109,6 +112,7 @@ public class GTaskClient {
return mInstance;
}
// 登录 Google Tasks如果已登录则检查登录状态是否过期或账户是否切换
public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
@ -164,6 +168,7 @@ public class GTaskClient {
return true;
}
// 获取 Google 账户的认证令牌,如果需要则失效当前令牌
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
@ -207,6 +212,7 @@ public class GTaskClient {
return authToken;
}
// 尝试登录 Google Tasks如果第一次失败则尝试失效认证令牌后重新登录
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the
@ -225,6 +231,7 @@ public class GTaskClient {
return true;
}
// 使用认证令牌登录 Google Tasks 并获取客户端版本
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000;
@ -280,10 +287,12 @@ public class GTaskClient {
return true;
}
// 获取并递增一个唯一的动作 ID
private int getActionId() {
return mActionId++;
}
// 创建一个用于发送 POST 请求的 HttpPost 对象,并设置必要的头部信息
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -291,6 +300,7 @@ public class GTaskClient {
return httpPost;
}
// 从 HttpEntity 中读取响应内容,并根据内容编码进行解压
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
@ -323,6 +333,7 @@ public class GTaskClient {
}
}
// 发送 POST 请求并获取响应的 JSONObject
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -360,6 +371,7 @@ public class GTaskClient {
}
}
// 创建一个新的任务,并发送相应的 POST 请求到 Google Tasks
public void createTask(Task task) throws NetworkFailureException {
commitUpdate();
try {
@ -370,7 +382,7 @@ public class GTaskClient {
actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// client version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
@ -386,6 +398,7 @@ public class GTaskClient {
}
}
// 创建一个新的任务列表,并发送相应的 POST 请求到 Google Tasks
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate();
try {
@ -412,6 +425,7 @@ public class GTaskClient {
}
}
// 提交更新列表中的所有动作到 Google Tasks
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
@ -433,6 +447,7 @@ public class GTaskClient {
}
}
// 添加一个节点的更新动作到更新列表中
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// too many update items may result in an error
@ -447,6 +462,7 @@ public class GTaskClient {
}
}
// 移动一个任务到另一个任务列表,并发送相应的 POST 请求到 Google Tasks
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
commitUpdate();
@ -486,6 +502,7 @@ public class GTaskClient {
}
}
// 删除一个节点,并发送相应的 POST 请求到 Google Tasks
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
try {
@ -509,6 +526,7 @@ public class GTaskClient {
}
}
// 获取所有任务列表,并返回相应的 JSONArray
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -547,6 +565,7 @@ public class GTaskClient {
}
}
// 获取指定任务列表中的所有任务,并返回相应的 JSONArray
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
try {
@ -575,10 +594,12 @@ public class GTaskClient {
}
}
// 获取当前同步的 Google 账户
public Account getSyncAccount() {
return mAccount;
}
// 重置更新列表
public void resetUpdateArray() {
mUpdateArray = null;
}

@ -47,7 +47,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
// 这是一个管理Google任务同步的类
public class GTaskManager {
private static final String TAG = GTaskManager.class.getSimpleName();
@ -87,6 +87,7 @@ public class GTaskManager {
private HashMap<Long, String> mNidToGid;
// 私有构造函数,防止外部实例化
private GTaskManager() {
mSyncing = false;
mCancelled = false;
@ -99,6 +100,7 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>();
}
// 获取GTaskManager的单例实例
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@ -106,11 +108,12 @@ public class GTaskManager {
return mInstance;
}
// 设置活动上下文,用于获取认证令牌
public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
mActivity = activity;
}
// 同步Google任务与本地数据库
public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
@ -131,18 +134,18 @@ public class GTaskManager {
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
// login google task
// 登录Google任务
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed");
}
}
// get the task list from google
// 从Google获取任务列表
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList();
// do content sync work
// 同步内容
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent();
} catch (NetworkFailureException e) {
@ -168,6 +171,7 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
// 初始化Google任务列表
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
@ -175,19 +179,18 @@ public class GTaskManager {
try {
JSONArray jsTaskLists = client.getTaskLists();
// init meta list first
// 初始化元数据列表
mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object);
// load meta data
// 加载元数据
JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j);
@ -203,29 +206,26 @@ public class GTaskManager {
}
}
// create meta list if not existed
// 如果元数据列表不存在则创建
if (mMetaList == null) {
mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META);
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META);
GTaskClient.getInstance().createTaskList(mMetaList);
}
// init task list
// 初始化任务列表
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) {
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist);
// load tasks
// 加载任务
JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j);
@ -247,6 +247,7 @@ public class GTaskManager {
}
}
// 同步内容到Google任务或本地数据库
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;
@ -259,12 +260,9 @@ public class GTaskManager {
return;
}
// for local deleted note
// 同步本地删除的笔记
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, null);
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(type<>? AND parent_id=?)", new String[] { String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) }, null);
if (c != null) {
while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
@ -286,15 +284,12 @@ public class GTaskManager {
}
}
// sync folder first
// 同步文件夹
syncFolder();
// for note existing in database
// 同步本地存在的笔记
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(type=? AND parent_id<>?)", new String[] { String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) }, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
@ -306,10 +301,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
// 本地新增
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
// 远程删除
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
@ -326,7 +321,7 @@ public class GTaskManager {
}
}
// go through remaining items
// 同步剩余的Google任务
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
@ -334,16 +329,14 @@ public class GTaskManager {
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
// mCancelled can be set by another thread, so we neet to check one by
// one
// clear local delete table
// 清除本地删除的条目
if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes");
}
}
// refresh local sync id
// 刷新本地同步ID
if (!mCancelled) {
GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId();
@ -351,6 +344,7 @@ public class GTaskManager {
}
// 同步文件夹到Google任务或本地数据库
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
@ -361,10 +355,9 @@ public class GTaskManager {
return;
}
// for root folder
// 同步根文件夹
try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
if (c != null) {
c.moveToNext();
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
@ -373,9 +366,8 @@ public class GTaskManager {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
// for system folder, only update remote name if necessary
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
// 更新远程名称(如果需要)
if (!node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
@ -390,12 +382,9 @@ public class GTaskManager {
}
}
// for call-note folder
// 同步通话记录文件夹
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
}, null);
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", new String[] { String.valueOf(Notes.ID_CALL_RECORD_FOLDER) }, null);
if (c != null) {
if (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
@ -404,11 +393,8 @@ public class GTaskManager {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if
// necessary
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE))
// 更新远程名称(如果需要)
if (!node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
@ -424,12 +410,9 @@ public class GTaskManager {
}
}
// for local existing folders
// 同步本地存在的文件夹
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(type=? AND parent_id<>?)", new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) }, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
@ -441,10 +424,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
// 本地新增
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
// 远程删除
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
@ -460,7 +443,7 @@ public class GTaskManager {
}
}
// for remote add folders
// 同步远程新增的文件夹
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
@ -476,6 +459,7 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate();
}
// 执行内容同步操作
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -510,8 +494,8 @@ public class GTaskManager {
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea
// right now just use local update simply
// 合并修改可能是更好的做法
// 目前我们简单地使用本地更新
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_NONE:
@ -522,6 +506,7 @@ public class GTaskManager {
}
}
// 在本地添加Google任务节点
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
@ -529,11 +514,9 @@ public class GTaskManager {
SqlNote sqlNote;
if (node instanceof TaskList) {
if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
} else if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
} else if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
} else {
sqlNote = new SqlNote(mContext);
@ -549,7 +532,7 @@ public class GTaskManager {
if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// the id is not available, have to create a new one
// ID不可用必须创建一个新的
note.remove(NoteColumns.ID);
}
}
@ -562,8 +545,7 @@ public class GTaskManager {
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// the data id is not available, have to create
// a new one
// Data ID不可用必须创建一个新的
data.remove(DataColumns.ID);
}
}
@ -584,30 +566,30 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue());
}
// create the local node
// 创建本地节点
sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false);
// update gid-nid mapping
// 更新GID-NID映射
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta
// 更新元数据
updateRemoteMeta(node.getGid(), sqlNote);
}
// 更新本地Google任务节点
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote;
// update the note locally
// 更新本地笔记
sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent());
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
: new Long(Notes.ID_ROOT_FOLDER);
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) : new Long(Notes.ID_ROOT_FOLDER);
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot update local node");
@ -615,10 +597,11 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true);
// update meta info
// 更新元数据信息
updateRemoteMeta(node.getGid(), sqlNote);
}
// 在Google任务中添加新的节点
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -627,7 +610,7 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c);
Node n;
// update remotely
// 远程更新
if (sqlNote.isNoteType()) {
Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent());
@ -642,12 +625,12 @@ public class GTaskManager {
GTaskClient.getInstance().createTask(task);
n = (Node) task;
// add meta
// 添加元数据
updateRemoteMeta(task.getGid(), sqlNote);
} else {
TaskList tasklist = null;
// we need to skip folder if it has already existed
// 如果文件夹已经存在则跳过
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT;
@ -671,7 +654,7 @@ public class GTaskManager {
}
}
// no match we can add now
// 如果没有匹配项则可以添加
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
@ -681,17 +664,18 @@ public class GTaskManager {
n = (Node) tasklist;
}
// update local note
// 更新本地笔记
sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false);
sqlNote.resetLocalModified();
sqlNote.commit(true);
// gid-id mapping
// GID-ID映射
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
// 在Google任务中更新节点
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -699,14 +683,14 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely
// 远程更新
node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node);
// update meta
// 更新元数据
updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary
// 如果需要移动任务
if (sqlNote.isNoteType()) {
Task task = (Task) node;
TaskList preParentList = task.getParent();
@ -725,11 +709,12 @@ public class GTaskManager {
}
}
// clear local modified flag
// 清除本地修改标志
sqlNote.resetLocalModified();
sqlNote.commit(true);
}
// 更新Google任务中的元数据
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
@ -746,12 +731,13 @@ public class GTaskManager {
}
}
// 刷新本地同步ID
private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) {
return;
}
// get the latest gtask list
// 获取最新的Google任务列表
mGTaskHashMap.clear();
mGTaskListHashMap.clear();
mMetaHashMap.clear();
@ -759,10 +745,7 @@ public class GTaskManager {
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(type<>? AND parent_id<>?)", new String[] { String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) }, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
@ -771,12 +754,10 @@ public class GTaskManager {
mGTaskHashMap.remove(gid);
ContentValues values = new ContentValues();
values.put(NoteColumns.SYNC_ID, node.getLastModified());
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
c.getLong(SqlNote.ID_COLUMN)), values, null, null);
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(SqlNote.ID_COLUMN)), values, null, null);
} else {
Log.e(TAG, "something is missed");
throw new ActionFailureException(
"some local items don't have gid after sync");
throw new ActionFailureException("some local items don't have gid after sync");
}
}
} else {
@ -790,10 +771,12 @@ public class GTaskManager {
}
}
// 获取同步账户
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}
// 取消同步
public void cancelSync() {
mCancelled = true;
}

@ -23,25 +23,36 @@ import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
// GTaskSyncService 是一个用于同步任务的服务类
public class GTaskSyncService extends Service {
// 定义同步操作的 action 类型名称
public final static String ACTION_STRING_NAME = "sync_action_type";
// 定义开始同步的 action 类型
public final static int ACTION_START_SYNC = 0;
// 定义取消同步的 action 类型
public final static int ACTION_CANCEL_SYNC = 1;
// 定义无效的 action 类型
public final static int ACTION_INVALID = 2;
// 定义同步服务广播名称
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
// 定义同步服务广播中是否正在同步的键名
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
// 定义同步服务广播中进度信息的键名
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
// 静态变量,用于存储同步任务实例
private static GTaskASyncTask mSyncTask = null;
// 静态变量,用于存储同步进度信息
private static String mSyncProgress = "";
// 启动同步任务的方法
private void startSync() {
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -56,17 +67,20 @@ public class GTaskSyncService extends Service {
}
}
// 取消同步任务的方法
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
// 服务创建时的回调方法
@Override
public void onCreate() {
mSyncTask = null;
}
// 服务启动命令的回调方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
@ -86,6 +100,7 @@ public class GTaskSyncService extends Service {
return super.onStartCommand(intent, flags, startId);
}
// 服务内存不足时的回调方法
@Override
public void onLowMemory() {
if (mSyncTask != null) {
@ -93,10 +108,12 @@ public class GTaskSyncService extends Service {
}
}
// 返回服务的 IBinder 对象
public IBinder onBind(Intent intent) {
return null;
}
// 发送同步进度广播的方法
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -105,6 +122,7 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent);
}
// 静态方法,用于启动同步服务
public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
@ -112,16 +130,19 @@ public class GTaskSyncService extends Service {
activity.startService(intent);
}
// 静态方法,用于取消同步服务
public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
}
// 检查是否正在同步的方法
public static boolean isSyncing() {
return mSyncTask != null;
}
// 获取同步进度信息的方法
public static String getProgressString() {
return mSyncProgress;
}

@ -33,7 +33,7 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
// 代表一个笔记,包含笔记的基本信息和笔记数据
public class Note {
private ContentValues mNoteDiffValues;
private NoteData mNoteData;
@ -70,36 +70,44 @@ public class Note {
mNoteData = new NoteData();
}
// 设置笔记的基本信息
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
// 设置文本笔记的数据
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
// 设置文本笔记的数据ID
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
// 获取文本笔记的数据ID
public long getTextDataId() {
return mNoteData.mTextDataId;
}
// 设置通话笔记的数据ID
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}
// 设置通话笔记的数据
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
}
// 判断笔记是否被本地修改过
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
// 同步笔记到数据库
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -130,6 +138,7 @@ public class Note {
return true;
}
// 笔记数据类,包含文本数据和通话数据
private class NoteData {
private long mTextDataId;
@ -148,10 +157,12 @@ public class Note {
mCallDataId = 0;
}
// 判断笔记数据是否被本地修改过
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
// 设置文本数据ID
void setTextDataId(long id) {
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
@ -159,6 +170,7 @@ public class Note {
mTextDataId = id;
}
// 设置通话数据ID
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
@ -166,18 +178,21 @@ public class Note {
mCallDataId = id;
}
// 设置通话数据
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
// 设置文本数据
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
// 将笔记数据推送到内容解析器
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety

Loading…
Cancel
Save