diff --git a/src/main/java/net/micode/notes/gtask/data/SqlNote.java b/src/main/java/net/micode/notes/gtask/data/SqlNote.java index 79a4095..d16f8e5 100644 --- a/src/main/java/net/micode/notes/gtask/data/SqlNote.java +++ b/src/main/java/net/micode/notes/gtask/data/SqlNote.java @@ -14,6 +14,11 @@ * limitations under the License. */ +/* + * Description:用于支持小米便签最底层的数据库相关操作,和sqldata的关系上是父集关系,即note是data的子父集。 + * 和SqlData相比,SqlNote算是真正意义上的数据了。 + */ + package net.micode.notes.gtask.data; import android.appwidget.AppWidgetManager; @@ -38,11 +43,28 @@ import org.json.JSONObject; import java.util.ArrayList; +/* + * Description:用于支持小米便签最底层的数据库相关操作,和sqldata的关系上是父集关系,即note是data的子父集。 + * 和SqlData相比,SqlNote算是真正意义上的数据了。 + */ + +/* + * 功能描述: + * 实现过程: + * 参数注解: + * Made By CuiCan + */ + public class SqlNote { + /* + * 功能描述:得到类的简写名称存入字符串TAG中 + * 实现过程:调用getSimpleName ()函数 + * Made By CuiCan + */ private static final String TAG = SqlNote.class.getSimpleName(); private static final int INVALID_ID = -99999; - + // 集合了interface NoteColumns中所有SF常量(17个) public static final String[] PROJECTION_NOTE = new String[] { NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, @@ -52,6 +74,7 @@ public class SqlNote { NoteColumns.VERSION }; + //以下设置17个列的编号 public static final int ID_COLUMN = 0; public static final int ALERTED_DATE_COLUMN = 1; @@ -86,6 +109,7 @@ public class SqlNote { public static final int VERSION_COLUMN = 16; + //一下定义了17个内部的变量,其中12个可以由content中获得,5个需要初始化为0或者new private Context mContext; private ContentResolver mContentResolver; @@ -122,6 +146,13 @@ public class SqlNote { private ArrayList mDataList; + /* + * 功能描述:构造函数 + * 参数注解: mIsCreate用于标示构造方式 + * 参数注解: + * Made By CuiCan + */ + //构造函数只有context,对所有的变量进行初始化 public SqlNote(Context context) { mContext = context; mContentResolver = context.getContentResolver(); @@ -129,9 +160,9 @@ public class SqlNote { mId = INVALID_ID; mAlertDate = 0; mBgColorId = ResourceParser.getDefaultBgId(context); - mCreatedDate = System.currentTimeMillis(); + mCreatedDate = System.currentTimeMillis();//调用系统函数获得创建时间 mHasAttachment = 0; - mModifiedDate = System.currentTimeMillis(); + mModifiedDate = System.currentTimeMillis();//最后一次修改时间初始化为创建时间 mParentId = 0; mSnippet = ""; mType = Notes.TYPE_NOTE; @@ -143,17 +174,33 @@ public class SqlNote { mDataList = new ArrayList(); } + + /* + * 功能描述:构造函数 + * 参数注解: mIsCreate用于标示构造方式 + * 参数注解: + * Made By CuiCan + */ + //构造函数有context和一个数据库的cursor,多数变量通过cursor指向的一条记录直接进行初始化 public SqlNote(Context context, Cursor c) { mContext = context; mContentResolver = context.getContentResolver(); mIsCreate = false; loadFromCursor(c); mDataList = new ArrayList(); + // if (mType == Notes.TYPE_NOTE) loadDataContent(); mDiffNoteValues = new ContentValues(); } + + /* + * 功能描述:构造函数 + * 参数注解: mIsCreate用于标示构造方式 + * 参数注解: + * Made By CuiCan + */ public SqlNote(Context context, long id) { mContext = context; mContentResolver = context.getContentResolver(); @@ -166,16 +213,21 @@ public class SqlNote { } + /* + * 功能描述:通过id从光标处加载数据 + * Made By CuiCan + */ private void loadFromCursor(long id) { Cursor c = null; try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", new String[] { - String.valueOf(id) - }, null); + String.valueOf(id) + }, null);//通过id获得对应的ContentResolver中的cursor if (c != null) { c.moveToNext(); - loadFromCursor(c); + loadFromCursor(c);//然后加载数据进行初始化,这样函数 + //SqlNote(Context context, long id)与SqlNote(Context context, long id)的实现方式基本相同 } else { Log.w(TAG, "loadFromCursor: cursor = null"); } @@ -185,7 +237,12 @@ public class SqlNote { } } + /* + * 功能描述:通过游标从光标处加载数据 + * Made By CuiCan + */ private void loadFromCursor(Cursor c) { + //直接从一条记录中的获得以下变量的初始值 mId = c.getLong(ID_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN); mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); @@ -200,13 +257,18 @@ public class SqlNote { mVersion = c.getLong(VERSION_COLUMN); } + /* + * 功能描述:通过content机制获取共享数据并加载到数据库当前游标处 + * 参数注解: + * Made By CuiCan + */ private void loadDataContent() { Cursor c = null; mDataList.clear(); try { c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, "(note_id=?)", new String[] { - String.valueOf(mId) + String.valueOf(mId) }, null); if (c != null) { if (c.getCount() == 0) { @@ -226,6 +288,11 @@ public class SqlNote { } } + /* + * 功能描述:设置通过content机制用于共享的数据信息 + * 参数注解: + * Made By CuiCan + */ public boolean setContent(JSONObject js) { try { JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); @@ -267,7 +334,6 @@ public class SqlNote { mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); } mBgColorId = bgColorId; - long createDate = note.has(NoteColumns.CREATED_DATE) ? note .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); if (mIsCreate || mCreatedDate != createDate) { @@ -359,6 +425,11 @@ public class SqlNote { return true; } + /* + * 功能描述:获取content机制提供的数据并加载到note中 + * 参数注解: + * Made By CuiCan + */ public JSONObject getContent() { try { JSONObject js = new JSONObject(); @@ -369,7 +440,7 @@ public class SqlNote { } JSONObject note = new JSONObject(); - if (mType == Notes.TYPE_NOTE) { + if (mType == Notes.TYPE_NOTE) {//类型为note时 note.put(NoteColumns.ID, mId); note.put(NoteColumns.ALERTED_DATE, mAlertDate); note.put(NoteColumns.BG_COLOR_ID, mBgColorId); @@ -392,7 +463,7 @@ public class SqlNote { } } js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); - } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { + } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {//类型为文件夹或者 note.put(NoteColumns.ID, mId); note.put(NoteColumns.TYPE, mType); note.put(NoteColumns.SNIPPET, mSnippet); @@ -407,39 +478,84 @@ public class SqlNote { return null; } + /* + * 功能描述:给当前id设置父id + * 参数注解: + * Made By CuiCan + */ public void setParentId(long id) { mParentId = id; mDiffNoteValues.put(NoteColumns.PARENT_ID, id); } + /* + * 功能描述:给当前id设置Gtaskid + * 参数注解: + * Made By CuiCan + */ public void setGtaskId(String gid) { mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); } + /* + * 功能描述:给当前id设置同步id + * 参数注解: + * Made By CuiCan + */ public void setSyncId(long syncId) { mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); } + /* + * 功能描述:初始化本地修改,即撤销所有当前修改 + * 参数注解: + * Made By CuiCan + */ public void resetLocalModified() { mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); } + /* + * 功能描述:获得当前id + * 参数注解: + * Made By CuiCan + */ public long getId() { return mId; } + /* + * 功能描述:获得当前id的父id + * 参数注解: + * Made By CuiCan + */ public long getParentId() { return mParentId; } + /* + * 功能描述:获取小片段即用于显示的部分便签内容 + * 参数注解: + * Made By CuiCan + */ public String getSnippet() { return mSnippet; } + /* + * 功能描述:判断是否为便签类型 + * 参数注解: + * Made By CuiCan + */ public boolean isNoteType() { return mType == Notes.TYPE_NOTE; } + /* + * 功能描述:commit函数用于把当前造作所做的修改保存到数据库 + * 参数注解: + * Made By CuiCan + */ public void commit(boolean validateVersion) { if (mIsCreate) { if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { @@ -458,7 +574,7 @@ public class SqlNote { } if (mType == Notes.TYPE_NOTE) { - for (SqlData sqlData : mDataList) { + for (SqlData sqlData : mDataList) {//直接使用sqldata中的实现 sqlData.commit(mId, false, -1); } } @@ -470,14 +586,14 @@ public class SqlNote { if (mDiffNoteValues.size() > 0) { mVersion ++; int result = 0; - if (!validateVersion) { + if (!validateVersion) {//构造字符串 result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" + NoteColumns.ID + "=?)", new String[] { - String.valueOf(mId) + String.valueOf(mId) }); } else { result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" - + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", + + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", new String[] { String.valueOf(mId), String.valueOf(mVersion) }); diff --git a/src/main/java/net/micode/notes/gtask/data/Task.java b/src/main/java/net/micode/notes/gtask/data/Task.java index 6a19454..278fc27 100644 --- a/src/main/java/net/micode/notes/gtask/data/Task.java +++ b/src/main/java/net/micode/notes/gtask/data/Task.java @@ -32,25 +32,27 @@ import org.json.JSONException; import org.json.JSONObject; + + public class Task extends Node { private static final String TAG = Task.class.getSimpleName(); - private boolean mCompleted; + private boolean mCompleted;//是否完成 private String mNotes; - private JSONObject mMetaInfo; + private JSONObject mMetaInfo;//将在实例中存储数据的类型 - private Task mPriorSibling; + private Task mPriorSibling;//对应的优先兄弟Task的指针(待完善) - private TaskList mParent; + private TaskList mParent;//所在的任务列表的指针 public Task() { super(); mCompleted = false; mNotes = null; - mPriorSibling = null; - mParent = null; + mPriorSibling = null;//TaskList中当前Task前面的Task的指针 + mParent = null;//当前Task所在的TaskList mMetaInfo = null; } @@ -80,14 +82,18 @@ public class Task extends Node { js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // parent_id - js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); + if (mParent!= null) { + js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); + } // dest_parent_type js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, GTaskStringUtils.GTASK_JSON_TYPE_GROUP); // list_id - js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); + if (mParent!= null) { + js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); + } // prior_sibling_id if (mPriorSibling != null) { @@ -175,7 +181,7 @@ public class Task extends Node { } } - public void setContentByLocalJSON(JSONObject js) { + public void setContentByLocalJSON(JSONObject js) { //��metadata����ʵʩ if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) || !js.has(GTaskStringUtils.META_HEAD_DATA)) { Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); diff --git a/src/main/java/net/micode/notes/gtask/data/TaskList.java b/src/main/java/net/micode/notes/gtask/data/TaskList.java index 4ea21c5..6af65de 100644 --- a/src/main/java/net/micode/notes/gtask/data/TaskList.java +++ b/src/main/java/net/micode/notes/gtask/data/TaskList.java @@ -30,12 +30,14 @@ import org.json.JSONObject; import java.util.ArrayList; + + public class TaskList extends Node { - private static final String TAG = TaskList.class.getSimpleName(); + private static final String TAG = TaskList.class.getSimpleName();//tag标记 - private int mIndex; + private int mIndex;//当前TaskList的指针 - private ArrayList mChildren; + private ArrayList mChildren;//类中主要的保存数据的单元,用来实现一个以Task为元素的ArrayList public TaskList() { super(); @@ -43,6 +45,10 @@ public class TaskList extends Node { mIndex = 1; } + /* (non-Javadoc) + * @see net.micode.notes.gtask.data.Node#getCreateAction(int) + * 生成并返回一个包含了一定数据的JSONObject实体 + */ public JSONObject getCreateAction(int actionId) { JSONObject js = new JSONObject(); @@ -58,7 +64,7 @@ public class TaskList extends Node { js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); // entity_delta - JSONObject entity = new JSONObject(); + JSONObject entity = new JSONObject();//entity实体 entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, @@ -74,6 +80,10 @@ public class TaskList extends Node { return js; } + /* (non-Javadoc) + * @see net.micode.notes.gtask.data.Node#getUpdateAction(int) + * 生成并返回一个包含了一定数据的JSONObject实体 + */ public JSONObject getUpdateAction(int actionId) { JSONObject js = new JSONObject(); @@ -216,10 +226,19 @@ public class TaskList extends Node { return SYNC_ACTION_ERROR; } + /** + * @return + * 功能:获得TaskList的大小,即mChildren的大小 + */ public int getChildTaskCount() { return mChildren.size(); } + /** + * @param task + * @return 返回值为是否成功添加任务。 + * 功能:在当前任务表末尾添加新的任务。 + */ public boolean addChildTask(Task task) { boolean ret = false; if (task != null && !mChildren.contains(task)) { @@ -229,11 +248,19 @@ public class TaskList extends Node { task.setPriorSibling(mChildren.isEmpty() ? null : mChildren .get(mChildren.size() - 1)); task.setParent(this); + //注意:每一次ArrayList的变化都要紧跟相关Task中PriorSibling的更改 + //,接下来几个函数都有相关操作 } } return ret; } + /** + * @param task + * @param index + * @return + * 功能:在当前任务表的指定位置添加新的任务。 + */ public boolean addChildTask(Task task, int index) { if (index < 0 || index > mChildren.size()) { Log.e(TAG, "add child task: invalid index"); @@ -260,6 +287,11 @@ public class TaskList extends Node { return true; } + /** + * @param task + * @return 返回删除是否成功 + * 功能:删除TaskList中的一个Task + */ public boolean removeChildTask(Task task) { boolean ret = false; int index = mChildren.indexOf(task); @@ -281,6 +313,12 @@ public class TaskList extends Node { return ret; } + /** + * @param task + * @param index + * @return + * 功能:将当前TaskList中含有的某个Task移到index位置 + */ public boolean moveChildTask(Task task, int index) { if (index < 0 || index >= mChildren.size()) { @@ -297,8 +335,14 @@ public class TaskList extends Node { if (pos == index) return true; return (removeChildTask(task) && addChildTask(task, index)); + //利用已实现好的功能完成当下功能; } + /** + * @param gid + * @return返回寻找结果 + * 功能:按gid寻找Task + */ public Task findChildTaskByGid(String gid) { for (int i = 0; i < mChildren.size(); i++) { Task t = mChildren.get(i); @@ -309,10 +353,20 @@ public class TaskList extends Node { return null; } + /** + * @param task + * @return + * 功能:返回指定Task的index + */ public int getChildTaskIndex(Task task) { return mChildren.indexOf(task); } + /** + * @param index + * @return + * 功能:返回指定index的Task + */ public Task getChildTaskByIndex(int index) { if (index < 0 || index >= mChildren.size()) { Log.e(TAG, "getTaskByIndex: invalid index"); @@ -321,8 +375,13 @@ public class TaskList extends Node { return mChildren.get(index); } + /** + * @param gid + * @return + * 功能:返回指定gid的Task + */ public Task getChilTaskByGid(String gid) { - for (Task task : mChildren) { + for (Task task : mChildren) {//一种常见的ArrayList的遍历方法(四种,见精读笔记) if (task.getGid().equals(gid)) return task; } @@ -340,4 +399,4 @@ public class TaskList extends Node { public int getIndex() { return this.mIndex; } -} +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java b/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java index 15504be..f455c7a 100644 --- a/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java +++ b/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java @@ -1,28 +1,27 @@ /* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Description:支持小米便签运行过程中的运行异常处理。 */ package net.micode.notes.gtask.exception; public class ActionFailureException extends RuntimeException { private static final long serialVersionUID = 4425249765923293627L; + /* + * serialVersionUID相当于java类的身份证。主要用于版本控制。 + * serialVersionUID作用是序列化时保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。 + * Made By Cuican + */ public ActionFailureException() { super(); } - + /* + * 在JAVA类中使用super来引用父类的成分,用this来引用当前对象. + * 如果一个类从另外一个类继承,我们new这个子类的实例对象的时候,这个子类对象里面会有一个父类对象。 + * 怎么去引用里面的父类对象呢?使用super来引用 + * 也就是说,此处super()以及super (paramString)可认为是Exception ()和Exception (paramString) + * Made By Cuican + */ public ActionFailureException(String paramString) { super(paramString); } @@ -30,4 +29,4 @@ public class ActionFailureException extends RuntimeException { public ActionFailureException(String paramString, Throwable paramThrowable) { super(paramString, paramThrowable); } -} +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java b/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java index b08cfb1..63a1adb 100644 --- a/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java +++ b/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java @@ -1,28 +1,28 @@ /* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Description:支持小米便签运行过程中的网络异常处理。 */ package net.micode.notes.gtask.exception; public class NetworkFailureException extends Exception { private static final long serialVersionUID = 2107610287180234136L; + /* + * serialVersionUID相当于java类的身份证。主要用于版本控制。 + * serialVersionUID作用是序列化时保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。 + * Made By Cuican + */ public NetworkFailureException() { super(); } + /* + * 在JAVA类中使用super来引用父类的成分,用this来引用当前对象. + * 如果一个类从另外一个类继承,我们new这个子类的实例对象的时候,这个子类对象里面会有一个父类对象。 + * 怎么去引用里面的父类对象呢?使用super来引用 + * 也就是说,此处super()以及super (paramString)可认为是Exception ()和Exception (paramString) + * Made By Cuican + */ public NetworkFailureException(String paramString) { super(paramString); } @@ -30,4 +30,4 @@ public class NetworkFailureException extends Exception { public NetworkFailureException(String paramString, Throwable paramThrowable) { super(paramString, paramThrowable); } -} +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java index 440a871..fb6fb02 100644 --- a/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java +++ b/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java @@ -29,8 +29,18 @@ import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesPreferenceActivity; + + +/*异步操作类,实现GTask的异步操作过程 + * 主要方法: + * private void showNotification(int tickerId, String content) 向用户提示当前同步的状态,是一个用于交互的方法 + * protected Integer doInBackground(Void... unused) 此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间 + * protected void onProgressUpdate(String... progress) 可以使用进度条增加用户体验度。 此方法在主线程执行,用于显示任务执行的进度。 + * protected void onPostExecute(Integer result) 相当于Handler 处理UI的方式,在这里面可以使用在doInBackground 得到的结果处理操作UI + */ public class GTaskASyncTask extends AsyncTask { + private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; public interface OnCompleteListener { @@ -57,24 +67,22 @@ public class GTaskASyncTask extends AsyncTask { mTaskManager.cancelSync(); } - public void publishProgess(String message) { + public void publishProgess(String message) { // 发布进度单位,系统将会调用onProgressUpdate()方法更新这些值 publishProgress(new String[] { - message + message }); } private void showNotification(int tickerId, String content) { - PendingIntent pendingIntent; + PendingIntent pendingIntent; //一个描述了想要启动一个Activity、Broadcast或是Service的意图 if (tickerId != R.string.ticker_success) { pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesPreferenceActivity.class), 0); - + NotesPreferenceActivity.class), 0); //如果同步不成功,那么从系统取得一个用于启动一个NotesPreferenceActivity的PendingIntent对象 } else { pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesListActivity.class), 0); - } - + NotesListActivity.class), 0); //如果同步成功,那么从系统取得一个用于启动一个NotesListActivity的PendingIntent对象 + } Notification.Builder builder = new Notification.Builder(mContext) .setAutoCancel(true) .setContentTitle(mContext.getString(R.string.app_name)) @@ -83,31 +91,30 @@ public class GTaskASyncTask extends AsyncTask { .setWhen(System.currentTimeMillis()) .setOngoing(true); Notification notification=builder.getNotification(); - mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); + mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//通过NotificationManager对象的notify()方法来执行一个notification的消息 } - @Override protected Integer doInBackground(Void... unused) { publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity - .getSyncAccountName(mContext))); - return mTaskManager.sync(mContext, this); + .getSyncAccountName(mContext))); //利用getString,将把 NotesPreferenceActivity.getSyncAccountName(mContext))的字符串内容传进sync_progress_login中 + return mTaskManager.sync(mContext, this); //进行后台同步具体操作 } @Override protected void onProgressUpdate(String... progress) { showNotification(R.string.ticker_syncing, progress[0]); - if (mContext instanceof GTaskSyncService) { + if (mContext instanceof GTaskSyncService) { //instanceof 判断mContext是否是GTaskSyncService的实例 ((GTaskSyncService) mContext).sendBroadcast(progress[0]); } } @Override - protected void onPostExecute(Integer result) { + protected void onPostExecute(Integer result) { //用于在执行完后台任务后更新UI,显示结果 if (result == GTaskManager.STATE_SUCCESS) { showNotification(R.string.ticker_success, mContext.getString( R.string.success_sync_account, mTaskManager.getSyncAccount())); - NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); + 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) { @@ -115,14 +122,14 @@ public class GTaskASyncTask extends AsyncTask { } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { showNotification(R.string.ticker_cancel, mContext .getString(R.string.error_sync_cancelled)); - } + } //几种不同情况下的结果显示 if (mOnCompleteListener != null) { - new Thread(new Runnable() { + new Thread(new Runnable() { //这里好像是方法内的一个线程,但是并不太懂什么意思 - public void run() { + public void run() { //完成后的操作,使用onComplete()将所有值都重新初始化,相当于完成一次操作 mOnCompleteListener.onComplete(); } }).start(); } } -} +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java b/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java index c1fc748..409f5f8 100644 --- a/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java +++ b/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java @@ -61,10 +61,16 @@ import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; + + +/* + * 主要功能:实现GTASK的登录操作,进行GTASK任务的创建,创建任务列表,从网络上获取任务和任务列表的内容 + * 主要使用类或技术:accountManager JSONObject HttpParams authToken Gid + */ public class GTaskClient { private static final String TAG = GTaskClient.class.getSimpleName(); - private static final String GTASK_URL = "https://mail.google.com/tasks/"; + private static final String GTASK_URL = "https://mail.google.com/tasks/"; //这个是指定的URL private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; @@ -102,6 +108,10 @@ public class GTaskClient { mUpdateArray = null; } + /*用来获取的实例化对象 + * 使用 getInstance() + * 返回mInstance这个实例化对象 + */ public static synchronized GTaskClient getInstance() { if (mInstance == null) { mInstance = new GTaskClient(); @@ -109,42 +119,50 @@ public class GTaskClient { return mInstance; } + /*用来实现登录操作的函数,传入的参数是一个Activity + * 设置登录操作限制时间,如果超时则需要重新登录 + * 有两种登录方式,使用用户自己的URL登录或者使用谷歌官方的URL登录 + * 返回true或者false,即最后是否登陆成功 + */ public boolean login(Activity activity) { // we suppose that the cookie would expire after 5 minutes // then we need to re-login + //判断距离最后一次登录操作是否超过5分钟 final long interval = 1000 * 60 * 5; if (mLastLoginTime + interval < System.currentTimeMillis()) { mLoggedin = false; } - // need to re-login after account switch + // need to re-login after account switch 重新登录操作 if (mLoggedin && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity .getSyncAccountName(activity))) { mLoggedin = false; } + //如果没超过时间,则不需要重新登录 if (mLoggedin) { Log.d(TAG, "already logged in"); return true; } - mLastLoginTime = System.currentTimeMillis(); - String authToken = loginGoogleAccount(activity, false); + mLastLoginTime = System.currentTimeMillis();//更新最后登录时间,改为系统当前的时间 + String authToken = loginGoogleAccount(activity, false);//判断是否登录到谷歌账户 if (authToken == null) { Log.e(TAG, "login google account failed"); return false; } // login with custom domain if necessary - if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() + //尝试使用用户自己的域名登录 + if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() //将用户账号名改为统一格式(小写)后判断是否为一个谷歌账号地址 .endsWith("googlemail.com"))) { StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); int index = mAccount.name.indexOf('@') + 1; String suffix = mAccount.name.substring(index); url.append(suffix + "/"); - mGetUrl = url.toString() + "ig"; - mPostUrl = url.toString() + "r/ig"; + mGetUrl = url.toString() + "ig"; //设置用户对应的getUrl + mPostUrl = url.toString() + "r/ig"; //设置用户对应的postUrl if (tryToLoginGtask(activity, authToken)) { mLoggedin = true; @@ -152,6 +170,7 @@ public class GTaskClient { } // try to login with google official url + //如果用户账户无法登录,则使用谷歌官方的URI进行登录 if (!mLoggedin) { mGetUrl = GTASK_GET_URL; mPostUrl = GTASK_POST_URL; @@ -164,10 +183,15 @@ public class GTaskClient { return true; } + /*具体实现登录谷歌账户的方法 + * 使用令牌机制 + * 使用AccountManager来管理注册账号 + * 返回值是账号的令牌 + */ private String loginGoogleAccount(Activity activity, boolean invalidateToken) { - String authToken; - AccountManager accountManager = AccountManager.get(activity); - Account[] accounts = accountManager.getAccountsByType("com.google"); + String authToken; //令牌,是登录操作保证安全性的一个方法 + AccountManager accountManager = AccountManager.get(activity);//AccountManager这个类给用户提供了集中注册账号的接口 + Account[] accounts = accountManager.getAccountsByType("com.google");//获取全部以com.google结尾的account if (accounts.length == 0) { Log.e(TAG, "there is no available google account"); @@ -176,6 +200,7 @@ public class GTaskClient { String accountName = NotesPreferenceActivity.getSyncAccountName(activity); Account account = null; + //遍历获得的accounts信息,寻找已经记录过的账户信息 for (Account a : accounts) { if (a.name.equals(accountName)) { account = a; @@ -190,11 +215,13 @@ public class GTaskClient { } // get the token now + //获取选中账号的令牌 AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile", null, activity, null, null); try { Bundle authTokenBundle = accountManagerFuture.getResult(); authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); + //如果是invalidateToken,那么需要调用invalidateAuthToken(String, String)方法废除这个无效token if (invalidateToken) { accountManager.invalidateAuthToken("com.google", authToken); loginGoogleAccount(activity, false); @@ -207,10 +234,12 @@ public class GTaskClient { return authToken; } + //尝试登陆Gtask,这只是一个预先判断令牌是否是有效以及是否能登上GTask的方法,而不是具体实现登陆的方法 private boolean tryToLoginGtask(Activity activity, String authToken) { if (!loginGtask(authToken)) { - // maybe the auth token is out of date, now let's invalidate the + // maybe the auth token is out of authTokedate, now let's invalidate the // token and try again + //删除过一个无效的authToken,申请一个新的后再次尝试登陆 authToken = loginGoogleAccount(activity, true); if (authToken == null) { Log.e(TAG, "login google account failed"); @@ -225,25 +254,27 @@ public class GTaskClient { return true; } + //实现登录GTask的具体操作 private boolean loginGtask(String authToken) { int timeoutConnection = 10000; - int timeoutSocket = 15000; - HttpParams httpParameters = new BasicHttpParams(); - HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); - HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); + int timeoutSocket = 15000; //socket是一种通信连接实现数据的交换的端口 + HttpParams httpParameters = new BasicHttpParams(); //实例化一个新的HTTP参数类 + HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);//设置连接超时时间 + HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);//设置设置端口超时时间 mHttpClient = new DefaultHttpClient(httpParameters); - BasicCookieStore localBasicCookieStore = new BasicCookieStore(); + BasicCookieStore localBasicCookieStore = new BasicCookieStore(); //设置本地cookie mHttpClient.setCookieStore(localBasicCookieStore); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); // login gtask try { - String loginUrl = mGetUrl + "?auth=" + authToken; - HttpGet httpGet = new HttpGet(loginUrl); + String loginUrl = mGetUrl + "?auth=" + authToken; //设置登录的url + HttpGet httpGet = new HttpGet(loginUrl); //通过登录的uri实例化网页上资源的查找 HttpResponse response = null; response = mHttpClient.execute(httpGet); // get the cookie now + //获取CookieStore里存放的cookie,看如果存有“GTL(不知道什么意思)”,则说明有验证成功的有效的cookie List cookies = mHttpClient.getCookieStore().getCookies(); boolean hasAuthCookie = false; for (Cookie cookie : cookies) { @@ -256,6 +287,7 @@ public class GTaskClient { } // get the client version + //获取client的内容,具体操作是在返回的Content中截取从_setup(开始到)}中间的字符串内容,也就是gtask_url的内容 String resString = getResponseContent(response.getEntity()); String jsBegin = "_setup("; String jsEnd = ")}"; @@ -284,6 +316,10 @@ public class GTaskClient { return mActionId++; } + /*实例化创建一个用于向网络传输数据的对象 + * 使用HttpPost类 + * 返回一个httpPost实例化对象,但里面还没有内容 + */ private HttpPost createHttpPost() { HttpPost httpPost = new HttpPost(mPostUrl); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); @@ -291,24 +327,28 @@ public class GTaskClient { return httpPost; } + /*通过URL获取响应后返回的数据,也就是网络上的数据和资源 + * 使用getContentEncoding()获取网络上的资源和数据 + * 返回值就是获取到的资源 + */ private String getResponseContent(HttpEntity entity) throws IOException { String contentEncoding = null; - if (entity.getContentEncoding() != null) { + if (entity.getContentEncoding() != null) {//通过URL得到HttpEntity对象,如果不为空则使用getContent()方法创建一个流将数据从网络都过来 contentEncoding = entity.getContentEncoding().getValue(); Log.d(TAG, "encoding: " + contentEncoding); } InputStream input = entity.getContent(); - if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { + if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {//GZIP是使用DEFLATE进行压缩数据的另一个压缩库 input = new GZIPInputStream(entity.getContent()); - } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { + } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {//DEFLATE是一个无专利的压缩算法,它可以实现无损数据压缩 Inflater inflater = new Inflater(true); input = new InflaterInputStream(entity.getContent(), inflater); } try { InputStreamReader isr = new InputStreamReader(input); - BufferedReader br = new BufferedReader(isr); + BufferedReader br = new BufferedReader(isr);//是一个包装类,它可以包装字符流,将字符流放入缓存里,先把字符读到缓存里,到缓存满了时候,再读入内存,是为了提供读的效率而设计的 StringBuilder sb = new StringBuilder(); while (true) { @@ -323,20 +363,28 @@ public class GTaskClient { } } + /*通过JSON发送请求 + * 请求的具体内容在json的实例化对象js中然后传入 + * 利用UrlEncodedFormEntity entity和httpPost.setEntity(entity)方法把js中的内容放置到httpPost中 + * 执行请求后使用getResponseContent方法得到返回的数据和资源 + * 将资源再次放入json后返回 + */ private JSONObject postRequest(JSONObject js) throws NetworkFailureException { - if (!mLoggedin) { + if (!mLoggedin) {//未登录 Log.e(TAG, "please login first"); throw new ActionFailureException("not logged in"); } + //实例化一个httpPost的对象用来向服务器传输数据,在这里就是发送请求,而请求的内容在js里 HttpPost httpPost = createHttpPost(); try { LinkedList list = new LinkedList(); list.add(new BasicNameValuePair("r", js.toString())); - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); //UrlEncodedFormEntity()的形式比较单一,是普通的键值对 httpPost.setEntity(entity); // execute the post + //执行这个请求 HttpResponse response = mHttpClient.execute(httpPost); String jsString = getResponseContent(response.getEntity()); return new JSONObject(jsString); @@ -360,6 +408,12 @@ public class GTaskClient { } } + /*创建单个任务 + * 传入参数是一个.gtask.data.Task包里Task类的对象 + * 利用json获取Task里的内容,并且创建相应的jsPost + * 利用postRequest得到任务的返回信息 + * 使用task.setGid设置task的new_ID + */ public void createTask(Task task) throws NetworkFailureException { commitUpdate(); try { @@ -386,6 +440,9 @@ public class GTaskClient { } } + /* + * 创建一个任务列表,与createTask几乎一样,区别就是最后设置的是tasklist的gid + */ public void createTaskList(TaskList tasklist) throws NetworkFailureException { commitUpdate(); try { @@ -412,6 +469,11 @@ public class GTaskClient { } } + /* + * 同步更新操作 + * 使用JSONObject进行数据存储,使用jsPost.put,Put的信息包括UpdateArray和ClientVersion + * 使用postRequest发送这个jspost,进行处理 + */ public void commitUpdate() throws NetworkFailureException { if (mUpdateArray != null) { try { @@ -433,6 +495,10 @@ public class GTaskClient { } } + /* + * 添加更新的事项 + * 调用commitUpdate()实现 + */ public void addUpdateNode(Node node) throws NetworkFailureException { if (node != null) { // too many update items may result in an error @@ -447,6 +513,12 @@ public class GTaskClient { } } + /* + * 移动task,比如讲task移动到不同的task列表中去 + * 通过getGid获取task所属列表的gid + * 通过JSONObject.put(String name, Object value)函数设置移动后的task的相关属性值,从而达到移动的目的 + * 最后还是通过postRequest进行更新后的发送 + */ public void moveTask(Task task, TaskList preParent, TaskList curParent) throws NetworkFailureException { commitUpdate(); @@ -463,15 +535,17 @@ public class GTaskClient { if (preParent == curParent && task.getPriorSibling() != null) { // put prioring_sibing_id only if moving within the tasklist and // it is not the first one + //设置优先级ID,只有当移动是发生在文件中 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()); + 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); + //最后将ACTION_LIST加入到jsPost中 jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // client_version @@ -486,6 +560,11 @@ public class GTaskClient { } } + /* + * 删除操作节点 + * 还是利用JSON + * 删除过后使用postRequest发送删除后的结果 + */ public void deleteNode(Node node) throws NetworkFailureException { commitUpdate(); try { @@ -494,7 +573,7 @@ public class GTaskClient { // action_list node.setDeleted(true); - actionList.put(node.getUpdateAction(getActionId())); + actionList.put(node.getUpdateAction(getActionId())); //这里会获取到删除操作的ID,加入到actionLiast中 jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // client_version @@ -509,6 +588,11 @@ public class GTaskClient { } } + /* + * 获取任务列表 + * 首先通过GetURI使用getResponseContent从网上获取数据 + * 然后筛选出"_setup("到)}的部分,并且从中获取GTASK_JSON_LISTS的内容返回 + */ public JSONArray getTaskLists() throws NetworkFailureException { if (!mLoggedin) { Log.e(TAG, "please login first"); @@ -521,6 +605,7 @@ public class GTaskClient { response = mHttpClient.execute(httpGet); // get the task list + //筛选工作,把筛选出的字符串放入jsString String resString = getResponseContent(response.getEntity()); String jsBegin = "_setup("; String jsEnd = ")}"; @@ -531,6 +616,7 @@ public class GTaskClient { jsString = resString.substring(begin + jsBegin.length(), end); } JSONObject js = new JSONObject(jsString); + //获取GTASK_JSON_LISTS return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); } catch (ClientProtocolException e) { Log.e(TAG, e.toString()); @@ -547,6 +633,9 @@ public class GTaskClient { } } + /* + * 通过传入的TASKList的gid,从网络上获取相应属于这个任务列表的任务 + */ public JSONArray getTaskList(String listGid) throws NetworkFailureException { commitUpdate(); try { @@ -558,7 +647,7 @@ public class GTaskClient { action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); - action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); + action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); //这里设置为传入的listGid action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); actionList.put(action); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); @@ -579,6 +668,7 @@ public class GTaskClient { return mAccount; } + //重置更新的内容 public void resetUpdateArray() { mUpdateArray = null; }