();
}
+ // 检查缓存中是否已存在该号码对应的联系人
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
+ // 构造查询条件,将电话号码转换为标准格式
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
+ // 查询联系人数据库
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
- new String [] { Phone.DISPLAY_NAME },
+ new String [] { Phone.DISPLAY_NAME }, // 只查询联系人显示名称
selection,
new String[] { phoneNumber },
null);
if (cursor != null && cursor.moveToFirst()) {
try {
+ // 获取联系人姓名
String name = cursor.getString(0);
+ // 将结果存入缓存
sContactCache.put(phoneNumber, name);
return name;
} catch (IndexOutOfBoundsException e) {
+ // 处理游标越界异常
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
+ // 确保关闭游标
cursor.close();
}
} else {
+ // 未找到匹配的联系人
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/data/Notes.java b/src/Notes-master/app/src/main/java/net/micode/notes/data/Notes.java
index f240604..6e56c51 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/data/Notes.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/data/Notes.java
@@ -17,24 +17,32 @@
package net.micode.notes.data;
import android.net.Uri;
+
+/**
+ * 笔记数据模型类,定义了笔记相关的常量和数据结构
+ */
public class Notes {
+ // 内容提供者的授权字符串
public static final String AUTHORITY = "micode_notes";
+ // 日志标签
public static final String TAG = "Notes";
- public static final int TYPE_NOTE = 0;
- public static final int TYPE_FOLDER = 1;
- public static final int TYPE_SYSTEM = 2;
+ // 笔记类型常量
+ public static final int TYPE_NOTE = 0; // 普通笔记
+ public static final int TYPE_FOLDER = 1; // 文件夹
+ public static final int TYPE_SYSTEM = 2; // 系统文件夹
/**
- * Following IDs are system folders' identifiers
- * {@link Notes#ID_ROOT_FOLDER } is default folder
- * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
- * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
+ * 系统文件夹的ID定义:
+ * {@link Notes#ID_ROOT_FOLDER } 是默认文件夹
+ * {@link Notes#ID_TEMPARAY_FOLDER } 用于不属于任何文件夹的笔记
+ * {@link Notes#ID_CALL_RECORD_FOLDER} 用于存储通话记录
*/
public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
+ // Intent传递数据时使用的Extra键名
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
@@ -42,209 +50,214 @@ public class Notes {
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
- public static final int TYPE_WIDGET_INVALIDE = -1;
- public static final int TYPE_WIDGET_2X = 0;
- public static final int TYPE_WIDGET_4X = 1;
+ // Widget类型常量
+ public static final int TYPE_WIDGET_INVALIDE = -1; // 无效widget
+ public static final int TYPE_WIDGET_2X = 0; // 2x大小widget
+ public static final int TYPE_WIDGET_4X = 1; // 4x大小widget
+ /**
+ * 数据类型常量类
+ */
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/**
- * Uri to query all notes and folders
+ * 用于查询所有笔记和文件夹的Uri
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
- * Uri to query data
+ * 用于查询数据的Uri
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
+ /**
+ * 笔记数据库表列名接口
+ */
public interface NoteColumns {
/**
- * The unique ID for a row
- * Type: INTEGER (long)
+ * 行的唯一ID
+ * 类型: INTEGER (long)
*/
public static final String ID = "_id";
/**
- * The parent's id for note or folder
- * Type: INTEGER (long)
+ * 笔记或文件夹的父ID
+ * 类型: INTEGER (long)
*/
public static final String PARENT_ID = "parent_id";
/**
- * Created data for note or folder
- * Type: INTEGER (long)
+ * 创建日期
+ * 类型: INTEGER (long)
*/
public static final String CREATED_DATE = "created_date";
/**
- * Latest modified date
- * Type: INTEGER (long)
+ * 最后修改日期
+ * 类型: INTEGER (long)
*/
public static final String MODIFIED_DATE = "modified_date";
-
/**
- * Alert date
- * Type: INTEGER (long)
+ * 提醒日期
+ * 类型: INTEGER (long)
*/
public static final String ALERTED_DATE = "alert_date";
/**
- * Folder's name or text content of note
- * Type: TEXT
+ * 文件夹名称或笔记文本内容
+ * 类型: TEXT
*/
public static final String SNIPPET = "snippet";
/**
- * Note's widget id
- * Type: INTEGER (long)
+ * 笔记的widget ID
+ * 类型: INTEGER (long)
*/
public static final String WIDGET_ID = "widget_id";
/**
- * Note's widget type
- * Type: INTEGER (long)
+ * 笔记的widget类型
+ * 类型: INTEGER (long)
*/
public static final String WIDGET_TYPE = "widget_type";
/**
- * Note's background color's id
- * Type: INTEGER (long)
+ * 笔记的背景颜色ID
+ * 类型: INTEGER (long)
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
- * For text note, it doesn't has attachment, for multi-media
- * note, it has at least one attachment
- * Type: INTEGER
+ * 是否包含附件标志
+ * 类型: INTEGER
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
- * Folder's count of notes
- * Type: INTEGER (long)
+ * 文件夹中的笔记数量
+ * 类型: INTEGER (long)
*/
public static final String NOTES_COUNT = "notes_count";
/**
- * The file type: folder or note
- * Type: INTEGER
+ * 文件类型:文件夹或笔记
+ * 类型: INTEGER
*/
public static final String TYPE = "type";
/**
- * The last sync id
- * Type: INTEGER (long)
+ * 最后同步ID
+ * 类型: INTEGER (long)
*/
public static final String SYNC_ID = "sync_id";
/**
- * Sign to indicate local modified or not
- * Type: INTEGER
+ * 本地修改标志
+ * 类型: INTEGER
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
- * Original parent id before moving into temporary folder
- * Type : INTEGER
+ * 移入临时文件夹前的原始父ID
+ * 类型: INTEGER
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
- * The gtask id
- * Type : TEXT
+ * Google任务ID
+ * 类型: TEXT
*/
public static final String GTASK_ID = "gtask_id";
/**
- * The version code
- * Type : INTEGER (long)
+ * 版本号
+ * 类型: INTEGER (long)
*/
public static final String VERSION = "version";
}
+ /**
+ * 数据表列名接口
+ */
public interface DataColumns {
/**
- * The unique ID for a row
- * Type: INTEGER (long)
+ * 行的唯一ID
+ * 类型: INTEGER (long)
*/
public static final String ID = "_id";
/**
- * The MIME type of the item represented by this row.
- * Type: Text
+ * 该行表示项的MIME类型
+ * 类型: Text
*/
public static final String MIME_TYPE = "mime_type";
/**
- * The reference id to note that this data belongs to
- * Type: INTEGER (long)
+ * 该数据所属笔记的引用ID
+ * 类型: INTEGER (long)
*/
public static final String NOTE_ID = "note_id";
/**
- * Created data for note or folder
- * Type: INTEGER (long)
+ * 创建日期
+ * 类型: INTEGER (long)
*/
public static final String CREATED_DATE = "created_date";
/**
- * Latest modified date
- * Type: INTEGER (long)
+ * 最后修改日期
+ * 类型: INTEGER (long)
*/
public static final String MODIFIED_DATE = "modified_date";
/**
- * Data's content
- * Type: TEXT
+ * 数据内容
+ * 类型: TEXT
*/
public static final String CONTENT = "content";
-
/**
- * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
- * integer data type
- * Type: INTEGER
+ * 通用数据列,具体含义由MIME类型决定
+ * 类型: INTEGER
*/
public static final String DATA1 = "data1";
/**
- * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
- * integer data type
- * Type: INTEGER
+ * 通用数据列,具体含义由MIME类型决定
+ * 类型: INTEGER
*/
public static final String DATA2 = "data2";
/**
- * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
- * TEXT data type
- * Type: TEXT
+ * 通用数据列,具体含义由MIME类型决定
+ * 类型: TEXT
*/
public static final String DATA3 = "data3";
/**
- * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
- * TEXT data type
- * Type: TEXT
+ * 通用数据列,具体含义由MIME类型决定
+ * 类型: TEXT
*/
public static final String DATA4 = "data4";
/**
- * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
- * TEXT data type
- * Type: TEXT
+ * 通用数据列,具体含义由MIME类型决定
+ * 类型: TEXT
*/
public static final String DATA5 = "data5";
}
+ /**
+ * 文本笔记相关常量类
+ */
public static final class TextNote implements DataColumns {
/**
- * Mode to indicate the text in check list mode or not
- * Type: Integer 1:check list mode 0: normal mode
+ * 文本模式标志
+ * 类型: Integer 1:清单模式 0:普通模式
*/
public static final String MODE = DATA1;
@@ -257,16 +270,19 @@ public class Notes {
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
+ /**
+ * 通话记录笔记相关常量类
+ */
public static final class CallNote implements DataColumns {
/**
- * Call date for this record
- * Type: INTEGER (long)
+ * 通话日期
+ * 类型: INTEGER (long)
*/
public static final String CALL_DATE = DATA1;
/**
- * Phone number for this record
- * Type: TEXT
+ * 电话号码
+ * 类型: TEXT
*/
public static final String PHONE_NUMBER = DATA3;
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java b/src/Notes-master/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java
index ffe5d57..68cd38f 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java
@@ -26,22 +26,33 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
-
+/**
+ * 笔记数据库帮助类,用于管理笔记数据库的创建和升级
+ */
public class NotesDatabaseHelper extends SQLiteOpenHelper {
+ // 数据库名称
private static final String DB_NAME = "note.db";
+ // 数据库版本号
private static final int DB_VERSION = 4;
+ /**
+ * 数据库表名常量接口
+ */
public interface TABLE {
- public static final String NOTE = "note";
-
- public static final String DATA = "data";
+ public static final String NOTE = "note"; // 笔记表
+ public static final String DATA = "data"; // 数据表
}
private static final String TAG = "NotesDatabaseHelper";
+ // 单例模式实例
private static NotesDatabaseHelper mInstance;
+ /**
+ * 创建笔记表的SQL语句
+ * 包含笔记的基本信息:ID、父ID、提醒时间、背景色、创建时间等
+ */
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
@@ -63,6 +74,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")";
+ /**
+ * 创建数据表的SQL语句
+ * 存储笔记的具体内容数据
+ */
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
@@ -78,12 +93,15 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";
+ /**
+ * 创建数据表NOTE_ID索引的SQL语句
+ */
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/**
- * Increase folder's note count when move note to the folder
+ * 当笔记移动到文件夹时增加文件夹笔记计数的触发器
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+
@@ -95,7 +113,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
- * Decrease folder's note count when move note from folder
+ * 当笔记从文件夹移出时减少文件夹笔记计数的触发器
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " +
@@ -108,7 +126,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
- * Increase folder's note count when insert new note to the folder
+ * 当向文件夹插入新笔记时增加文件夹笔记计数的触发器
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " +
@@ -120,7 +138,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
- * Decrease folder's note count when delete note from the folder
+ * 当从文件夹删除笔记时减少文件夹笔记计数的触发器
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +
@@ -133,7 +151,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
- * Update note's content when insert data with type {@link DataConstants#NOTE}
+ * 当插入NOTE类型的数据时更新笔记内容的触发器
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
@@ -146,7 +164,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
- * Update note's content when data with {@link DataConstants#NOTE} type has changed
+ * 当NOTE类型的数据更新时更新笔记内容的触发器
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
@@ -159,7 +177,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
- * Update note's content when data with {@link DataConstants#NOTE} type has deleted
+ * 当NOTE类型的数据删除时更新笔记内容的触发器
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
@@ -172,7 +190,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
- * Delete datas belong to note which has been deleted
+ * 当笔记被删除时删除相关数据的触发器
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
@@ -183,7 +201,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
- * Delete notes belong to folder which has been deleted
+ * 当文件夹被删除时删除其下所有笔记的触发器
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
@@ -194,7 +212,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
- * Move notes belong to folder which has been moved to trash folder
+ * 当文件夹被移到回收站时移动其下所有笔记的触发器
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " +
@@ -206,10 +224,18 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
+ /**
+ * 构造函数
+ * @param context 上下文对象
+ */
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
+ /**
+ * 创建笔记表
+ * @param db 数据库对象
+ */
public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db);
@@ -217,6 +243,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "note table has been created");
}
+ /**
+ * 重新创建笔记表的所有触发器
+ * @param db 数据库对象
+ */
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
@@ -235,18 +265,22 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
+ /**
+ * 创建系统文件夹
+ * @param db 数据库对象
+ */
private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues();
/**
- * call record foler for call notes
+ * 创建通话记录文件夹
*/
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
- * root folder which is default folder
+ * 创建根文件夹(默认文件夹)
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
@@ -254,7 +288,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
/**
- * temporary folder which is used for moving note
+ * 创建临时文件夹(用于移动笔记)
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
@@ -262,7 +296,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
/**
- * create trash folder
+ * 创建回收站文件夹
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
@@ -270,6 +304,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
}
+ /**
+ * 创建数据表
+ * @param db 数据库对象
+ */
public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db);
@@ -277,6 +315,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "data table has been created");
}
+ /**
+ * 重新创建数据表的所有触发器
+ * @param db 数据库对象
+ */
private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
@@ -287,6 +329,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
+ /**
+ * 获取NotesDatabaseHelper的单例
+ * @param context 上下文对象
+ * @return NotesDatabaseHelper实例
+ */
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
@@ -294,12 +341,22 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance;
}
+ /**
+ * 数据库创建回调
+ * @param db 数据库对象
+ */
@Override
public void onCreate(SQLiteDatabase db) {
createNoteTable(db);
createDataTable(db);
}
+ /**
+ * 数据库升级回调
+ * @param db 数据库对象
+ * @param oldVersion 旧版本号
+ * @param newVersion 新版本号
+ */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
@@ -307,7 +364,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
if (oldVersion == 1) {
upgradeToV2(db);
- skipV2 = true; // this upgrade including the upgrade from v2 to v3
+ skipV2 = true; // 此升级包含从v2到v3的升级
oldVersion++;
}
@@ -333,6 +390,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
}
}
+ /**
+ * 升级到版本2
+ * @param db 数据库对象
+ */
private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
@@ -340,21 +401,29 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
createDataTable(db);
}
+ /**
+ * 升级到版本3
+ * @param db 数据库对象
+ */
private void upgradeToV3(SQLiteDatabase db) {
- // drop unused triggers
+ // 删除未使用的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
- // add a column for gtask id
+ // 添加gtask_id列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
- // add a trash system folder
+ // 添加回收站系统文件夹
ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
+ /**
+ * 升级到版本4
+ * @param db 数据库对象
+ */
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/data/NotesProvider.java b/src/Notes-master/app/src/main/java/net/micode/notes/data/NotesProvider.java
index edb0a60..8aae48c 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/data/NotesProvider.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/data/NotesProvider.java
@@ -34,24 +34,32 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
-
+/**
+ * 笔记内容提供者类,用于管理笔记数据的访问
+ */
public class NotesProvider extends ContentProvider {
+ // URI匹配器
private static final UriMatcher mMatcher;
+ // 数据库帮助类实例
private NotesDatabaseHelper mHelper;
+ // 日志标签
private static final String TAG = "NotesProvider";
- private static final int URI_NOTE = 1;
- private static final int URI_NOTE_ITEM = 2;
- private static final int URI_DATA = 3;
- private static final int URI_DATA_ITEM = 4;
-
- private static final int URI_SEARCH = 5;
- private static final int URI_SEARCH_SUGGEST = 6;
+ // URI匹配类型常量
+ private static final int URI_NOTE = 1; // 笔记URI
+ private static final int URI_NOTE_ITEM = 2; // 单条笔记URI
+ private static final int URI_DATA = 3; // 数据URI
+ private static final int URI_DATA_ITEM = 4; // 单条数据URI
+ private static final int URI_SEARCH = 5; // 搜索URI
+ private static final int URI_SEARCH_SUGGEST = 6; // 搜索建议URI
+ // 静态初始化URI匹配规则
static {
+ // 创建URI匹配器实例
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
+ // 添加各种URI匹配规则
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
@@ -62,8 +70,9 @@ public class NotesProvider extends ContentProvider {
}
/**
- * x'0A' represents the '\n' character in sqlite. For title and content in the search result,
- * we will trim '\n' and white space in order to show more information.
+ * 搜索结果的投影列
+ * x'0A'表示sqlite中的换行符'\n'
+ * 为了在搜索结果中显示更多信息,我们会去除标题和内容中的换行符和空格
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
@@ -73,50 +82,69 @@ public class NotesProvider extends ContentProvider {
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
+ /**
+ * 笔记搜索的SQL查询语句
+ */
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
+ /**
+ * 内容提供者创建时的回调方法
+ */
@Override
public boolean onCreate() {
+ // 初始化数据库帮助类
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
+ /**
+ * 查询数据的方法
+ */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
+ // 初始化游标
Cursor c = null;
+ // 获取可读数据库实例
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
+ // 根据URI类型执行不同的查询操作
switch (mMatcher.match(uri)) {
case URI_NOTE:
+ // 查询所有笔记
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
+ // 查询单条笔记
id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
+ // 查询所有数据
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM:
+ // 查询单条数据
id = uri.getPathSegments().get(1);
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_SEARCH:
case URI_SEARCH_SUGGEST:
+ // 检查查询参数
if (sortOrder != null || projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
+ // 获取搜索字符串
String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
@@ -126,11 +154,13 @@ public class NotesProvider extends ContentProvider {
searchString = uri.getQueryParameter("pattern");
}
+ // 如果搜索字符串为空则返回null
if (TextUtils.isEmpty(searchString)) {
return null;
}
try {
+ // 格式化搜索字符串并执行查询
searchString = String.format("%%%s%%", searchString);
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
@@ -141,38 +171,56 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
+ // 设置通知URI
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
+ /**
+ * 插入数据的方法
+ */
+ /**
+ * 插入数据到数据库中
+ * @param uri 要插入数据的URI
+ * @param values 要插入的数据
+ * @return 插入数据后生成的URI
+ */
@Override
public Uri insert(Uri uri, ContentValues values) {
+ // 获取可写数据库实例
SQLiteDatabase db = mHelper.getWritableDatabase();
+ // 初始化数据ID、笔记ID和插入ID
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
case URI_NOTE:
+ // 插入笔记数据
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
case URI_DATA:
+ // 插入笔记内容数据
if (values.containsKey(DataColumns.NOTE_ID)) {
+ // 从values中获取笔记ID
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
+ // 记录错误日志:缺少笔记ID
Log.d(TAG, "Wrong data format without note id:" + values.toString());
}
+ // 插入数据并获取插入ID
insertedId = dataId = db.insert(TABLE.DATA, null, values);
break;
default:
+ // 未知URI异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
- // Notify the note uri
+ // 通知笔记URI发生变化
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
- // Notify the data uri
+ // 通知数据URI发生变化
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
@@ -181,22 +229,29 @@ public class NotesProvider extends ContentProvider {
return ContentUris.withAppendedId(uri, insertedId);
}
+ /**
+ * 删除数据的方法
+ */
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
+ // 初始化删除计数
int count = 0;
String id = null;
+ // 获取可写数据库实例
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
+ // 根据URI类型执行不同的删除操作
switch (mMatcher.match(uri)) {
case URI_NOTE:
+ // 删除笔记,确保只删除ID大于0的笔记
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
+ // 删除单条笔记
id = uri.getPathSegments().get(1);
/**
- * ID that smaller than 0 is system folder which is not allowed to
- * trash
+ * ID小于0的是系统文件夹,不允许删除
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
@@ -206,10 +261,12 @@ public class NotesProvider extends ContentProvider {
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
+ // 删除所有数据
count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true;
break;
case URI_DATA_ITEM:
+ // 删除单条数据
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
@@ -218,6 +275,7 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
+ // 如果有数据被删除,发送通知
if (count > 0) {
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
@@ -227,28 +285,38 @@ public class NotesProvider extends ContentProvider {
return count;
}
+ /**
+ * 更新数据的方法
+ */
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+ // 初始化更新计数
int count = 0;
String id = null;
+ // 获取可写数据库实例
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false;
+ // 根据URI类型执行不同的更新操作
switch (mMatcher.match(uri)) {
case URI_NOTE:
+ // 更新笔记
increaseNoteVersion(-1, selection, selectionArgs);
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
+ // 更新单条笔记
id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
break;
case URI_DATA:
+ // 更新所有数据
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
break;
case URI_DATA_ITEM:
+ // 更新单条数据
id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
@@ -258,6 +326,7 @@ public class NotesProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI " + uri);
}
+ // 如果有数据被更新,发送通知
if (count > 0) {
if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
@@ -267,11 +336,18 @@ public class NotesProvider extends ContentProvider {
return count;
}
+ /**
+ * 解析选择条件的辅助方法
+ */
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
+ /**
+ * 增加笔记版本号的方法
+ */
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
+ // 构建SQL更新语句
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(TABLE.NOTE);
@@ -279,6 +355,7 @@ public class NotesProvider extends ContentProvider {
sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
+ // 添加WHERE子句
if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE ");
}
@@ -293,9 +370,13 @@ public class NotesProvider extends ContentProvider {
sql.append(selectString);
}
+ // 执行SQL语句
mHelper.getWritableDatabase().execSQL(sql.toString());
}
+ /**
+ * 获取MIME类型的方法
+ */
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/MetaData.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/MetaData.java
index 3a2050b..c0b2878 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/MetaData.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/MetaData.java
@@ -24,12 +24,22 @@ import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
-
+/**
+ * 元数据类,继承自Task类
+ * 用于处理与Google Task相关的元数据
+ */
public class MetaData extends Task {
+ // 日志标签
private final static String TAG = MetaData.class.getSimpleName();
+ // 关联的Google Task ID
private String mRelatedGid = null;
+ /**
+ * 设置元数据信息
+ * @param gid Google Task ID
+ * @param metaInfo 元数据JSON对象
+ */
public void setMeta(String gid, JSONObject metaInfo) {
try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
@@ -40,15 +50,27 @@ public class MetaData extends Task {
setName(GTaskStringUtils.META_NOTE_NAME);
}
+ /**
+ * 获取关联的Google Task ID
+ * @return 关联的Google Task ID
+ */
public String getRelatedGid() {
return mRelatedGid;
}
+ /**
+ * 判断是否值得保存
+ * @return 如果notes不为空则返回true
+ */
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
+ /**
+ * 通过远程JSON设置内容
+ * @param js 远程JSON对象
+ */
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
@@ -63,17 +85,31 @@ public class MetaData extends Task {
}
}
+ /**
+ * 通过本地JSON设置内容(不支持的操作)
+ * @param js 本地JSON对象
+ * @throws IllegalAccessError 该方法不应被调用
+ */
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
+ /**
+ * 从内容获取本地JSON(不支持的操作)
+ * @throws IllegalAccessError 该方法不应被调用
+ */
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
+ /**
+ * 获取同步操作(不支持的操作)
+ * @param c 数据库游标
+ * @throws IllegalAccessError 该方法不应被调用
+ */
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/Node.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/Node.java
index 63950e0..386aa3c 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/Node.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/Node.java
@@ -20,33 +20,41 @@ import android.database.Cursor;
import org.json.JSONObject;
+/**
+ * 节点抽象类,用于表示Google Task中的节点数据
+ */
public abstract class Node {
- public static final int SYNC_ACTION_NONE = 0;
+ // 同步动作常量定义
+ public static final int SYNC_ACTION_NONE = 0; // 无需同步
- public static final int SYNC_ACTION_ADD_REMOTE = 1;
+ public static final int SYNC_ACTION_ADD_REMOTE = 1; // 添加到远程
- public static final int SYNC_ACTION_ADD_LOCAL = 2;
+ public static final int SYNC_ACTION_ADD_LOCAL = 2; // 添加到本地
- public static final int SYNC_ACTION_DEL_REMOTE = 3;
+ public static final int SYNC_ACTION_DEL_REMOTE = 3; // 从远程删除
- public static final int SYNC_ACTION_DEL_LOCAL = 4;
+ public static final int SYNC_ACTION_DEL_LOCAL = 4; // 从本地删除
- public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
+ public static final int SYNC_ACTION_UPDATE_REMOTE = 5; // 更新远程
- public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
+ public static final int SYNC_ACTION_UPDATE_LOCAL = 6; // 更新本地
- public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
+ public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; // 更新冲突
- public static final int SYNC_ACTION_ERROR = 8;
+ public static final int SYNC_ACTION_ERROR = 8; // 同步错误
- private String mGid;
+ // 节点基本属性
+ private String mGid; // Google Task ID
- private String mName;
+ private String mName; // 节点名称
- private long mLastModified;
+ private long mLastModified; // 最后修改时间
- private boolean mDeleted;
+ private boolean mDeleted; // 删除标记
+ /**
+ * 构造函数,初始化节点基本属性
+ */
public Node() {
mGid = null;
mName = "";
@@ -54,46 +62,105 @@ public abstract class Node {
mDeleted = false;
}
+ /**
+ * 获取创建动作的JSON对象
+ * @param actionId 动作ID
+ * @return 创建动作的JSON对象
+ */
public abstract JSONObject getCreateAction(int actionId);
+ /**
+ * 获取更新动作的JSON对象
+ * @param actionId 动作ID
+ * @return 更新动作的JSON对象
+ */
public abstract JSONObject getUpdateAction(int actionId);
+ /**
+ * 通过远程JSON设置内容
+ * @param js 远程JSON对象
+ */
public abstract void setContentByRemoteJSON(JSONObject js);
+ /**
+ * 通过本地JSON设置内容
+ * @param js 本地JSON对象
+ */
public abstract void setContentByLocalJSON(JSONObject js);
+ /**
+ * 从内容获取本地JSON
+ * @return 本地JSON对象
+ */
public abstract JSONObject getLocalJSONFromContent();
+ /**
+ * 获取同步动作
+ * @param c 数据库游标
+ * @return 同步动作类型
+ */
public abstract int getSyncAction(Cursor c);
+ /**
+ * 设置Google Task ID
+ * @param gid Google Task ID
+ */
public void setGid(String gid) {
this.mGid = gid;
}
+ /**
+ * 设置节点名称
+ * @param name 节点名称
+ */
public void setName(String name) {
this.mName = name;
}
+ /**
+ * 设置最后修改时间
+ * @param lastModified 最后修改时间
+ */
public void setLastModified(long lastModified) {
this.mLastModified = lastModified;
}
+ /**
+ * 设置删除标记
+ * @param deleted 删除标记
+ */
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}
+ /**
+ * 获取Google Task ID
+ * @return Google Task ID
+ */
public String getGid() {
return this.mGid;
}
+ /**
+ * 获取节点名称
+ * @return 节点名称
+ */
public String getName() {
return this.mName;
}
+ /**
+ * 获取最后修改时间
+ * @return 最后修改时间
+ */
public long getLastModified() {
return this.mLastModified;
}
+ /**
+ * 获取删除标记
+ * @return 删除标记
+ */
public boolean getDeleted() {
return this.mDeleted;
}
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/SqlData.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/SqlData.java
index d3ec3be..a272bb1 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/SqlData.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/SqlData.java
@@ -36,154 +36,154 @@ import org.json.JSONObject;
public class SqlData {
- private static final String TAG = SqlData.class.getSimpleName();
+ private static final String TAG = SqlData.class.getSimpleName(); // 日志标签
- private static final int INVALID_ID = -99999;
+ private static final int INVALID_ID = -99999; // 无效ID常量
public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
- };
+ }; // 数据列投影
- public static final int DATA_ID_COLUMN = 0;
+ public static final int DATA_ID_COLUMN = 0; // 数据ID列索引
- public static final int DATA_MIME_TYPE_COLUMN = 1;
+ public static final int DATA_MIME_TYPE_COLUMN = 1; // 数据MIME类型列索引
- public static final int DATA_CONTENT_COLUMN = 2;
+ public static final int DATA_CONTENT_COLUMN = 2; // 数据内容列索引
- public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
+ public static final int DATA_CONTENT_DATA_1_COLUMN = 3; // 数据内容数据1列索引
- public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
+ public static final int DATA_CONTENT_DATA_3_COLUMN = 4; // 数据内容数据3列索引
- private ContentResolver mContentResolver;
+ private ContentResolver mContentResolver; // 内容解析器
- private boolean mIsCreate;
+ private boolean mIsCreate; // 是否为创建标志
- private long mDataId;
+ private long mDataId; // 数据ID
- private String mDataMimeType;
+ private String mDataMimeType; // 数据MIME类型
- private String mDataContent;
+ private String mDataContent; // 数据内容
- private long mDataContentData1;
+ private long mDataContentData1; // 数据内容数据1
- private String mDataContentData3;
+ private String mDataContentData3; // 数据内容数据3
- private ContentValues mDiffDataValues;
+ private ContentValues mDiffDataValues; // 差异数据值
public SqlData(Context context) {
- mContentResolver = context.getContentResolver();
- mIsCreate = true;
- mDataId = INVALID_ID;
- mDataMimeType = DataConstants.NOTE;
- mDataContent = "";
- mDataContentData1 = 0;
- mDataContentData3 = "";
- mDiffDataValues = new ContentValues();
+ mContentResolver = context.getContentResolver(); // 获取内容解析器
+ mIsCreate = true; // 设置为创建标志
+ mDataId = INVALID_ID; // 初始化数据ID
+ mDataMimeType = DataConstants.NOTE; // 初始化数据MIME类型
+ mDataContent = ""; // 初始化数据内容
+ mDataContentData1 = 0; // 初始化数据内容数据1
+ mDataContentData3 = ""; // 初始化数据内容数据3
+ mDiffDataValues = new ContentValues(); // 初始化差异数据值
}
public SqlData(Context context, Cursor c) {
- mContentResolver = context.getContentResolver();
- mIsCreate = false;
- loadFromCursor(c);
- mDiffDataValues = new ContentValues();
+ mContentResolver = context.getContentResolver(); // 获取内容解析器
+ mIsCreate = false; // 设置为非创建标志
+ loadFromCursor(c); // 从游标加载数据
+ mDiffDataValues = new ContentValues(); // 初始化差异数据值
}
private void loadFromCursor(Cursor c) {
- mDataId = c.getLong(DATA_ID_COLUMN);
- mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
- mDataContent = c.getString(DATA_CONTENT_COLUMN);
- mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
- mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
+ mDataId = c.getLong(DATA_ID_COLUMN); // 从游标获取数据ID
+ mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); // 从游标获取数据MIME类型
+ mDataContent = c.getString(DATA_CONTENT_COLUMN); // 从游标获取数据内容
+ mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); // 从游标获取数据内容数据1
+ mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); // 从游标获取数据内容数据3
}
public void setContent(JSONObject js) throws JSONException {
- long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
+ long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; // 获取JSON中的数据ID
if (mIsCreate || mDataId != dataId) {
- mDiffDataValues.put(DataColumns.ID, dataId);
+ mDiffDataValues.put(DataColumns.ID, dataId); // 更新差异数据值中的数据ID
}
- mDataId = dataId;
+ mDataId = dataId; // 更新数据ID
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
- : DataConstants.NOTE;
+ : DataConstants.NOTE; // 获取JSON中的数据MIME类型
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
- mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType);
+ mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); // 更新差异数据值中的数据MIME类型
}
- mDataMimeType = dataMimeType;
+ mDataMimeType = dataMimeType; // 更新数据MIME类型
- String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
+ String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; // 获取JSON中的数据内容
if (mIsCreate || !mDataContent.equals(dataContent)) {
- mDiffDataValues.put(DataColumns.CONTENT, dataContent);
+ mDiffDataValues.put(DataColumns.CONTENT, dataContent); // 更新差异数据值中的数据内容
}
- mDataContent = dataContent;
+ mDataContent = dataContent; // 更新数据内容
- long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
+ long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; // 获取JSON中的数据内容数据1
if (mIsCreate || mDataContentData1 != dataContentData1) {
- mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
+ mDiffDataValues.put(DataColumns.DATA1, dataContentData1); // 更新差异数据值中的数据内容数据1
}
- mDataContentData1 = dataContentData1;
+ mDataContentData1 = dataContentData1; // 更新数据内容数据1
- String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
+ String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; // 获取JSON中的数据内容数据3
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
- mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
+ mDiffDataValues.put(DataColumns.DATA3, dataContentData3); // 更新差异数据值中的数据内容数据3
}
- mDataContentData3 = dataContentData3;
+ mDataContentData3 = dataContentData3; // 更新数据内容数据3
}
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
- Log.e(TAG, "it seems that we haven't created this in database yet");
+ Log.e(TAG, "it seems that we haven't created this in database yet"); // 日志记录错误信息
return null;
}
- JSONObject js = new JSONObject();
- js.put(DataColumns.ID, mDataId);
- js.put(DataColumns.MIME_TYPE, mDataMimeType);
- js.put(DataColumns.CONTENT, mDataContent);
- js.put(DataColumns.DATA1, mDataContentData1);
- js.put(DataColumns.DATA3, mDataContentData3);
- return js;
+ JSONObject js = new JSONObject(); // 创建JSON对象
+ js.put(DataColumns.ID, mDataId); // 将数据ID放入JSON对象
+ js.put(DataColumns.MIME_TYPE, mDataMimeType); // 将数据MIME类型放入JSON对象
+ js.put(DataColumns.CONTENT, mDataContent); // 将数据内容放入JSON对象
+ js.put(DataColumns.DATA1, mDataContentData1); // 将数据内容数据1放入JSON对象
+ js.put(DataColumns.DATA3, mDataContentData3); // 将数据内容数据3放入JSON对象
+ return js; // 返回JSON对象
}
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
- mDiffDataValues.remove(DataColumns.ID);
+ mDiffDataValues.remove(DataColumns.ID); // 移除差异数据值中的数据ID
}
- mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
- Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
+ mDiffDataValues.put(DataColumns.NOTE_ID, noteId); // 将笔记ID放入差异数据值
+ Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); // 插入数据
try {
- mDataId = Long.valueOf(uri.getPathSegments().get(1));
+ mDataId = Long.valueOf(uri.getPathSegments().get(1)); // 获取插入数据的ID
} catch (NumberFormatException e) {
- Log.e(TAG, "Get note id error :" + e.toString());
- throw new ActionFailureException("create note failed");
+ Log.e(TAG, "Get note id error :" + e.toString()); // 日志记录错误信息
+ throw new ActionFailureException("create note failed"); // 抛出操作失败异常
}
} else {
if (mDiffDataValues.size() > 0) {
int result = 0;
if (!validateVersion) {
result = mContentResolver.update(ContentUris.withAppendedId(
- Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
+ Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); // 更新数据
} else {
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
String.valueOf(noteId), String.valueOf(version)
- });
+ }); // 更新数据并验证版本
}
if (result == 0) {
- Log.w(TAG, "there is no update. maybe user updates note when syncing");
+ Log.w(TAG, "there is no update. maybe user updates note when syncing"); // 日志记录警告信息
}
}
}
- mDiffDataValues.clear();
- mIsCreate = false;
+ mDiffDataValues.clear(); // 清空差异数据值
+ mIsCreate = false; // 设置为非创建标志
}
public long getId() {
- return mDataId;
+ return mDataId; // 返回数据ID
}
}
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java
index 79a4095..b439eda 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java
@@ -16,6 +16,7 @@
package net.micode.notes.gtask.data;
+// 导入所需的Android系统类
import android.appwidget.AppWidgetManager;
import android.content.ContentResolver;
import android.content.ContentValues;
@@ -24,6 +25,7 @@ import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
+// 导入应用程序相关类
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
@@ -31,19 +33,22 @@ import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import net.micode.notes.tool.ResourceParser;
+// 导入JSON相关类
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
+// 导入Java工具类
import java.util.ArrayList;
public class SqlNote {
- private static final String TAG = SqlNote.class.getSimpleName();
+ private static final String TAG = SqlNote.class.getSimpleName(); // 日志标签
- private static final int INVALID_ID = -99999;
+ private static final int INVALID_ID = -99999; // 无效ID常量
- public static final String[] PROJECTION_NOTE = new String[] {
+ // 笔记表的列名数组,用于数据库查询
+ 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,
NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
@@ -52,76 +57,46 @@ public class SqlNote {
NoteColumns.VERSION
};
- public static final int ID_COLUMN = 0;
-
- public static final int ALERTED_DATE_COLUMN = 1;
-
- public static final int BG_COLOR_ID_COLUMN = 2;
-
- public static final int CREATED_DATE_COLUMN = 3;
-
- public static final int HAS_ATTACHMENT_COLUMN = 4;
-
- public static final int MODIFIED_DATE_COLUMN = 5;
-
- public static final int NOTES_COUNT_COLUMN = 6;
-
- public static final int PARENT_ID_COLUMN = 7;
-
- public static final int SNIPPET_COLUMN = 8;
-
- public static final int TYPE_COLUMN = 9;
-
- public static final int WIDGET_ID_COLUMN = 10;
-
- public static final int WIDGET_TYPE_COLUMN = 11;
-
- public static final int SYNC_ID_COLUMN = 12;
-
- public static final int LOCAL_MODIFIED_COLUMN = 13;
-
- public static final int ORIGIN_PARENT_ID_COLUMN = 14;
-
- public static final int GTASK_ID_COLUMN = 15;
-
- public static final int VERSION_COLUMN = 16;
-
- private Context mContext;
-
- private ContentResolver mContentResolver;
-
- private boolean mIsCreate;
-
- private long mId;
-
- private long mAlertDate;
-
- private int mBgColorId;
-
- private long mCreatedDate;
-
- private int mHasAttachment;
-
- private long mModifiedDate;
-
- private long mParentId;
-
- private String mSnippet;
-
- private int mType;
-
- private int mWidgetId;
-
- private int mWidgetType;
-
- private long mOriginParent;
-
- private long mVersion;
-
- private ContentValues mDiffNoteValues;
-
- private ArrayList mDataList;
-
+ // 定义各列的索引常量
+ public static final int ID_COLUMN = 0; // ID列索引
+ public static final int ALERTED_DATE_COLUMN = 1; // 提醒日期列索引
+ public static final int BG_COLOR_ID_COLUMN = 2; // 背景颜色ID列索引
+ public static final int CREATED_DATE_COLUMN = 3; // 创建日期列索引
+ public static final int HAS_ATTACHMENT_COLUMN = 4; // 是否有附件列索引
+ public static final int MODIFIED_DATE_COLUMN = 5; // 修改日期列索引
+ public static final int NOTES_COUNT_COLUMN = 6; // 笔记数量列索引
+ public static final int PARENT_ID_COLUMN = 7; // 父ID列索引
+ public static final int SNIPPET_COLUMN = 8; // 摘要列索引
+ public static final int TYPE_COLUMN = 9; // 类型列索引
+ public static final int WIDGET_ID_COLUMN = 10; // 小部件ID列索引
+ public static final int WIDGET_TYPE_COLUMN = 11; // 小部件类型列索引
+ public static final int SYNC_ID_COLUMN = 12; // 同步ID列索引
+ public static final int LOCAL_MODIFIED_COLUMN = 13; // 本地修改列索引
+ public static final int ORIGIN_PARENT_ID_COLUMN = 14; // 原始父ID列索引
+ public static final int GTASK_ID_COLUMN = 15; // GTask ID列索引
+ public static final int VERSION_COLUMN = 16; // 版本列索引
+
+ // 类的成员变量
+ private Context mContext; // 上下文对象
+ private ContentResolver mContentResolver; // 内容解析器
+ private boolean mIsCreate; // 是否是新建笔记
+ private long mId; // 笔记ID
+ private long mAlertDate; // 提醒日期
+ private int mBgColorId; // 背景颜色ID
+ private long mCreatedDate; // 创建日期
+ private int mHasAttachment; // 是否有附件
+ private long mModifiedDate; // 修改日期
+ private long mParentId; // 父ID
+ private String mSnippet; // 摘要
+ private int mType; // 类型
+ private int mWidgetId; // 小部件ID
+ private int mWidgetType; // 小部件类型
+ private long mOriginParent; // 原始父ID
+ private long mVersion; // 版本
+ private ContentValues mDiffNoteValues; // 笔记差异值
+ private ArrayList mDataList; // 数据列表
+
+ // 构造函数,创建新笔记
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
@@ -143,6 +118,7 @@ public class SqlNote {
mDataList = new ArrayList();
}
+ // 构造函数,从Cursor加载笔记
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
@@ -154,6 +130,7 @@ public class SqlNote {
mDiffNoteValues = new ContentValues();
}
+ // 构造函数,根据ID加载笔记
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
@@ -166,6 +143,7 @@ public class SqlNote {
}
+ // 根据ID从数据库加载笔记
private void loadFromCursor(long id) {
Cursor c = null;
try {
@@ -185,6 +163,7 @@ public class SqlNote {
}
}
+ // 从Cursor加载笔记数据
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
@@ -200,6 +179,7 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN);
}
+ // 加载笔记内容数据
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
@@ -226,13 +206,14 @@ public class SqlNote {
}
}
+ // 设置笔记内容
public boolean setContent(JSONObject js) {
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
Log.w(TAG, "cannot set system folder");
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
- // for folder we can only update the snnipet and type
+ // 对于文件夹类型,只能更新摘要和类型
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
@@ -247,6 +228,7 @@ public class SqlNote {
}
mType = type;
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
+ // 对于笔记类型,更新所有相关字段
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
if (mIsCreate || mId != id) {
@@ -331,6 +313,7 @@ public class SqlNote {
}
mOriginParent = originParent;
+ // 更新数据内容
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null;
@@ -359,6 +342,7 @@ public class SqlNote {
return true;
}
+ // 获取笔记内容的JSON表示
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
@@ -370,6 +354,7 @@ public class SqlNote {
JSONObject note = new JSONObject();
if (mType == Notes.TYPE_NOTE) {
+ // 对于笔记类型,添加所有字段
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate);
note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
@@ -384,6 +369,7 @@ public class SqlNote {
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
+ // 添加数据内容
JSONArray dataArray = new JSONArray();
for (SqlData sqlData : mDataList) {
JSONObject data = sqlData.getContent();
@@ -393,6 +379,7 @@ public class SqlNote {
}
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
} 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,41 +394,51 @@ public class SqlNote {
return null;
}
+ // 设置父ID
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
}
+ // 设置GTask ID
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
+ // 设置同步ID
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
+ // 重置本地修改标记
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}
+ // 获取笔记ID
public long getId() {
return mId;
}
+ // 获取父ID
public long getParentId() {
return mParentId;
}
+ // 获取摘要
public String getSnippet() {
return mSnippet;
}
+ // 判断是否为笔记类型
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}
+ // 提交笔记更改到数据库
public void commit(boolean validateVersion) {
if (mIsCreate) {
+ // 创建新笔记
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID);
}
@@ -463,6 +460,7 @@ public class SqlNote {
}
}
} else {
+ // 更新现有笔记
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id");
@@ -494,7 +492,7 @@ public class SqlNote {
}
}
- // refresh local info
+ // 刷新本地信息
loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE)
loadDataContent();
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/Task.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/Task.java
index 6a19454..9962e6a 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/Task.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/Task.java
@@ -31,20 +31,30 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
-
+/**
+ * Task类表示一个Google Task任务
+ */
public class Task extends Node {
private static final String TAG = Task.class.getSimpleName();
+ // 任务是否完成
private boolean mCompleted;
+ // 任务备注
private String mNotes;
+ // 任务元信息
private JSONObject mMetaInfo;
+ // 前一个兄弟任务
private Task mPriorSibling;
+ // 父任务列表
private TaskList mParent;
+ /**
+ * 构造函数,初始化Task对象
+ */
public Task() {
super();
mCompleted = false;
@@ -54,6 +64,11 @@ public class Task extends Node {
mMetaInfo = null;
}
+ /**
+ * 获取创建任务的JSON动作对象
+ * @param actionId 动作ID
+ * @return 创建任务的JSON对象
+ */
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@@ -103,6 +118,11 @@ public class Task extends Node {
return js;
}
+ /**
+ * 获取更新任务的JSON动作对象
+ * @param actionId 动作ID
+ * @return 更新任务的JSON对象
+ */
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@@ -135,6 +155,10 @@ public class Task extends Node {
return js;
}
+ /**
+ * 通过远程JSON设置任务内容
+ * @param js 远程JSON对象
+ */
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@@ -175,6 +199,10 @@ public class Task extends Node {
}
}
+ /**
+ * 通过本地JSON设置任务内容
+ * @param js 本地JSON对象
+ */
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
@@ -204,6 +232,10 @@ public class Task extends Node {
}
}
+ /**
+ * 从内容获取本地JSON对象
+ * @return 本地JSON对象
+ */
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
@@ -247,6 +279,10 @@ public class Task extends Node {
}
}
+ /**
+ * 设置任务的元信息
+ * @param metaData 元信息对象
+ */
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
@@ -258,6 +294,11 @@ public class Task extends Node {
}
}
+ /**
+ * 获取同步动作
+ * @param c 数据库游标
+ * @return 同步动作类型
+ */
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
@@ -311,39 +352,75 @@ public class Task extends Node {
return SYNC_ACTION_ERROR;
}
+ /**
+ * 判断任务是否值得保存
+ * @return 如果任务有内容返回true,否则返回false
+ */
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);
}
+ /**
+ * 设置任务完成状态
+ * @param completed 完成状态
+ */
public void setCompleted(boolean completed) {
this.mCompleted = completed;
}
+ /**
+ * 设置任务备注
+ * @param notes 备注内容
+ */
public void setNotes(String notes) {
this.mNotes = notes;
}
+ /**
+ * 设置前一个兄弟任务
+ * @param priorSibling 前一个兄弟任务
+ */
public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling;
}
+ /**
+ * 设置父任务列表
+ * @param parent 父任务列表
+ */
public void setParent(TaskList parent) {
this.mParent = parent;
}
+ /**
+ * 获取任务完成状态
+ * @return 任务完成状态
+ */
public boolean getCompleted() {
return this.mCompleted;
}
+ /**
+ * 获取任务备注
+ * @return 任务备注内容
+ */
public String getNotes() {
return this.mNotes;
}
+ /**
+ * 获取前一个兄弟任务
+ * @return 前一个兄弟任务
+ */
public Task getPriorSibling() {
return this.mPriorSibling;
}
+ /**
+ * 获取父任务列表
+ * @return 父任务列表
+ */
public TaskList getParent() {
return this.mParent;
}
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/TaskList.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/TaskList.java
index 4ea21c5..f774c32 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/TaskList.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/data/TaskList.java
@@ -29,35 +29,48 @@ import org.json.JSONObject;
import java.util.ArrayList;
-
+/**
+ * TaskList类表示一个任务列表,继承自Node类
+ */
public class TaskList extends Node {
+ // 日志标签
private static final String TAG = TaskList.class.getSimpleName();
+ // 任务列表索引
private int mIndex;
+ // 子任务列表
private ArrayList mChildren;
+ /**
+ * 构造函数,初始化TaskList对象
+ */
public TaskList() {
super();
mChildren = new ArrayList();
mIndex = 1;
}
+ /**
+ * 获取创建任务列表的JSON动作对象
+ * @param actionId 动作ID
+ * @return 创建任务列表的JSON对象
+ */
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
try {
- // action_type
+ // 设置动作类型为创建
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
- // action_id
+ // 设置动作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
- // index
+ // 设置索引
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
- // entity_delta
+ // 设置实体数据
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
@@ -74,21 +87,26 @@ public class TaskList extends Node {
return js;
}
+ /**
+ * 获取更新任务列表的JSON动作对象
+ * @param actionId 动作ID
+ * @return 更新任务列表的JSON对象
+ */
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
try {
- // action_type
+ // 设置动作类型为更新
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
- // action_id
+ // 设置动作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
- // id
+ // 设置任务列表ID
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
- // entity_delta
+ // 设置实体数据
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
@@ -103,20 +121,24 @@ public class TaskList extends Node {
return js;
}
+ /**
+ * 根据远程JSON数据设置任务列表内容
+ * @param js 远程JSON数据
+ */
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
- // id
+ // 设置任务列表ID
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
}
- // last_modified
+ // 设置最后修改时间
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
}
- // name
+ // 设置名称
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
}
@@ -129,6 +151,10 @@ public class TaskList extends Node {
}
}
+ /**
+ * 根据本地JSON数据设置任务列表内容
+ * @param js 本地JSON数据
+ */
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
@@ -137,6 +163,7 @@ public class TaskList extends Node {
try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
+ // 根据不同类型设置名称
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
@@ -157,11 +184,16 @@ public class TaskList extends Node {
}
}
+ /**
+ * 从内容生成本地JSON数据
+ * @return 本地JSON对象
+ */
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();
JSONObject folder = new JSONObject();
+ // 处理文件夹名称
String folderName = getName();
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
@@ -183,28 +215,33 @@ public class TaskList extends Node {
}
}
+ /**
+ * 获取同步动作
+ * @param c 数据库游标
+ * @return 同步动作类型
+ */
public int getSyncAction(Cursor c) {
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
- // there is no local update
+ // 本地未修改
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
- // no update both side
+ // 双方都未更新
return SYNC_ACTION_NONE;
} else {
- // apply remote to local
+ // 应用远程更新到本地
return SYNC_ACTION_UPDATE_LOCAL;
}
} else {
- // validate gtask id
+ // 验证gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
- // local modification only
+ // 仅本地修改
return SYNC_ACTION_UPDATE_REMOTE;
} else {
- // for folder conflicts, just apply local modification
+ // 对于文件夹冲突,仅应用本地修改
return SYNC_ACTION_UPDATE_REMOTE;
}
}
@@ -216,16 +253,25 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR;
}
+ /**
+ * 获取子任务数量
+ * @return 子任务数量
+ */
public int getChildTaskCount() {
return mChildren.size();
}
+ /**
+ * 添加子任务
+ * @param task 要添加的任务
+ * @return 是否添加成功
+ */
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task);
if (ret) {
- // need to set prior sibling and parent
+ // 设置前一个兄弟任务和父任务
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1));
task.setParent(this);
@@ -234,6 +280,12 @@ public class TaskList extends Node {
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");
@@ -244,7 +296,7 @@ public class TaskList extends Node {
if (task != null && pos == -1) {
mChildren.add(index, task);
- // update the task list
+ // 更新任务列表
Task preTask = null;
Task afterTask = null;
if (index != 0)
@@ -260,6 +312,11 @@ public class TaskList extends Node {
return true;
}
+ /**
+ * 移除子任务
+ * @param task 要移除的任务
+ * @return 是否移除成功
+ */
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
@@ -267,11 +324,11 @@ public class TaskList extends Node {
ret = mChildren.remove(task);
if (ret) {
- // reset prior sibling and parent
+ // 重置前一个兄弟任务和父任务
task.setPriorSibling(null);
task.setParent(null);
- // update the task list
+ // 更新任务列表
if (index != mChildren.size()) {
mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1));
@@ -281,6 +338,12 @@ public class TaskList extends Node {
return ret;
}
+ /**
+ * 移动子任务到指定位置
+ * @param task 要移动的任务
+ * @param index 目标位置
+ * @return 是否移动成功
+ */
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
@@ -299,6 +362,11 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index));
}
+ /**
+ * 根据GID查找子任务
+ * @param gid 任务GID
+ * @return 找到的任务,未找到返回null
+ */
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@@ -309,10 +377,20 @@ public class TaskList extends Node {
return null;
}
+ /**
+ * 获取子任务的索引
+ * @param task 子任务
+ * @return 任务索引
+ */
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
+ /**
+ * 根据索引获取子任务
+ * @param index 任务索引
+ * @return 子任务对象
+ */
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
@@ -321,6 +399,11 @@ public class TaskList extends Node {
return mChildren.get(index);
}
+ /**
+ * 根据GID获取子任务
+ * @param gid 任务GID
+ * @return 子任务对象
+ */
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
@@ -329,14 +412,26 @@ public class TaskList extends Node {
return null;
}
+ /**
+ * 获取子任务列表
+ * @return 子任务列表
+ */
public ArrayList getChildTaskList() {
return this.mChildren;
}
+ /**
+ * 设置任务列表索引
+ * @param index 索引值
+ */
public void setIndex(int index) {
this.mIndex = index;
}
+ /**
+ * 获取任务列表索引
+ * @return 索引值
+ */
public int getIndex() {
return this.mIndex;
}
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java
index 15504be..fe215d2 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java
@@ -16,17 +16,38 @@
package net.micode.notes.gtask.exception;
+/**
+ * Google Task操作失败异常类
+ * 用于处理Google Task同步过程中的操作失败情况
+ */
public class ActionFailureException extends RuntimeException {
+
+ /**
+ * 序列化ID
+ */
private static final long serialVersionUID = 4425249765923293627L;
+ /**
+ * 无参构造函数
+ * 创建一个没有详细信息的ActionFailureException
+ */
public ActionFailureException() {
super();
}
+ /**
+ * 带错误信息的构造函数
+ * @param paramString 错误信息描述
+ */
public ActionFailureException(String paramString) {
super(paramString);
}
+ /**
+ * 带错误信息和原因的构造函数
+ * @param paramString 错误信息描述
+ * @param paramThrowable 导致此异常的原因
+ */
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java
index b08cfb1..1023b1a 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java
@@ -16,17 +16,38 @@
package net.micode.notes.gtask.exception;
+/**
+ * 网络失败异常类
+ * 用于处理Google Task同步过程中的网络连接失败情况
+ */
public class NetworkFailureException extends Exception {
+
+ /**
+ * 序列化ID
+ */
private static final long serialVersionUID = 2107610287180234136L;
+ /**
+ * 无参构造函数
+ * 创建一个没有详细信息的NetworkFailureException
+ */
public NetworkFailureException() {
super();
}
+ /**
+ * 带错误信息的构造函数
+ * @param paramString 错误信息描述
+ */
public NetworkFailureException(String paramString) {
super(paramString);
}
+ /**
+ * 带错误信息和原因的构造函数
+ * @param paramString 错误信息描述
+ * @param paramThrowable 导致此异常的原因
+ */
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java
index 440a871..1c9cf18 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java
@@ -1,4 +1,3 @@
-
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
@@ -28,23 +27,39 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
-
+/**
+ * Google Task异步任务类
+ * 用于在后台执行Google Task同步操作
+ */
public class GTaskASyncTask extends AsyncTask {
+ // 通知ID
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
+ /**
+ * 同步完成监听器接口
+ */
public interface OnCompleteListener {
void onComplete();
}
+ // 上下文对象
private Context mContext;
+ // 通知管理器
private NotificationManager mNotifiManager;
+ // Google Task管理器
private GTaskManager mTaskManager;
+ // 同步完成监听器
private OnCompleteListener mOnCompleteListener;
+ /**
+ * 构造函数
+ * @param context 上下文
+ * @param listener 完成监听器
+ */
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
@@ -53,16 +68,28 @@ public class GTaskASyncTask extends AsyncTask {
mTaskManager = GTaskManager.getInstance();
}
+ /**
+ * 取消同步操作
+ */
public void cancelSync() {
mTaskManager.cancelSync();
}
+ /**
+ * 发布同步进度
+ * @param message 进度信息
+ */
public void publishProgess(String message) {
publishProgress(new String[] {
message
});
}
+ /**
+ * 显示通知
+ * @param tickerId 通知标题资源ID
+ * @param content 通知内容
+ */
private void showNotification(int tickerId, String content) {
PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) {
@@ -74,7 +101,7 @@ public class GTaskASyncTask extends AsyncTask {
NotesListActivity.class), 0);
}
-
+ // 创建通知
Notification.Builder builder = new Notification.Builder(mContext)
.setAutoCancel(true)
.setContentTitle(mContext.getString(R.string.app_name))
@@ -86,7 +113,11 @@ public class GTaskASyncTask extends AsyncTask {
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
@@ -94,6 +125,10 @@ public class GTaskASyncTask extends AsyncTask {
return mTaskManager.sync(mContext, this);
}
+ /**
+ * 更新同步进度
+ * @param progress 进度信息数组
+ */
@Override
protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]);
@@ -102,23 +137,30 @@ public class GTaskASyncTask extends AsyncTask {
}
}
+ /**
+ * 同步完成后的处理
+ * @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()));
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));
}
if (mOnCompleteListener != null) {
new Thread(new Runnable() {
-
public void run() {
mOnCompleteListener.onComplete();
}
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java
index c67dfdf..5ab4e3c 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java
@@ -60,36 +60,43 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
-
+/**
+ * GTaskClient类用于处理与Google Tasks的同步交互
+ * 实现了单例模式,提供了登录、创建任务、更新任务等功能
+ */
public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName();
+ // Google Tasks相关URL常量
private static final String GTASK_URL = "https://mail.google.com/tasks/";
-
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
-
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
+ // 单例实例
private static GTaskClient mInstance = null;
+ // HTTP客户端
private DefaultHttpClient mHttpClient;
+ // 请求URL
private String mGetUrl;
-
private String mPostUrl;
+ // 客户端版本号
private long mClientVersion;
+ // 登录状态相关
private boolean mLoggedin;
-
private long mLastLoginTime;
-
private int mActionId;
-
private Account mAccount;
+ // 更新数组
private JSONArray mUpdateArray;
+ /**
+ * 私有构造函数,初始化成员变量
+ */
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
@@ -102,6 +109,10 @@ public class GTaskClient {
mUpdateArray = null;
}
+ /**
+ * 获取GTaskClient的单例实例
+ * @return GTaskClient实例
+ */
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@@ -109,15 +120,19 @@ public class GTaskClient {
return mInstance;
}
+ /**
+ * 登录Google账户
+ * @param activity 当前Activity
+ * @return 是否登录成功
+ */
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
+ // 切换账号后需要重新登录
if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
@@ -136,7 +151,7 @@ public class GTaskClient {
return false;
}
- // login with custom domain if necessary
+ // 如果是自定义域名,需要特殊处理登录URL
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
@@ -151,7 +166,7 @@ public class GTaskClient {
}
}
- // try to login with google official url
+ // 尝试使用官方URL登录
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
@@ -164,6 +179,12 @@ public class GTaskClient {
return true;
}
+ /**
+ * 登录Google账户获取认证Token
+ * @param activity 当前Activity
+ * @param invalidateToken 是否使token失效
+ * @return 认证Token
+ */
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
@@ -189,7 +210,7 @@ public class GTaskClient {
return null;
}
- // get the token now
+ // 获取认证Token
AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
@@ -207,10 +228,15 @@ public class GTaskClient {
return authToken;
}
+ /**
+ * 尝试登录Google Tasks
+ * @param activity 当前Activity
+ * @param authToken 认证Token
+ * @return 是否登录成功
+ */
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
- // maybe the auth token is out of date, now let's invalidate the
- // token and try again
+ // Token可能过期,尝试重新获取Token
authToken = loginGoogleAccount(activity, true);
if (authToken == null) {
Log.e(TAG, "login google account failed");
@@ -225,6 +251,11 @@ public class GTaskClient {
return true;
}
+ /**
+ * 使用Token登录Google Tasks
+ * @param authToken 认证Token
+ * @return 是否登录成功
+ */
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000;
@@ -236,14 +267,14 @@ public class GTaskClient {
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
- // login gtask
+ // 登录Google Tasks
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) {
@@ -255,7 +286,7 @@ public class GTaskClient {
Log.w(TAG, "it seems that there is no auth cookie");
}
- // get the client version
+ // 获取客户端版本号
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}";
@@ -272,7 +303,6 @@ public class GTaskClient {
e.printStackTrace();
return false;
} catch (Exception e) {
- // simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed");
return false;
}
@@ -280,10 +310,18 @@ public class GTaskClient {
return true;
}
+ /**
+ * 获取操作ID
+ * @return 操作ID
+ */
private int getActionId() {
return mActionId++;
}
+ /**
+ * 创建HTTP POST请求
+ * @return HttpPost对象
+ */
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@@ -291,6 +329,12 @@ public class GTaskClient {
return httpPost;
}
+ /**
+ * 获取HTTP响应内容
+ * @param entity HTTP实体
+ * @return 响应内容字符串
+ * @throws IOException IO异常
+ */
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
@@ -323,6 +367,12 @@ public class GTaskClient {
}
}
+ /**
+ * 发送POST请求
+ * @param js 请求JSON数据
+ * @return 响应JSON对象
+ * @throws NetworkFailureException 网络异常
+ */
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@@ -336,7 +386,7 @@ public class GTaskClient {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
- // execute the post
+ // 执行POST请求
HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
@@ -360,20 +410,25 @@ public class GTaskClient {
}
}
+ /**
+ * 创建任务
+ * @param task 任务对象
+ * @throws NetworkFailureException 网络异常
+ */
public void createTask(Task task) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
- // action_list
+ // 构建action_list
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
+ // 发送请求
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@@ -386,20 +441,25 @@ public class GTaskClient {
}
}
+ /**
+ * 创建任务列表
+ * @param tasklist 任务列表对象
+ * @throws NetworkFailureException 网络异常
+ */
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
- // action_list
+ // 构建action_list
actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
- // client version
+ // 添加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);
@@ -412,15 +472,19 @@ public class GTaskClient {
}
}
+ /**
+ * 提交更新
+ * @throws NetworkFailureException 网络异常
+ */
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
JSONObject jsPost = new JSONObject();
- // action_list
+ // 添加action_list
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
- // client_version
+ // 添加client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
@@ -433,10 +497,14 @@ public class GTaskClient {
}
}
+ /**
+ * 添加节点更新
+ * @param node 节点对象
+ * @throws NetworkFailureException 网络异常
+ */
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
- // too many update items may result in an error
- // set max to 10 items
+ // 更新项过多可能导致错误,最多10项
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
@@ -447,6 +515,13 @@ public class GTaskClient {
}
}
+ /**
+ * 移动任务
+ * @param task 任务对象
+ * @param preParent 原父任务列表
+ * @param curParent 目标父任务列表
+ * @throws NetworkFailureException 网络异常
+ */
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
commitUpdate();
@@ -455,26 +530,25 @@ public class GTaskClient {
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
- // action_list
+ // 构建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
+ // 仅当在同一任务列表内移动且不是第一个时添加prior_sibling_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());
if (preParent != curParent) {
- // put the dest_list only if moving between tasklists
+ // 仅当在不同任务列表间移动时添加dest_list
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
- // client_version
+ // 添加client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
@@ -486,18 +560,23 @@ public class GTaskClient {
}
}
+ /**
+ * 删除节点
+ * @param node 节点对象
+ * @throws NetworkFailureException 网络异常
+ */
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
- // action_list
+ // 构建action_list
node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
- // client_version
+ // 添加client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
@@ -509,6 +588,11 @@ public class GTaskClient {
}
}
+ /**
+ * 获取任务列表
+ * @return 任务列表JSON数组
+ * @throws NetworkFailureException 网络异常
+ */
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@@ -520,7 +604,7 @@ public class GTaskClient {
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
- // get the task list
+ // 获取任务列表
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}";
@@ -547,6 +631,12 @@ public class GTaskClient {
}
}
+ /**
+ * 获取指定任务列表的任务
+ * @param listGid 任务列表ID
+ * @return 任务JSON数组
+ * @throws NetworkFailureException 网络异常
+ */
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
try {
@@ -554,7 +644,7 @@ public class GTaskClient {
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
- // action_list
+ // 构建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 +653,7 @@ public class GTaskClient {
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
- // client_version
+ // 添加client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
JSONObject jsResponse = postRequest(jsPost);
@@ -575,10 +665,17 @@ public class GTaskClient {
}
}
+ /**
+ * 获取同步账户
+ * @return 同步账户对象
+ */
public Account getSyncAccount() {
return mAccount;
}
+ /**
+ * 重置更新数组
+ */
public void resetUpdateArray() {
mUpdateArray = null;
}
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java
index d2b4082..5c69917 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java
@@ -47,46 +47,41 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
-
+/**
+ * GTaskManager类用于管理Google Tasks同步功能
+ * 实现了本地笔记与Google Tasks的双向同步
+ */
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;
-
- public static final int STATE_INTERNAL_ERROR = 2;
-
- public static final int STATE_SYNC_IN_PROGRESS = 3;
-
- public static final int STATE_SYNC_CANCELLED = 4;
-
- private static GTaskManager mInstance = null;
-
- private Activity mActivity;
-
- private Context mContext;
-
- private ContentResolver mContentResolver;
-
- private boolean mSyncing;
-
- private boolean mCancelled;
-
- private HashMap mGTaskListHashMap;
-
- private HashMap mGTaskHashMap;
-
- private HashMap mMetaHashMap;
-
- private TaskList mMetaList;
-
- private HashSet mLocalDeleteIdMap;
-
- private HashMap mGidToNid;
-
- private HashMap mNidToGid;
-
+ // 同步状态码定义
+ public static final int STATE_SUCCESS = 0; // 同步成功
+ public static final int STATE_NETWORK_ERROR = 1; // 网络错误
+ public static final int STATE_INTERNAL_ERROR = 2; // 内部错误
+ public static final int STATE_SYNC_IN_PROGRESS = 3; // 同步进行中
+ public static final int STATE_SYNC_CANCELLED = 4; // 同步被取消
+
+ private static GTaskManager mInstance = null; // 单例实例
+
+ private Activity mActivity; // 用于获取认证Token的Activity
+ private Context mContext; // 应用上下文
+ private ContentResolver mContentResolver; // 内容解析器
+
+ private boolean mSyncing; // 是否正在同步
+ private boolean mCancelled; // 是否取消同步
+
+ // 数据结构用于存储同步状态
+ private HashMap mGTaskListHashMap; // 任务列表映射
+ private HashMap mGTaskHashMap; // 任务节点映射
+ private HashMap mMetaHashMap; // 元数据映射
+ private TaskList mMetaList; // 元数据列表
+ private HashSet mLocalDeleteIdMap; // 本地删除ID集合
+ private HashMap mGidToNid; // Google ID到本地Note ID的映射
+ private HashMap mNidToGid; // 本地Note ID到Google ID的映射
+
+ /**
+ * 私有构造函数,初始化所有数据结构
+ */
private GTaskManager() {
mSyncing = false;
mCancelled = false;
@@ -99,6 +94,9 @@ public class GTaskManager {
mNidToGid = new HashMap();
}
+ /**
+ * 获取GTaskManager的单例实例
+ */
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@@ -106,11 +104,19 @@ public class GTaskManager {
return mInstance;
}
+ /**
+ * 设置Activity上下文,用于获取认证Token
+ */
public synchronized void setActivityContext(Activity activity) {
- // used for getting authtoken
mActivity = activity;
}
+ /**
+ * 执行同步操作
+ * @param context 上下文
+ * @param asyncTask 异步任务对象
+ * @return 同步状态码
+ */
public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
@@ -131,18 +137,18 @@ public class GTaskManager {
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
- // login google task
+ // 登录Google Tasks
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 +174,10 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
+ /**
+ * 初始化Google Tasks列表
+ * 获取远程任务列表并加载元数据
+ */
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
@@ -175,7 +185,7 @@ 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 +197,7 @@ 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 +213,7 @@ public class GTaskManager {
}
}
- // create meta list if not existed
+ // 如果元数据列表不存在则创建
if (mMetaList == null) {
mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
@@ -211,7 +221,7 @@ 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 +235,7 @@ 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);
@@ -247,6 +257,10 @@ public class GTaskManager {
}
}
+ /**
+ * 执行内容同步
+ * 处理本地和远程的增删改操作
+ */
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;
@@ -259,7 +273,7 @@ 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 +300,10 @@ 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 +320,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 +340,7 @@ public class GTaskManager {
}
}
- // go through remaining items
+ // 处理剩余项目
Iterator> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = iter.next();
@@ -334,16 +348,15 @@ 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
+ // mCancelled可能被其他线程设置,需要逐个检查
+ // 清理本地删除表
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 +364,10 @@ public class GTaskManager {
}
+ /**
+ * 同步文件夹
+ * 处理本地和远程文件夹的同步
+ */
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
@@ -361,7 +378,7 @@ 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);
@@ -373,7 +390,7 @@ 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))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
@@ -390,7 +407,7 @@ public class GTaskManager {
}
}
- // for call-note folder
+ // 处理通话记录文件夹
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] {
@@ -404,8 +421,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 +440,7 @@ public class GTaskManager {
}
}
- // for local existing folders
+ // 处理本地已存在的文件夹
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
@@ -441,10 +457,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 +476,7 @@ public class GTaskManager {
}
}
- // for remote add folders
+ // 处理远程新增的文件夹
Iterator> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = iter.next();
@@ -476,6 +492,12 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate();
}
+ /**
+ * 执行内容同步操作
+ * @param syncType 同步类型
+ * @param node 节点对象
+ * @param c 数据库游标
+ */
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@@ -510,18 +532,22 @@ 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:
break;
case Node.SYNC_ACTION_ERROR:
default:
- throw new ActionFailureException("unkown sync action type");
+ throw new ActionFailureException("unknown sync action type");
}
}
+ /**
+ * 添加本地节点
+ * @param node 要添加的节点
+ */
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
@@ -549,7 +575,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 +588,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
+ // 数据ID不可用,需要创建新的
data.remove(DataColumns.ID);
}
}
@@ -584,25 +609,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);
}
+ /**
+ * 更新本地节点
+ * @param node 节点对象
+ * @param c 数据库游标
+ */
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());
@@ -615,10 +645,15 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true);
- // update meta info
+ // 更新元数据信息
updateRemoteMeta(node.getGid(), sqlNote);
}
+ /**
+ * 添加远程节点
+ * @param node 节点对象
+ * @param c 数据库游标
+ */
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@@ -627,7 +662,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 +677,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 +706,7 @@ public class GTaskManager {
}
}
- // no match we can add now
+ // 没有匹配项则可以添加
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
@@ -681,17 +716,22 @@ 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());
}
+ /**
+ * 更新远程节点
+ * @param node 节点对象
+ * @param c 数据库游标
+ */
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java
index cca36f7..5d68b0b 100644
--- a/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java
+++ b/src/Notes-master/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java
@@ -23,25 +23,42 @@ import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
+/**
+ * Google Tasks同步服务类
+ * 负责管理与Google Tasks的同步操作,包括启动同步、取消同步等功能
+ */
public class GTaskSyncService extends Service {
+ /** Intent中同步动作的键名 */
public final static String ACTION_STRING_NAME = "sync_action_type";
+ /** 开始同步的动作值 */
public final static int ACTION_START_SYNC = 0;
+ /** 取消同步的动作值 */
public final static int ACTION_CANCEL_SYNC = 1;
+ /** 无效动作值 */
public final static int ACTION_INVALID = 2;
+ /** 广播Action名称 */
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
+ /** 广播Extra:是否正在同步 */
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
+ /** 广播Extra:同步进度信息 */
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 +73,32 @@ public class GTaskSyncService extends Service {
}
}
+ /**
+ * 取消当前的同步操作
+ */
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
+ /**
+ * Service创建时的回调
+ * 初始化同步任务为空
+ */
@Override
public void onCreate() {
mSyncTask = null;
}
+ /**
+ * Service启动时的回调
+ * 处理同步相关的Intent请求
+ * @param intent 启动服务的Intent
+ * @param flags 启动标志
+ * @param startId 启动ID
+ * @return 粘性服务的标志
+ */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
@@ -86,6 +118,10 @@ public class GTaskSyncService extends Service {
return super.onStartCommand(intent, flags, startId);
}
+ /**
+ * 系统内存不足时的回调
+ * 取消当前的同步任务
+ */
@Override
public void onLowMemory() {
if (mSyncTask != null) {
@@ -93,10 +129,18 @@ public class GTaskSyncService extends Service {
}
}
+ /**
+ * 绑定Service时的回调
+ * 本服务不支持绑定,返回null
+ */
public IBinder onBind(Intent intent) {
return null;
}
+ /**
+ * 发送同步状态广播
+ * @param msg 同步进度信息
+ */
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@@ -105,6 +149,10 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent);
}
+ /**
+ * 静态方法:启动同步
+ * @param activity 当前Activity上下文
+ */
public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
@@ -112,16 +160,28 @@ public class GTaskSyncService extends Service {
activity.startService(intent);
}
+ /**
+ * 静态方法:取消同步
+ * @param context 应用程序上下文
+ */
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);
}
+ /**
+ * 静态方法:判断是否正在同步
+ * @return 是否有正在进行的同步任务
+ */
public static boolean isSyncing() {
return mSyncTask != null;
}
+ /**
+ * 静态方法:获取当前同步进度信息
+ * @return 同步进度信息字符串
+ */
public static String getProgressString() {
return mSyncProgress;
}
diff --git a/src/Notes-master/app/src/main/res/values/styles.xml b/src/Notes-master/app/src/main/res/values/styles.xml
index d750e65..4889154 100644
--- a/src/Notes-master/app/src/main/res/values/styles.xml
+++ b/src/Notes-master/app/src/main/res/values/styles.xml
@@ -62,8 +62,12 @@
- @style/NoteActionBarStyle
+
+
+
+
\ No newline at end of file