diff --git a/src/Notes-master/src/net/micode/notes/gtask/exception/ActionFailureException.java b/src/Notes-master/src/net/micode/notes/gtask/exception/ActionFailureException.java index 15504be..3daed4f 100644 --- a/src/Notes-master/src/net/micode/notes/gtask/exception/ActionFailureException.java +++ b/src/Notes-master/src/net/micode/notes/gtask/exception/ActionFailureException.java @@ -15,13 +15,18 @@ */ package net.micode.notes.gtask.exception; - +/** + * GTask同步动作执行失败的运行时异常类 + */ public class ActionFailureException extends RuntimeException { + //序列化版本号 private static final long serialVersionUID = 4425249765923293627L; + //创建无异常消息的ActionFailureException实例 public ActionFailureException() { super(); } + //创建包含指定错误消息的ActionFailureException实例 public ActionFailureException(String paramString) { super(paramString); diff --git a/src/Notes-master/src/net/micode/notes/gtask/exception/NetworkFailureException.java b/src/Notes-master/src/net/micode/notes/gtask/exception/NetworkFailureException.java index b08cfb1..53e4ab5 100644 --- a/src/Notes-master/src/net/micode/notes/gtask/exception/NetworkFailureException.java +++ b/src/Notes-master/src/net/micode/notes/gtask/exception/NetworkFailureException.java @@ -15,14 +15,22 @@ */ package net.micode.notes.gtask.exception; - +/** + * 网络失败异常类 + * 用于表示与网络相关的操作失败 + */ public class NetworkFailureException extends Exception { private static final long serialVersionUID = 2107610287180234136L; - + /** + * 默认构造函数 + * 创建一个没有详细错误信息的网络失败异常 + */ public NetworkFailureException() { super(); } - + /** + * 带有错误信息的构造函数 + */ public NetworkFailureException(String paramString) { super(paramString); } diff --git a/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskASyncTask.java b/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskASyncTask.java index b3b61e7..da9746c 100644 --- a/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskASyncTask.java +++ b/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskASyncTask.java @@ -28,23 +28,33 @@ import net.micode.notes.R; import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesPreferenceActivity; - +/** + * GTask同步异步任务类 + * 1. 后台执行同步(登录验证、数据同步); + * 2. 实时发布同步进度并通过系统通知展示; + * 3. 同步完成后根据结果(成功/网络错误/内部错误/取消)展示对应通知; + */ public class GTaskASyncTask extends AsyncTask { - + /** + * GTask同步通知的唯一标识ID + * 用于区分其他通知,避免通知混淆 + */ private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; public interface OnCompleteListener { void onComplete(); } - + //上下文对象,用于获取系统服务、资源 private Context mContext; - + //通知管理器 private NotificationManager mNotifiManager; private GTaskManager mTaskManager; private OnCompleteListener mOnCompleteListener; - + /** + * 初始化GTask同步异步任务 + */ public GTaskASyncTask(Context context, OnCompleteListener listener) { mContext = context; mOnCompleteListener = listener; @@ -52,7 +62,9 @@ public class GTaskASyncTask extends AsyncTask { .getSystemService(Context.NOTIFICATION_SERVICE); mTaskManager = GTaskManager.getInstance(); } - + /** + * 取消正在进行的GTask同步 + */ public void cancelSync() { mTaskManager.cancelSync(); } @@ -63,25 +75,50 @@ public class GTaskASyncTask extends AsyncTask { }); } - private void showNotification(int tickerId, String content) { - 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); - - } else { - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesListActivity.class), 0); - } - notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, - pendingIntent); - mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); +// private void showNotification(int tickerId, String content) { +// 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); +// + // } else { +// pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, +// NotesListActivity.class), 0); +// } +// notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, +// pendingIntent); +// mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); +// } + /** + * 构建并显示GTask同步相关通知 + * 区分不同场景的通知跳转逻辑: + * - 非成功(失败/取消):跳转至笔记偏好设置页面(GTask账号配置); + * - 成功:跳转至笔记列表页面; + */ +private void showNotification(int tickerId, String content) { + PendingIntent pendingIntent; + if (tickerId != R.string.ticker_success) { + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, + NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE); + } else { + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, + NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE); } - + // 构建通知 + Notification.Builder builder = new Notification.Builder(mContext) + .setAutoCancel(true) + .setContentTitle(mContext.getString(R.string.app_name)) + .setContentText(content) + .setContentIntent(pendingIntent) + .setWhen(System.currentTimeMillis()) + .setOngoing(true); + Notification notification=builder.getNotification(); + mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); +} @Override protected Integer doInBackground(Void... unused) { publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity @@ -96,7 +133,13 @@ public class GTaskASyncTask extends AsyncTask { ((GTaskSyncService) mContext).sendBroadcast(progress[0]); } } - + /** + * 主线程同步完成回调 + * 1. 成功:展示成功通知,记录最后同步时间; + * 2. 网络错误:展示网络错误通知; + * 3. 内部错误:展示内部错误通知; + * 4. 取消:展示同步取消通知; + */ @Override protected void onPostExecute(Integer result) { if (result == GTaskManager.STATE_SUCCESS) { diff --git a/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskClient.java b/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskClient.java index c67dfdf..bf36ee4 100644 --- a/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskClient.java +++ b/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskClient.java @@ -110,14 +110,14 @@ public class GTaskClient { } public boolean login(Activity activity) { - // we suppose that the cookie would expire after 5 minutes - // then we need to re-login + // 假设Cookie在5分钟后过期 + // 如果超过5分钟,需要重新登录 final long interval = 1000 * 60 * 5; if (mLastLoginTime + interval < System.currentTimeMillis()) { mLoggedin = false; } - // need to re-login after account switch + // 账户切换后需要重新登录 if (mLoggedin && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity .getSyncAccountName(activity))) { @@ -136,7 +136,7 @@ public class GTaskClient { return false; } - // login with custom domain if necessary + // 如果必要,使用自定义域名登录 if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() .endsWith("googlemail.com"))) { StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); @@ -151,7 +151,7 @@ public class GTaskClient { } } - // try to login with google official url + // 如果自定义域名登录失败,尝试使用Google官方URL登录 if (!mLoggedin) { mGetUrl = GTASK_GET_URL; mPostUrl = GTASK_POST_URL; @@ -163,7 +163,7 @@ public class GTaskClient { mLoggedin = true; return true; } - + //登录Google账户并获取授权令牌 private String loginGoogleAccount(Activity activity, boolean invalidateToken) { String authToken; AccountManager accountManager = AccountManager.get(activity); @@ -189,7 +189,7 @@ public class GTaskClient { return null; } - // get the token now + // 获取token AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile", null, activity, null, null); try { @@ -206,7 +206,10 @@ 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 @@ -224,7 +227,11 @@ public class GTaskClient { } return true; } - + /** + * 实际执行Google Tasks登录 + * + * @return 登录成功返回true,否则返回false + */ private boolean loginGtask(String authToken) { int timeoutConnection = 10000; int timeoutSocket = 15000; @@ -236,14 +243,14 @@ public class GTaskClient { mHttpClient.setCookieStore(localBasicCookieStore); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); - // login gtask + // 登录gtask try { String loginUrl = mGetUrl + "?auth=" + authToken; HttpGet httpGet = new HttpGet(loginUrl); HttpResponse response = null; response = mHttpClient.execute(httpGet); - // get the cookie now + // 检查cookie是否存在 List cookies = mHttpClient.getCookieStore().getCookies(); boolean hasAuthCookie = false; for (Cookie cookie : cookies) { @@ -336,7 +343,7 @@ public class GTaskClient { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); httpPost.setEntity(entity); - // execute the post + // 执行请求 HttpResponse response = mHttpClient.execute(httpPost); String jsString = getResponseContent(response.getEntity()); return new JSONObject(jsString); @@ -392,14 +399,11 @@ public class GTaskClient { JSONObject jsPost = new JSONObject(); JSONArray actionList = new JSONArray(); - // action_list actionList.put(tasklist.getCreateAction(getActionId())); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - // client version jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - // post JSONObject jsResponse = postRequest(jsPost); JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( GTaskStringUtils.GTASK_JSON_RESULTS).get(0); @@ -417,10 +421,8 @@ public class GTaskClient { try { JSONObject jsPost = new JSONObject(); - // action_list jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); - // client_version jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); postRequest(jsPost); @@ -435,8 +437,6 @@ public class GTaskClient { public void addUpdateNode(Node node) throws NetworkFailureException { if (node != null) { - // too many update items may result in an error - // set max to 10 items if (mUpdateArray != null && mUpdateArray.length() > 10) { commitUpdate(); } @@ -455,26 +455,21 @@ public class GTaskClient { JSONArray actionList = new JSONArray(); JSONObject action = new JSONObject(); - // action_list action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); if (preParent == curParent && task.getPriorSibling() != null) { - // put prioring_sibing_id only if moving within the tasklist and - // it is not the first one action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); } action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); if (preParent != curParent) { - // put the dest_list only if moving between tasklists action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); } actionList.put(action); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - // client_version jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); postRequest(jsPost); @@ -492,12 +487,10 @@ public class GTaskClient { JSONObject jsPost = new JSONObject(); JSONArray actionList = new JSONArray(); - // action_list node.setDeleted(true); actionList.put(node.getUpdateAction(getActionId())); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - // client_version jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); postRequest(jsPost); @@ -520,7 +513,6 @@ public class GTaskClient { HttpResponse response = null; response = mHttpClient.execute(httpGet); - // get the task list String resString = getResponseContent(response.getEntity()); String jsBegin = "_setup("; String jsEnd = ")}"; @@ -554,7 +546,6 @@ public class GTaskClient { JSONArray actionList = new JSONArray(); JSONObject action = new JSONObject(); - // action_list action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); @@ -563,7 +554,6 @@ public class GTaskClient { actionList.put(action); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - // client_version jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); JSONObject jsResponse = postRequest(jsPost); diff --git a/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskManager.java b/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskManager.java index d2b4082..5df1c66 100644 --- a/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskManager.java +++ b/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskManager.java @@ -49,8 +49,9 @@ import java.util.Map; public class GTaskManager { + // 日志标签,使用类名作为标签 private static final String TAG = GTaskManager.class.getSimpleName(); - + // 同步状态常量 public static final int STATE_SUCCESS = 0; public static final int STATE_NETWORK_ERROR = 1; @@ -72,6 +73,7 @@ public class GTaskManager { private boolean mSyncing; private boolean mCancelled; + // 数据存储结构 private HashMap mGTaskListHashMap; @@ -107,7 +109,7 @@ public class GTaskManager { } public synchronized void setActivityContext(Activity activity) { - // used for getting authtoken + mActivity = activity; } @@ -131,18 +133,15 @@ public class GTaskManager { GTaskClient client = GTaskClient.getInstance(); client.resetUpdateArray(); - // login google task if (!mCancelled) { if (!client.login(mActivity)) { throw new NetworkFailureException("login google task failed"); } } - // get the task list from 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) { @@ -175,7 +174,6 @@ 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); @@ -187,7 +185,6 @@ public class GTaskManager { 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,7 +200,6 @@ public class GTaskManager { } } - // create meta list if not existed if (mMetaList == null) { mMetaList = new TaskList(); mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX @@ -211,7 +207,6 @@ public class GTaskManager { 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); @@ -225,7 +220,6 @@ public class GTaskManager { 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); @@ -259,7 +253,6 @@ 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[] { @@ -286,10 +279,8 @@ 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[] { @@ -306,10 +297,8 @@ 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 +315,6 @@ public class GTaskManager { } } - // go through remaining items Iterator> iter = mGTaskHashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = iter.next(); @@ -334,16 +322,12 @@ 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 if (!mCancelled) { GTaskClient.getInstance().commitUpdate(); refreshLocalSyncId(); @@ -361,7 +345,6 @@ 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); @@ -390,7 +373,6 @@ public class GTaskManager { } } - // for call-note folder try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", new String[] { @@ -404,8 +386,7 @@ 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)) @@ -424,7 +405,6 @@ public class GTaskManager { } } - // for local existing folders try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(type=? AND parent_id<>?)", new String[] { @@ -460,7 +440,6 @@ public class GTaskManager { } } - // for remote add folders Iterator> iter = mGTaskListHashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = iter.next(); @@ -584,15 +563,12 @@ public class GTaskManager { sqlNote.setParentId(parentId.longValue()); } - // create the local node sqlNote.setGtaskId(node.getGid()); sqlNote.commit(false); - // update gid-nid mapping mGidToNid.put(node.getGid(), sqlNote.getId()); mNidToGid.put(sqlNote.getId(), node.getGid()); - // update meta updateRemoteMeta(node.getGid(), sqlNote); } @@ -602,7 +578,6 @@ public class GTaskManager { } SqlNote sqlNote; - // update the note locally sqlNote = new SqlNote(mContext, c); sqlNote.setContent(node.getLocalJSONFromContent()); @@ -615,7 +590,6 @@ public class GTaskManager { sqlNote.setParentId(parentId.longValue()); sqlNote.commit(true); - // update meta info updateRemoteMeta(node.getGid(), sqlNote); } @@ -627,7 +601,6 @@ 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 +615,10 @@ 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 +642,6 @@ public class GTaskManager { } } - // no match we can add now if (tasklist == null) { tasklist = new TaskList(); tasklist.setContentByLocalJSON(sqlNote.getContent()); @@ -681,13 +651,11 @@ public class GTaskManager { n = (Node) tasklist; } - // update local note sqlNote.setGtaskId(n.getGid()); sqlNote.commit(false); sqlNote.resetLocalModified(); sqlNote.commit(true); - // gid-id mapping mGidToNid.put(n.getGid(), sqlNote.getId()); mNidToGid.put(sqlNote.getId(), n.getGid()); } @@ -699,14 +667,11 @@ 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,7 +690,6 @@ public class GTaskManager { } } - // clear local modified flag sqlNote.resetLocalModified(); sqlNote.commit(true); } @@ -751,7 +715,6 @@ public class GTaskManager { return; } - // get the latest gtask list mGTaskHashMap.clear(); mGTaskListHashMap.clear(); mMetaHashMap.clear(); diff --git a/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskSyncService.java b/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskSyncService.java index cca36f7..d6166e1 100644 --- a/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskSyncService.java +++ b/src/Notes-master/src/net/micode/notes/gtask/remote/GTaskSyncService.java @@ -22,12 +22,17 @@ import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; - +/** + * GTask(谷歌任务)同步服务类,继承自 Android 系统 Service,用于在后台处理笔记与 GTask 的同步逻辑。 + * 1. 启动/取消 GTask 同步操作 + * 2. 通过广播通知外部组件同步状态和同步进度 + * 3. 管理同步异步任务的生命周期 + */ public class GTaskSyncService extends Service { public final static String ACTION_STRING_NAME = "sync_action_type"; - + //同步操作类型:启动 GTask 同步 public final static int ACTION_START_SYNC = 0; - + //同步操作类型:启取消GTask 同步 public final static int ACTION_CANCEL_SYNC = 1; public final static int ACTION_INVALID = 2; @@ -41,7 +46,11 @@ public class GTaskSyncService extends Service { private static GTaskASyncTask mSyncTask = null; private static String mSyncProgress = ""; - + /** + * 1. 检查异步任务实例是否为空(避免重复启动) + * 2. 若为空则创建新的异步任务,设置完成回调(任务结束后清空实例、发送空进度广播、停止服务) + * 3. 发送初始同步状态广播,执行异步任务 + */ private void startSync() { if (mSyncTask == null) { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { @@ -66,7 +75,7 @@ public class GTaskSyncService extends Service { public void onCreate() { mSyncTask = null; } - + //解析 Intent 中的同步操作类型,执行对应操作(启动/取消同步) @Override public int onStartCommand(Intent intent, int flags, int startId) { Bundle bundle = intent.getExtras(); @@ -96,7 +105,7 @@ public class GTaskSyncService extends Service { public IBinder onBind(Intent intent) { return null; } - + //发送同步状态广播,通知外部组件当前同步状态和进度 public void sendBroadcast(String msg) { mSyncProgress = msg; Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);