diff --git a/java/net/micode/notes/data/Contact.java b/java/net/micode/notes/data/Contact.java index d97ac5d..e486249 100644 --- a/java/net/micode/notes/data/Contact.java +++ b/java/net/micode/notes/data/Contact.java @@ -25,49 +25,85 @@ import android.util.Log; import java.util.HashMap; +/** + * 联系人查询工具类 + * + * 功能:根据电话号码查询对应的联系人姓名 + * 特点: + * 1. 使用内存缓存提升查询效率 + * 2. 支持电话号码最小匹配规则(国际号码优化) + * 3. 处理联系人数据库查询异常 + */ public class Contact { + // 联系人缓存:电话号码 -> 联系人姓名 private static HashMap sContactCache; - private static final String TAG = "Contact"; + private static final String TAG = "Contact"; // 日志标签 + /** + * 联系人查询的SQL选择语句 + * + * 结构说明: + * 1. 使用 PHONE_NUMBERS_EQUAL 进行号码匹配(考虑格式化差异) + * 2. 限定数据类型为电话类型 (Phone.CONTENT_ITEM_TYPE) + * 3. 通过子查询关联 phone_lookup 表实现快速索引 + * 4. "+" 是占位符,将被替换为最小匹配长度 + */ private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER - + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" - + " AND " + Data.RAW_CONTACT_ID + " IN " + + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + + " AND " + Data.RAW_CONTACT_ID + " IN " + "(SELECT raw_contact_id " + " FROM phone_lookup" - + " WHERE min_match = '+')"; + + " WHERE min_match = '+')"; // '+' 将被实际的最小匹配值替换 + /** + * 根据电话号码获取联系人姓名 + * + * @param context 上下文对象(用于访问ContentResolver) + * @param phoneNumber 要查询的电话号码 + * @return 联系人姓名,若未找到则返回null + */ public static String getContact(Context context, String phoneNumber) { - if(sContactCache == null) { + // 初始化缓存 + if (sContactCache == null) { sContactCache = new HashMap(); } - if(sContactCache.containsKey(phoneNumber)) { + // 首先检查缓存 + if (sContactCache.containsKey(phoneNumber)) { return sContactCache.get(phoneNumber); } - String selection = CALLER_ID_SELECTION.replace("+", - PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); + // 生成最小匹配长度(处理国际号码) + String minMatch = PhoneNumberUtils.toCallerIDMinMatch(phoneNumber); + // 构建完整查询语句 + String selection = CALLER_ID_SELECTION.replace("+", minMatch); + + // 执行内容提供者查询 Cursor cursor = context.getContentResolver().query( - Data.CONTENT_URI, - new String [] { Phone.DISPLAY_NAME }, - selection, - new String[] { phoneNumber }, - null); + Data.CONTENT_URI, // 联系人数据URI + 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()); + Log.e(TAG, "Cursor字段访问错误: " + e.toString()); return null; } finally { + // 确保关闭游标 cursor.close(); } } else { - Log.d(TAG, "No contact matched with number:" + phoneNumber); + // 无匹配结果日志 + Log.d(TAG, "未找到匹配的联系人号码: " + phoneNumber); return null; } } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/data/Notes.java b/java/net/micode/notes/data/Notes.java index f240604..f08d319 100644 --- a/java/net/micode/notes/data/Notes.java +++ b/java/net/micode/notes/data/Notes.java @@ -17,263 +17,289 @@ package net.micode.notes.data; import android.net.Uri; + +/** + * 便签应用的数据模型类,定义便签和文件夹的常量、URI及数据库表结构 + * 包含类型标识、系统文件夹ID、 Intent 传递参数、数据列定义等 + */ public class Notes { + // 内容提供者的权限标识,用于URI构建 public static final String AUTHORITY = "micode_notes"; + // 日志标签,用于Logcat过滤 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; - - 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"; - public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; - 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; + public static final int ID_ROOT_FOLDER = 0; // 根文件夹ID + public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹ID(无所属便签) + public static final int ID_CALL_RECORD_FOLDER = -2; // 通话记录文件夹ID + public static final int ID_TRASH_FOLER = -3; // 回收站文件夹ID + + // Intent传递的额外参数键名(用于Activity间数据传递) + 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"; // 背景色ID + public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // 桌面小部件ID + public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // 小部件类型 + public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹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; // 2x尺寸 + public static final int TYPE_WIDGET_4X = 1; // 4x尺寸 + /** + * 数据类型常量内部类,定义便签内容的MIME类型 + */ public static class DataConstants { - public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; - public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; + 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:查询所有便签和文件夹 + * 格式:content://{AUTHORITY}/note */ public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); /** - * Uri to query data + * 内容提供者URI:查询便签附件或详细数据 + * 格式:content://{AUTHORITY}/data */ public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); + /** + * 便签/文件夹数据库表字段接口(Note表结构) + * 定义表中各列的常量名及数据类型说明 + */ 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(便签所属文件夹ID,或文件夹的父文件夹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)

+ * 便签关联的桌面小部件ID + *

类型:INTEGER (long)

*/ public static final String WIDGET_ID = "widget_id"; /** - * Note's widget type - *

Type: INTEGER (long)

+ * 便签关联的桌面小部件类型 + *

类型: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

+ * 便签是否包含附件(1=有,0=无) + *

类型: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

+ * 本地修改标识(1=已修改,0=未修改) + *

类型: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 Task ID(用于同步谷歌任务) + *

类型:TEXT

*/ public static final String GTASK_ID = "gtask_id"; /** - * The version code - *

Type : INTEGER (long)

+ * 数据版本号(用于版本控制) + *

类型:INTEGER (long)

*/ public static final String VERSION = "version"; } + /** + * 便签附件/详细数据表字段接口(Data表结构) + * 存储便签的多媒体附件或扩展数据 + */ 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

+ * 通用数据列1(含义由MIME类型决定,整型) + *

类型:INTEGER

*/ public static final String DATA1 = "data1"; /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * integer data type - *

Type: INTEGER

+ * 通用数据列2(含义由MIME类型决定,整型) + *

类型:INTEGER

*/ public static final String DATA2 = "data2"; /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * TEXT data type - *

Type: TEXT

+ * 通用数据列3(含义由MIME类型决定,文本型) + *

类型:TEXT

*/ public static final String DATA3 = "data3"; /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * TEXT data type - *

Type: TEXT

+ * 通用数据列4(含义由MIME类型决定,文本型) + *

类型:TEXT

*/ public static final String DATA4 = "data4"; /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * TEXT data type - *

Type: TEXT

+ * 通用数据列5(含义由MIME类型决定,文本型) + *

类型:TEXT

*/ public static final String DATA5 = "data5"; } + /** + * 文本便签内部类(继承DataColumns接口) + * 定义文本便签的特殊字段和URI + */ 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=普通模式)

+ * 存储于DataColumns.DATA1列 */ public static final String MODE = DATA1; + // 清单模式标识 public static final int MODE_CHECK_LIST = 1; - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; - - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; - - public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); + // 内容提供者相关URI和MIME类型 + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; // 目录类型 + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; // 条目类型 + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); // 文本便签URI } + /** + * 通话记录便签内部类(继承DataColumns接口) + * 定义通话记录便签的特殊字段和URI + */ public static final class CallNote implements DataColumns { /** - * Call date for this record - *

Type: INTEGER (long)

+ * 通话日期(时间戳) + *

类型:INTEGER (long)

+ * 存储于DataColumns.DATA1列 */ public static final String CALL_DATE = DATA1; /** - * Phone number for this record - *

Type: TEXT

+ * 电话号码 + *

类型:TEXT

+ * 存储于DataColumns.DATA3列 */ public static final String PHONE_NUMBER = DATA3; - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; - - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; - - public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); + // 内容提供者相关URI和MIME类型 + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; // 目录类型 + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; // 条目类型 + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); // 通话记录URI } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/data/NotesDatabaseHelper.java b/java/net/micode/notes/data/NotesDatabaseHelper.java index ffe5d57..d0a4e8f 100644 --- a/java/net/micode/notes/data/NotesDatabaseHelper.java +++ b/java/net/micode/notes/data/NotesDatabaseHelper.java @@ -27,189 +27,248 @@ import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.NoteColumns; +/** + * 便签应用数据库辅助类,继承自SQLiteOpenHelper + * 负责创建和管理数据库表结构、定义触发器、处理版本升级 + * 采用单例模式确保全局唯一数据库实例 + */ public class NotesDatabaseHelper extends SQLiteOpenHelper { + // 数据库文件名 private static final String DB_NAME = "note.db"; - + // 数据库版本号(当前为4) private static final int DB_VERSION = 4; + /** + * 数据库表名接口,定义note表和data表的常量名 + */ 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; + /** + * 创建note表的SQL语句(存储便签和文件夹基本信息) + * 字段说明: + * - ID: 主键 + * - PARENT_ID: 父文件夹ID + * - ALERTED_DATE: 提醒日期(时间戳) + * - BG_COLOR_ID: 背景色ID + * - CREATED_DATE: 创建日期(默认当前时间戳) + * - HAS_ATTACHMENT: 是否有附件(1=有) + * - MODIFIED_DATE: 最后修改日期(默认当前时间戳) + * - NOTES_COUNT: 文件夹包含的便签数 + * - SNIPPET: 便签内容或文件夹名称 + * - TYPE: 类型(便签/文件夹/系统) + * - WIDGET_ID: 关联的桌面小部件ID + * - WIDGET_TYPE: 小部件类型 + * - SYNC_ID: 同步ID(用于云同步) + * - LOCAL_MODIFIED: 本地修改标识(1=已修改) + * - ORIGIN_PARENT_ID: 原始父文件夹ID(移动时使用) + * - GTASK_ID: Google任务ID + * - VERSION: 数据版本号(用于冲突检测) + */ private static final String CREATE_NOTE_TABLE_SQL = - "CREATE TABLE " + TABLE.NOTE + "(" + - NoteColumns.ID + " INTEGER PRIMARY KEY," + - NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + - NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + - NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + - NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + - ")"; + "CREATE TABLE " + TABLE.NOTE + "(" + + NoteColumns.ID + " INTEGER PRIMARY KEY," + + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + + ")"; + /** + * 创建data表的SQL语句(存储便签附件或扩展数据) + * 字段说明: + * - ID: 主键 + * - MIME_TYPE: 数据类型(如图片/音频) + * - NOTE_ID: 关联的便签ID(外键) + * - CREATED_DATE: 创建日期(默认当前时间戳) + * - MODIFIED_DATE: 最后修改日期(默认当前时间戳) + * - CONTENT: 数据内容(文本类型) + * - DATA1-DATA5: 通用数据列(含义由MIME类型决定) + */ private static final String CREATE_DATA_TABLE_SQL = - "CREATE TABLE " + TABLE.DATA + "(" + - DataColumns.ID + " INTEGER PRIMARY KEY," + - DataColumns.MIME_TYPE + " TEXT NOT NULL," + - DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + - DataColumns.DATA1 + " INTEGER," + - DataColumns.DATA2 + " INTEGER," + - DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + - DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + - DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + - ")"; - + "CREATE TABLE " + TABLE.DATA + "(" + + DataColumns.ID + " INTEGER PRIMARY KEY," + + DataColumns.MIME_TYPE + " TEXT NOT NULL," + + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA1 + " INTEGER," + + DataColumns.DATA2 + " INTEGER," + + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + + ")"; + + // 创建data表note_id索引的SQL(加速按便签ID查询) private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = - "CREATE INDEX IF NOT EXISTS note_id_index ON " + - TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; + "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 + * 触发器:当便签移动到新文件夹时,增加目标文件夹的便签计数 + * 触发时机:note表的parent_id更新后 */ private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = - "CREATE TRIGGER increase_folder_count_on_update "+ - " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + - " END"; + "CREATE TRIGGER increase_folder_count_on_update "+ + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END"; /** - * Decrease folder's note count when move note from folder + * 触发器:当便签移出文件夹时,减少原文件夹的便签计数 + * 触发时机:note表的parent_id更新后 */ private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = - "CREATE TRIGGER decrease_folder_count_on_update " + - " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + - " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + - " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + - " END"; + "CREATE TRIGGER decrease_folder_count_on_update " + + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + + " END"; /** - * Increase folder's note count when insert new note to the folder + * 触发器:当新便签插入到文件夹时,增加目标文件夹的便签计数 + * 触发时机:note表插入新记录后 */ private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = - "CREATE TRIGGER increase_folder_count_on_insert " + - " AFTER INSERT ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + - " END"; + "CREATE TRIGGER increase_folder_count_on_insert " + + " AFTER INSERT ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END"; /** - * Decrease folder's note count when delete note from the folder + * 触发器:当便签从文件夹删除时,减少原文件夹的便签计数 + * 触发时机:note表删除记录后 */ private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = - "CREATE TRIGGER decrease_folder_count_on_delete " + - " AFTER DELETE ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + - " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + - " AND " + NoteColumns.NOTES_COUNT + ">0;" + - " END"; + "CREATE TRIGGER decrease_folder_count_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0;" + + " END"; /** - * Update note's content when insert data with type {@link DataConstants#NOTE} + * 触发器:当插入文本便签数据时,更新note表的内容 + * 触发时机:data表插入MIME_TYPE为文本便签的记录后 */ private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = - "CREATE TRIGGER update_note_content_on_insert " + - " AFTER INSERT ON " + TABLE.DATA + - " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + - " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + - " END"; + "CREATE TRIGGER update_note_content_on_insert " + + " AFTER INSERT ON " + TABLE.DATA + + " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END"; /** - * Update note's content when data with {@link DataConstants#NOTE} type has changed + * 触发器:当文本便签数据更新时,更新note表的内容 + * 触发时机:data表更新MIME_TYPE为文本便签的记录后 */ private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = - "CREATE TRIGGER update_note_content_on_update " + - " AFTER UPDATE ON " + TABLE.DATA + - " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + - " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + - " END"; + "CREATE TRIGGER update_note_content_on_update " + + " AFTER UPDATE ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END"; /** - * Update note's content when data with {@link DataConstants#NOTE} type has deleted + * 触发器:当删除文本便签数据时,清空note表的内容 + * 触发时机:data表删除MIME_TYPE为文本便签的记录后 */ private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = - "CREATE TRIGGER update_note_content_on_delete " + - " AFTER delete ON " + TABLE.DATA + - " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.SNIPPET + "=''" + - " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + - " END"; + "CREATE TRIGGER update_note_content_on_delete " + + " AFTER delete ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=''" + + " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + + " END"; /** - * Delete datas belong to note which has been deleted + * 触发器:当便签被删除时,级联删除其关联的附件数据 + * 触发时机:note表删除记录后 */ private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = - "CREATE TRIGGER delete_data_on_delete " + - " AFTER DELETE ON " + TABLE.NOTE + - " BEGIN" + - " DELETE FROM " + TABLE.DATA + - " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + - " END"; + "CREATE TRIGGER delete_data_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.DATA + + " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + + " END"; /** - * Delete notes belong to folder which has been deleted + * 触发器:当文件夹被删除时,级联删除其包含的所有便签 + * 触发时机:note表删除记录后(仅针对文件夹类型) */ private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = - "CREATE TRIGGER folder_delete_notes_on_delete " + - " AFTER DELETE ON " + TABLE.NOTE + - " BEGIN" + - " DELETE FROM " + TABLE.NOTE + - " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + - " END"; + "CREATE TRIGGER folder_delete_notes_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END"; /** - * Move notes belong to folder which has been moved to trash folder + * 触发器:当文件夹被移动到回收站时,将其包含的便签同步移动到回收站 + * 触发时机:note表更新parent_id为回收站ID后 */ private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = - "CREATE TRIGGER folder_move_notes_on_trash " + - " AFTER UPDATE ON " + TABLE.NOTE + - " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + - " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + - " END"; + "CREATE TRIGGER folder_move_notes_on_trash " + + " AFTER UPDATE ON " + TABLE.NOTE + + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END"; + /** + * 构造方法,调用父类SQLiteOpenHelper初始化 + * @param context 应用上下文 + */ public NotesDatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } + /** + * 创建note表及相关触发器,并初始化系统文件夹 + * @param db 可写的SQLiteDatabase实例 + */ public void createNoteTable(SQLiteDatabase db) { db.execSQL(CREATE_NOTE_TABLE_SQL); reCreateNoteTableTriggers(db); @@ -217,6 +276,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { Log.d(TAG, "note table has been created"); } + /** + * 重建note表相关触发器(先删除旧触发器再创建新触发器) + * @param db 可写的SQLiteDatabase实例 + */ 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 +298,22 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); } + /** + * 创建系统默认文件夹(通话记录、根目录、临时文件夹、回收站) + * @param db 可写的SQLiteDatabase实例 + */ 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 +321,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 +329,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 +337,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { db.insert(TABLE.NOTE, null, values); } + /** + * 创建data表及相关触发器,并创建note_id索引 + * @param db 可写的SQLiteDatabase实例 + */ public void createDataTable(SQLiteDatabase db) { db.execSQL(CREATE_DATA_TABLE_SQL); reCreateDataTableTriggers(db); @@ -277,6 +348,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { Log.d(TAG, "data table has been created"); } + /** + * 重建data表相关触发器(先删除旧触发器再创建新触发器) + * @param db 可写的SQLiteDatabase实例 + */ 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 +362,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); } + /** + * 获取数据库辅助类的单例实例(线程安全) + * @param context 应用上下文 + * @return NotesDatabaseHelper实例 + */ static synchronized NotesDatabaseHelper getInstance(Context context) { if (mInstance == null) { mInstance = new NotesDatabaseHelper(context); @@ -294,45 +374,66 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { return mInstance; } + /** + * 数据库创建回调(首次创建数据库时调用) + * 调用createNoteTable和createDataTable创建表结构 + * @param db 可写的SQLiteDatabase实例 + */ @Override public void onCreate(SQLiteDatabase db) { createNoteTable(db); createDataTable(db); } + /** + * 数据库版本升级回调 + * 根据旧版本号执行对应的升级逻辑 + * @param db 可写的SQLiteDatabase实例 + * @param oldVersion 旧版本号 + * @param newVersion 新版本号 + */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { boolean reCreateTriggers = false; boolean skipV2 = false; + // 版本1升级到版本2(全量重建表结构) if (oldVersion == 1) { upgradeToV2(db); - skipV2 = true; // this upgrade including the upgrade from v2 to v3 + skipV2 = true; // 该升级包含了版本2到版本3的逻辑 oldVersion++; } + // 版本2升级到版本3(添加GTASK_ID列和回收站文件夹) if (oldVersion == 2 && !skipV2) { upgradeToV3(db); reCreateTriggers = true; oldVersion++; } + // 版本3升级到版本4(添加VERSION列) if (oldVersion == 3) { upgradeToV4(db); oldVersion++; } + // 若触发器在升级过程中被修改,重新创建触发器 if (reCreateTriggers) { reCreateNoteTableTriggers(db); reCreateDataTableTriggers(db); } + // 若版本升级未完成,抛出异常(防止数据不一致) if (oldVersion != newVersion) { throw new IllegalStateException("Upgrade notes database to version " + newVersion + "fails"); } } + /** + * 版本1升级到版本2的具体实现(全量重建表结构) + * @param db 可写的SQLiteDatabase实例 + */ private void upgradeToV2(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); @@ -340,23 +441,31 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { createDataTable(db); } + /** + * 版本2升级到版本3的具体实现(添加GTASK_ID列和回收站文件夹) + * @param db 可写的SQLiteDatabase实例 + */ 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 + // 添加Google任务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); } + /** + * 版本3升级到版本4的具体实现(添加VERSION列) + * @param db 可写的SQLiteDatabase实例 + */ private void upgradeToV4(SQLiteDatabase db) { db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0"); } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/data/NotesProvider.java b/java/net/micode/notes/data/NotesProvider.java index edb0a60..0455241 100644 --- a/java/net/micode/notes/data/NotesProvider.java +++ b/java/net/micode/notes/data/NotesProvider.java @@ -35,83 +35,120 @@ import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.NotesDatabaseHelper.TABLE; +/** + * 便签应用内容提供者,继承自ContentProvider + * 负责管理便签数据的增删改查操作,对外提供统一的数据访问接口 + * 通过UriMatcher匹配不同的URI请求,实现数据的分层访问控制 + */ public class NotesProvider extends ContentProvider { + // UriMatcher实例,用于匹配不同的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 static { + // 初始化UriMatcher mMatcher = new UriMatcher(UriMatcher.NO_MATCH); + // 注册便签相关URI mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); + // 注册便签数据相关URI mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); + // 注册搜索相关URI mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); } /** - * 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. + * 搜索功能投影定义(用于搜索建议和结果) + * 字段说明: + * - ID: 便签ID + * - SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA: 意图附加数据(便签ID) + * - SearchManager.SUGGEST_COLUMN_TEXT_1: 搜索建议文本1(便签内容,去除换行符) + * - SearchManager.SUGGEST_COLUMN_TEXT_2: 搜索建议文本2(便签内容,去除换行符) + * - SearchManager.SUGGEST_COLUMN_ICON_1: 搜索建议图标(使用R.drawable.search_result) + * - SearchManager.SUGGEST_COLUMN_INTENT_ACTION: 意图动作(ACTION_VIEW) + * - SearchManager.SUGGEST_COLUMN_INTENT_DATA: 意图数据(文本便签MIME类型) */ private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," - + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," - + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," - + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," - + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," - + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," - + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," + + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," + + "'" + 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; + + " FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + /** + * 内容提供者初始化方法(在创建时调用) + * 初始化数据库辅助类实例 + * @return 初始化结果(始终返回true) + */ @Override public boolean onCreate() { mHelper = NotesDatabaseHelper.getInstance(getContext()); return true; } + /** + * 处理数据查询请求 + * 根据URI匹配结果执行不同的查询逻辑 + * @param uri 查询请求URI + * @param projection 查询字段投影 + * @param selection 查询条件 + * @param selectionArgs 查询条件参数 + * @param sortOrder 排序规则 + * @return 查询结果Cursor + */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, - String sortOrder) { + 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); + // 查询便签列表 + c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, sortOrder); break; case URI_NOTE_ITEM: + // 查询单条便签(通过ID) 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); + // 查询便签数据列表 + c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, sortOrder); break; case URI_DATA_ITEM: + // 查询单条便签数据(通过ID) 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"); @@ -119,10 +156,12 @@ public class NotesProvider extends ContentProvider { String searchString = null; if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { + // 从URI路径获取搜索字符串(搜索建议场景) if (uri.getPathSegments().size() > 1) { searchString = uri.getPathSegments().get(1); } } else { + // 从查询参数获取搜索字符串(搜索结果场景) searchString = uri.getQueryParameter("pattern"); } @@ -131,7 +170,9 @@ public class NotesProvider extends ContentProvider { } try { + // 构建模糊查询条件(前后添加通配符) searchString = String.format("%%%s%%", searchString); + // 执行搜索SQL查询 c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, new String[] { searchString }); } catch (IllegalStateException ex) { @@ -141,21 +182,32 @@ public class NotesProvider extends ContentProvider { default: throw new IllegalArgumentException("Unknown URI " + uri); } + // 设置内容变更通知监听 if (c != null) { c.setNotificationUri(getContext().getContentResolver(), uri); } return c; } + /** + * 处理数据插入请求 + * 根据URI匹配结果插入不同类型的数据 + * @param uri 插入请求URI + * @param values 要插入的ContentValues + * @return 插入成功的URI(包含ID) + */ @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = mHelper.getWritableDatabase(); long dataId = 0, noteId = 0, insertedId = 0; + // 根据URI匹配结果执行不同的插入逻辑 switch (mMatcher.match(uri)) { case URI_NOTE: + // 插入便签记录 insertedId = noteId = db.insert(TABLE.NOTE, null, values); break; case URI_DATA: + // 插入便签数据记录(需关联便签ID) if (values.containsKey(DataColumns.NOTE_ID)) { noteId = values.getAsLong(DataColumns.NOTE_ID); } else { @@ -166,13 +218,13 @@ public class NotesProvider extends ContentProvider { default: 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,23 +233,30 @@ public class NotesProvider extends ContentProvider { return ContentUris.withAppendedId(uri, insertedId); } + /** + * 处理数据删除请求 + * 根据URI匹配结果删除不同类型的数据 + * @param uri 删除请求URI + * @param selection 删除条件 + * @param selectionArgs 删除条件参数 + * @return 删除的记录数 + */ @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: + // 删除便签记录(过滤系统文件夹) selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; count = db.delete(TABLE.NOTE, selection, selectionArgs); break; case URI_NOTE_ITEM: + // 删除单条便签记录(通过ID,过滤系统文件夹) id = uri.getPathSegments().get(1); - /** - * ID that smaller than 0 is system folder which is not allowed to - * trash - */ long noteId = Long.valueOf(id); if (noteId <= 0) { break; @@ -206,10 +265,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) id = uri.getPathSegments().get(1); count = db.delete(TABLE.DATA, DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); @@ -218,6 +279,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 +289,42 @@ public class NotesProvider extends ContentProvider { return count; } + /** + * 处理数据更新请求 + * 根据URI匹配结果更新不同类型的数据 + * @param uri 更新请求URI + * @param values 要更新的ContentValues + * @param selection 更新条件 + * @param selectionArgs 更新条件参数 + * @return 更新的记录数 + */ @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,增加版本号) 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) id = uri.getPathSegments().get(1); count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); @@ -258,6 +334,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,10 +344,21 @@ public class NotesProvider extends ContentProvider { return count; } + /** + * 解析查询条件(添加AND连接符) + * @param selection 原始查询条件 + * @return 解析后的查询条件 + */ private String parseSelection(String selection) { return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); } + /** + * 增加便签版本号(用于冲突检测) + * @param id 便签ID(-1表示批量更新) + * @param selection 更新条件 + * @param selectionArgs 更新条件参数 + */ private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { StringBuilder sql = new StringBuilder(120); sql.append("UPDATE "); @@ -279,6 +367,7 @@ public class NotesProvider extends ContentProvider { sql.append(NoteColumns.VERSION); sql.append("=" + NoteColumns.VERSION + "+1 "); + // 构建更新条件 if (id > 0 || !TextUtils.isEmpty(selection)) { sql.append(" WHERE "); } @@ -293,13 +382,19 @@ public class NotesProvider extends ContentProvider { sql.append(selectString); } + // 执行SQL更新语句 mHelper.getWritableDatabase().execSQL(sql.toString()); } + /** + * 获取URI对应的MIME类型(未实现) + * @param uri 目标URI + * @return MIME类型字符串 + */ @Override public String getType(Uri uri) { // TODO Auto-generated method stub return null; } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/gtask/data/MetaData.java b/java/net/micode/notes/gtask/data/MetaData.java index 3a2050b..16cd776 100644 --- a/java/net/micode/notes/gtask/data/MetaData.java +++ b/java/net/micode/notes/gtask/data/MetaData.java @@ -25,36 +25,64 @@ import org.json.JSONException; import org.json.JSONObject; +/** + * Google任务元数据类,继承自Task基类 + * 用于存储Google任务与本地便签的关联元数据信息 + * 主要功能:管理Google任务ID与本地便签的映射关系 + */ public class MetaData extends Task { private final static String TAG = MetaData.class.getSimpleName(); + // 关联的Google任务GID(全局唯一标识) private String mRelatedGid = null; + /** + * 设置元数据信息 + * @param gid Google任务GID + * @param metaInfo 元数据JSON对象 + */ public void setMeta(String gid, JSONObject metaInfo) { try { + // 将Google任务GID存入元数据头部 metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); } catch (JSONException e) { Log.e(TAG, "failed to put related gid"); } + // 将元数据JSON转为字符串存储到便签内容中 setNotes(metaInfo.toString()); + // 设置元数据便签的名称(固定为META_NOTE_NAME) setName(GTaskStringUtils.META_NOTE_NAME); } + /** + * 获取关联的Google任务GID + * @return Google任务GID + */ public String getRelatedGid() { return mRelatedGid; } + /** + * 判断元数据是否值得保存(只要便签内容不为空即值得保存) + * @return 是否值得保存 + */ @Override public boolean isWorthSaving() { return getNotes() != null; } + /** + * 从远程JSON数据设置内容(重写Task基类方法) + * @param js 远程JSON数据 + */ @Override public void setContentByRemoteJSON(JSONObject js) { super.setContentByRemoteJSON(js); if (getNotes() != null) { try { + // 解析便签内容中的元数据JSON JSONObject metaInfo = new JSONObject(getNotes().trim()); + // 提取关联的Google任务GID mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); } catch (JSONException e) { Log.w(TAG, "failed to get related gid"); @@ -63,20 +91,34 @@ 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数据(禁止调用) + * @return 本地JSON数据(始终抛出异常) + * @throws IllegalAccessError 始终抛出异常,禁止使用该方法 + */ @Override public JSONObject getLocalJSONFromContent() { throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); } + /** + * 获取同步操作类型(禁止调用) + * @param c 数据库游标 + * @return 同步操作类型(始终抛出异常) + * @throws IllegalAccessError 始终抛出异常,禁止使用该方法 + */ @Override public int getSyncAction(Cursor c) { throw new IllegalAccessError("MetaData:getSyncAction should not be called"); } - -} +} \ No newline at end of file diff --git a/java/net/micode/notes/gtask/data/Node.java b/java/net/micode/notes/gtask/data/Node.java index 63950e0..047468e 100644 --- a/java/net/micode/notes/gtask/data/Node.java +++ b/java/net/micode/notes/gtask/data/Node.java @@ -20,33 +20,33 @@ import android.database.Cursor; import org.json.JSONObject; +/** + * Google任务同步节点的抽象基类 + * 定义了同步操作类型常量和节点数据的基本结构 + * 提供了创建、更新、删除等同步操作的抽象方法接口 + * 子类需实现具体的JSON转换和同步逻辑 + */ public abstract class Node { - public static final int SYNC_ACTION_NONE = 0; - - public static final int SYNC_ACTION_ADD_REMOTE = 1; - - 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_LOCAL = 4; - - 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_CONFLICT = 7; - - public static final int SYNC_ACTION_ERROR = 8; - - private String mGid; - - private String mName; - - private long mLastModified; - - private boolean mDeleted; - + // 同步操作类型常量(用于标识不同的同步动作) + public static final int SYNC_ACTION_NONE = 0; // 无同步动作 + public static final int SYNC_ACTION_ADD_REMOTE = 1; // 添加到远程服务器 + 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_LOCAL = 4; // 从本地数据库删除 + 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_CONFLICT = 7; // 同步冲突(需解决) + public static final int SYNC_ACTION_ERROR = 8; // 同步错误 + + // 节点基本属性 + private String mGid; // Google任务全局唯一标识(GID) + private String mName; // 节点名称(如任务标题) + private long mLastModified; // 最后修改时间戳 + private boolean mDeleted; // 是否已删除标志 + + /** + * 默认构造函数,初始化节点基本属性 + */ public Node() { mGid = null; mName = ""; @@ -54,48 +54,109 @@ 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任务GID + * @param gid Google任务全局唯一标识 + */ 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任务GID + * @return Google任务全局唯一标识 + */ 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; } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/gtask/data/SqlData.java b/java/net/micode/notes/gtask/data/SqlData.java index d3ec3be..7329fa1 100644 --- a/java/net/micode/notes/gtask/data/SqlData.java +++ b/java/net/micode/notes/gtask/data/SqlData.java @@ -35,53 +35,59 @@ import org.json.JSONException; import org.json.JSONObject; +/** + * 便签数据操作类,封装本地数据库操作逻辑 + * 负责便签数据的增删改查、JSON序列化与反序列化 + * 支持增量更新和版本验证,确保数据一致性 + */ public class SqlData { private static final String TAG = SqlData.class.getSimpleName(); + // 无效ID标识(用于新建数据对象) private static final int INVALID_ID = -99999; + // 数据查询投影(定义需要查询的字段) 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_MIME_TYPE_COLUMN = 1; - 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_3_COLUMN = 4; - private ContentResolver mContentResolver; - - private boolean mIsCreate; - - private long mDataId; - - private String mDataMimeType; - - private String mDataContent; - - private long mDataContentData1; - - private String mDataContentData3; - - private ContentValues mDiffDataValues; - + // 数据访问与状态管理 + private ContentResolver mContentResolver; // 内容解析器(用于数据库操作) + private boolean mIsCreate; // 是否为新建数据对象 + private long mDataId; // 数据ID + private String mDataMimeType; // MIME类型 + private String mDataContent; // 内容文本 + private long mDataContentData1; // 附加数据1(通常存储数值型数据) + private String mDataContentData3; // 附加数据3(通常存储字符串型数据) + private ContentValues mDiffDataValues; // 差异值集合(存储需要更新的字段) + + /** + * 构造函数(新建数据对象) + * 初始化默认值,设置为新建状态 + */ public SqlData(Context context) { mContentResolver = context.getContentResolver(); mIsCreate = true; mDataId = INVALID_ID; - mDataMimeType = DataConstants.NOTE; + mDataMimeType = DataConstants.NOTE; // 默认MIME类型为普通便签 mDataContent = ""; mDataContentData1 = 0; mDataContentData3 = ""; mDiffDataValues = new ContentValues(); } + /** + * 构造函数(从数据库加载数据) + * 从游标中加载数据,设置为非新建状态 + */ public SqlData(Context context, Cursor c) { mContentResolver = context.getContentResolver(); mIsCreate = false; @@ -89,6 +95,10 @@ public class SqlData { mDiffDataValues = new ContentValues(); } + /** + * 从游标加载数据 + * 用于从查询结果中初始化对象属性 + */ private void loadFromCursor(Cursor c) { mDataId = c.getLong(DATA_ID_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); @@ -97,13 +107,20 @@ public class SqlData { mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); } + /** + * 从JSON对象设置内容 + * 支持增量更新,仅将变化的字段存入差异值集合 + * @param js JSON对象,包含要设置的字段 + */ public void setContent(JSONObject js) throws JSONException { + // 处理ID字段 long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; if (mIsCreate || mDataId != dataId) { mDiffDataValues.put(DataColumns.ID, dataId); } mDataId = dataId; + // 处理MIME类型 String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) : DataConstants.NOTE; if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { @@ -111,18 +128,21 @@ public class SqlData { } mDataMimeType = dataMimeType; + // 处理内容文本 String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; if (mIsCreate || !mDataContent.equals(dataContent)) { mDiffDataValues.put(DataColumns.CONTENT, dataContent); } mDataContent = dataContent; + // 处理附加数据1 long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; if (mIsCreate || mDataContentData1 != dataContentData1) { mDiffDataValues.put(DataColumns.DATA1, dataContentData1); } mDataContentData1 = dataContentData1; + // 处理附加数据3 String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { mDiffDataValues.put(DataColumns.DATA3, dataContentData3); @@ -130,6 +150,11 @@ public class SqlData { mDataContentData3 = dataContentData3; } + /** + * 获取内容的JSON表示 + * 将当前对象属性转换为JSON对象 + * @return 包含当前对象属性的JSON对象 + */ public JSONObject getContent() throws JSONException { if (mIsCreate) { Log.e(TAG, "it seems that we haven't created this in database yet"); @@ -144,30 +169,41 @@ public class SqlData { return js; } + /** + * 提交数据到数据库 + * 根据对象状态执行插入或更新操作 + * @param noteId 关联的便签ID + * @param validateVersion 是否验证版本(用于乐观锁控制) + * @param version 预期的版本号 + */ 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); + 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"); } } else { + // 更新数据处理 if (mDiffDataValues.size() > 0) { int result = 0; if (!validateVersion) { + // 不验证版本的简单更新 result = mContentResolver.update(ContentUris.withAppendedId( Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); } else { + // 验证版本的更新(乐观锁机制) result = mContentResolver.update(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { String.valueOf(noteId), String.valueOf(version) @@ -179,11 +215,16 @@ public class SqlData { } } + // 重置状态 mDiffDataValues.clear(); mIsCreate = false; } + /** + * 获取数据ID + * @return 数据ID + */ public long getId() { return mDataId; } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/gtask/data/SqlNote.java b/java/net/micode/notes/gtask/data/SqlNote.java index 79a4095..f5704dc 100644 --- a/java/net/micode/notes/gtask/data/SqlNote.java +++ b/java/net/micode/notes/gtask/data/SqlNote.java @@ -38,11 +38,18 @@ import org.json.JSONObject; import java.util.ArrayList; +/** + * 便签数据操作类,封装便签的数据库操作逻辑 + * 负责便签的增删改查、JSON数据转换和同步功能 + * 支持便签基本信息和附加数据的管理 + */ public class SqlNote { private static final String TAG = SqlNote.class.getSimpleName(); + // 无效ID标识 private static final int INVALID_ID = -99999; + // 便签查询投影(定义查询的字段) public static final String[] PROJECTION_NOTE = new String[] { NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, @@ -52,130 +59,114 @@ 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; - + // 成员变量 + 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(); mIsCreate = true; mId = INVALID_ID; mAlertDate = 0; - mBgColorId = ResourceParser.getDefaultBgId(context); - mCreatedDate = System.currentTimeMillis(); + mBgColorId = ResourceParser.getDefaultBgId(context); // 设置默认背景色 + mCreatedDate = System.currentTimeMillis(); // 设置当前时间为创建时间 mHasAttachment = 0; - mModifiedDate = System.currentTimeMillis(); - mParentId = 0; + mModifiedDate = System.currentTimeMillis(); // 设置当前时间为修改时间 + mParentId = 0; // 默认父文件夹为根目录 mSnippet = ""; - mType = Notes.TYPE_NOTE; - mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; - mWidgetType = Notes.TYPE_WIDGET_INVALIDE; + mType = Notes.TYPE_NOTE; // 默认类型为便签 + mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; // 无效小部件ID + mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 无效小部件类型 mOriginParent = 0; mVersion = 0; mDiffNoteValues = new ContentValues(); mDataList = new ArrayList(); } + /** + * 构造函数(从数据库游标加载便签数据) + * @param context 应用上下文 + * @param c 包含便签数据的游标 + */ public SqlNote(Context context, Cursor c) { mContext = context; mContentResolver = context.getContentResolver(); mIsCreate = false; - loadFromCursor(c); + loadFromCursor(c); // 从游标加载数据 mDataList = new ArrayList(); if (mType == Notes.TYPE_NOTE) - loadDataContent(); + loadDataContent(); // 加载便签附加数据 mDiffNoteValues = new ContentValues(); } + /** + * 构造函数(根据ID加载便签数据) + * @param context 应用上下文 + * @param id 便签ID + */ public SqlNote(Context context, long id) { mContext = context; mContentResolver = context.getContentResolver(); mIsCreate = false; - loadFromCursor(id); + loadFromCursor(id); // 根据ID加载数据 mDataList = new ArrayList(); if (mType == Notes.TYPE_NOTE) - loadDataContent(); + loadDataContent(); // 加载便签附加数据 mDiffNoteValues = new ContentValues(); - } + /** + * 根据ID从数据库加载便签数据 + * @param id 便签ID + */ private void loadFromCursor(long id) { Cursor c = null; try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", - new String[] { - String.valueOf(id) - }, null); + new String[] {String.valueOf(id)}, null); if (c != null) { c.moveToNext(); - loadFromCursor(c); + loadFromCursor(c); // 从游标加载数据 } else { Log.w(TAG, "loadFromCursor: cursor = null"); } @@ -185,6 +176,10 @@ public class SqlNote { } } + /** + * 从游标加载便签基本信息 + * @param c 包含便签数据的游标 + */ private void loadFromCursor(Cursor c) { mId = c.getLong(ID_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN); @@ -200,14 +195,15 @@ public class SqlNote { mVersion = c.getLong(VERSION_COLUMN); } + /** + * 加载便签附加数据(如富文本内容、附件等) + */ private void loadDataContent() { Cursor c = null; mDataList.clear(); try { c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, - "(note_id=?)", new String[] { - String.valueOf(mId) - }, null); + "(note_id=?)", new String[] {String.valueOf(mId)}, null); if (c != null) { if (c.getCount() == 0) { Log.w(TAG, "it seems that the note has not data"); @@ -226,22 +222,25 @@ public class SqlNote { } } + /** + * 从JSON对象设置便签内容 + * @param js 包含便签数据的JSON对象 + * @return 设置是否成功 + */ 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) : ""; + // 文件夹只能更新名称和类型 + String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : ""; if (mIsCreate || !mSnippet.equals(snippet)) { mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); } mSnippet = snippet; - int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) - : Notes.TYPE_NOTE; + int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE; if (mIsCreate || mType != type) { mDiffNoteValues.put(NoteColumns.TYPE, type); } @@ -254,57 +253,53 @@ public class SqlNote { } mId = id; - long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note - .getLong(NoteColumns.ALERTED_DATE) : 0; + // 设置便签各项属性(带增量更新逻辑) + long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note.getLong(NoteColumns.ALERTED_DATE) : 0; if (mIsCreate || mAlertDate != alertDate) { mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); } mAlertDate = alertDate; - int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note - .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); + int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note.getInt(NoteColumns.BG_COLOR_ID) + : ResourceParser.getDefaultBgId(mContext); if (mIsCreate || mBgColorId != bgColorId) { mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); } mBgColorId = bgColorId; - long createDate = note.has(NoteColumns.CREATED_DATE) ? note - .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); + long createDate = note.has(NoteColumns.CREATED_DATE) ? note.getLong(NoteColumns.CREATED_DATE) + : System.currentTimeMillis(); if (mIsCreate || mCreatedDate != createDate) { mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); } mCreatedDate = createDate; - int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note - .getInt(NoteColumns.HAS_ATTACHMENT) : 0; + int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note.getInt(NoteColumns.HAS_ATTACHMENT) : 0; if (mIsCreate || mHasAttachment != hasAttachment) { mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); } mHasAttachment = hasAttachment; - long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note - .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); + long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note.getLong(NoteColumns.MODIFIED_DATE) + : System.currentTimeMillis(); if (mIsCreate || mModifiedDate != modifiedDate) { mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); } mModifiedDate = modifiedDate; - long parentId = note.has(NoteColumns.PARENT_ID) ? note - .getLong(NoteColumns.PARENT_ID) : 0; + long parentId = note.has(NoteColumns.PARENT_ID) ? note.getLong(NoteColumns.PARENT_ID) : 0; if (mIsCreate || mParentId != parentId) { mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); } mParentId = parentId; - String snippet = note.has(NoteColumns.SNIPPET) ? note - .getString(NoteColumns.SNIPPET) : ""; + String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : ""; if (mIsCreate || !mSnippet.equals(snippet)) { mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); } mSnippet = snippet; - int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) - : Notes.TYPE_NOTE; + int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE; if (mIsCreate || mType != type) { mDiffNoteValues.put(NoteColumns.TYPE, type); } @@ -317,20 +312,20 @@ public class SqlNote { } mWidgetId = widgetId; - int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note - .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; + int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note.getInt(NoteColumns.WIDGET_TYPE) + : Notes.TYPE_WIDGET_INVALIDE; if (mIsCreate || mWidgetType != widgetType) { mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); } mWidgetType = widgetType; - long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note - .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; + long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; if (mIsCreate || mOriginParent != originParent) { mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); } mOriginParent = originParent; + // 处理附加数据 for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); SqlData sqlData = null; @@ -359,6 +354,10 @@ public class SqlNote { return true; } + /** + * 将便签数据转换为JSON对象 + * @return 包含便签数据的JSON对象 + */ public JSONObject getContent() { try { JSONObject js = new JSONObject(); @@ -370,6 +369,7 @@ public class SqlNote { JSONObject note = new JSONObject(); if (mType == Notes.TYPE_NOTE) { + // 构建便签类型的JSON数据 note.put(NoteColumns.ID, mId); note.put(NoteColumns.ALERTED_DATE, mAlertDate); note.put(NoteColumns.BG_COLOR_ID, mBgColorId); @@ -384,6 +384,7 @@ public class SqlNote { note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); js.put(GTaskStringUtils.META_HEAD_NOTE, note); + // 构建附加数据的JSON数组 JSONArray dataArray = new JSONArray(); for (SqlData sqlData : mDataList) { JSONObject data = sqlData.getContent(); @@ -393,6 +394,7 @@ public class SqlNote { } js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { + // 构建文件夹或系统类型的JSON数据 note.put(NoteColumns.ID, mId); note.put(NoteColumns.TYPE, mType); note.put(NoteColumns.SNIPPET, mSnippet); @@ -407,41 +409,77 @@ public class SqlNote { return null; } + /** + * 设置父文件夹ID + * @param id 父文件夹ID + */ public void setParentId(long id) { mParentId = id; mDiffNoteValues.put(NoteColumns.PARENT_ID, id); } + /** + * 设置Google任务ID + * @param gid Google任务ID + */ public void setGtaskId(String gid) { mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); } + /** + * 设置同步ID + * @param syncId 同步ID + */ public void setSyncId(long syncId) { mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); } + /** + * 重置本地修改标识 + */ public void resetLocalModified() { mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); } + /** + * 获取便签ID + * @return 便签ID + */ public long getId() { return mId; } + /** + * 获取父文件夹ID + * @return 父文件夹ID + */ public long getParentId() { return mParentId; } + /** + * 获取便签内容/文件夹名称 + * @return 便签内容/文件夹名称 + */ public String getSnippet() { return mSnippet; } + /** + * 判断是否为便签类型 + * @return 是否为便签类型 + */ public boolean isNoteType() { return mType == Notes.TYPE_NOTE; } + /** + * 提交便签数据到数据库 + * @param validateVersion 是否验证版本(用于乐观锁) + */ public void commit(boolean validateVersion) { if (mIsCreate) { + // 新建便签处理 if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { mDiffNoteValues.remove(NoteColumns.ID); } @@ -457,36 +495,37 @@ public class SqlNote { throw new IllegalStateException("Create thread id failed"); } + // 保存附加数据 if (mType == Notes.TYPE_NOTE) { for (SqlData sqlData : mDataList) { sqlData.commit(mId, false, -1); } } } 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"); } if (mDiffNoteValues.size() > 0) { - mVersion ++; + mVersion++; int result = 0; if (!validateVersion) { + // 不验证版本的更新 result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" - + NoteColumns.ID + "=?)", new String[] { - String.valueOf(mId) - }); + + NoteColumns.ID + "=?)", new String[] {String.valueOf(mId)}); } else { + // 验证版本的更新(乐观锁) result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" - + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", - new String[] { - String.valueOf(mId), String.valueOf(mVersion) - }); + + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", + new String[] {String.valueOf(mId), String.valueOf(mVersion)}); } if (result == 0) { Log.w(TAG, "there is no update. maybe user updates note when syncing"); } } + // 更新附加数据 if (mType == Notes.TYPE_NOTE) { for (SqlData sqlData : mDataList) { sqlData.commit(mId, validateVersion, mVersion); @@ -494,7 +533,7 @@ public class SqlNote { } } - // refresh local info + // 刷新本地数据 loadFromCursor(mId); if (mType == Notes.TYPE_NOTE) loadDataContent(); @@ -502,4 +541,4 @@ public class SqlNote { mDiffNoteValues.clear(); mIsCreate = false; } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/gtask/data/Task.java b/java/net/micode/notes/gtask/data/Task.java index 6a19454..46220cc 100644 --- a/java/net/micode/notes/gtask/data/Task.java +++ b/java/net/micode/notes/gtask/data/Task.java @@ -32,19 +32,27 @@ import org.json.JSONException; import org.json.JSONObject; +/** + * Google任务数据模型类,继承自Node抽象基类 + * 用于表示Google任务及其同步操作,实现了任务的创建、更新和同步逻辑 + */ 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; + /** + * 构造函数,初始化任务对象的默认状态 + */ public Task() { super(); mCompleted = false; @@ -54,21 +62,26 @@ public class Task extends Node { mMetaInfo = null; } + /** + * 获取创建任务的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, mParent.getChildTaskIndex(this)); - // entity_delta + // 设置任务实体信息 JSONObject entity = new JSONObject(); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); @@ -79,17 +92,17 @@ public class Task extends Node { } js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - // parent_id + // 设置父级任务列表ID js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); - // dest_parent_type + // 设置目标父级类型为任务组 js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, GTaskStringUtils.GTASK_JSON_TYPE_GROUP); - // list_id + // 设置任务列表ID js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); - // prior_sibling_id + // 设置前一个兄弟任务ID(如果有) if (mPriorSibling != null) { js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); } @@ -103,21 +116,26 @@ public class Task 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()); if (getNotes() != null) { @@ -135,35 +153,39 @@ public class Task 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)); } - // notes + // 设置任务备注 if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); } - // deleted + // 设置删除状态 if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); } - // completed + // 设置完成状态 if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); } @@ -175,6 +197,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)) { @@ -182,14 +208,17 @@ public class Task extends Node { } try { + // 解析便签信息和数据数组 JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + // 验证便签类型 if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { Log.e(TAG, "invalid type"); return; } + // 从数据数组中获取任务名称 for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { @@ -204,16 +233,21 @@ public class Task extends Node { } } + /** + * 从任务内容生成本地JSON数据 + * @return 包含本地任务数据的JSON对象 + */ public JSONObject getLocalJSONFromContent() { String name = getName(); try { if (mMetaInfo == null) { - // new task created from web + // 处理从网络创建的新任务 if (name == null) { Log.w(TAG, "the note seems to be an empty one"); return null; } + // 构建新任务的JSON结构 JSONObject js = new JSONObject(); JSONObject note = new JSONObject(); JSONArray dataArray = new JSONArray(); @@ -225,10 +259,11 @@ public class Task extends Node { js.put(GTaskStringUtils.META_HEAD_NOTE, note); return js; } else { - // synced task + // 处理已同步的任务 JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + // 更新任务名称 for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { @@ -237,6 +272,7 @@ public class Task extends Node { } } + // 设置便签类型并返回元数据 note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); return mMetaInfo; } @@ -247,6 +283,10 @@ public class Task extends Node { } } + /** + * 设置任务元数据信息 + * @param metaData 元数据对象 + */ public void setMetaInfo(MetaData metaData) { if (metaData != null && metaData.getNotes() != null) { try { @@ -258,9 +298,15 @@ public class Task extends Node { } } + /** + * 获取任务同步操作类型 + * @param c 数据库游标 + * @return 同步操作类型常量 + */ public int getSyncAction(Cursor c) { try { JSONObject noteInfo = null; + // 从元数据中获取便签信息 if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); } @@ -270,36 +316,38 @@ public class Task extends Node { return SYNC_ACTION_UPDATE_REMOTE; } + // 验证便签ID if (!noteInfo.has(NoteColumns.ID)) { Log.w(TAG, "remote note id seems to be deleted"); return SYNC_ACTION_UPDATE_LOCAL; } - // validate the note id now if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { Log.w(TAG, "note id doesn't match"); return SYNC_ACTION_UPDATE_LOCAL; } + // 判断本地修改状态 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 { + // 同步冲突 return SYNC_ACTION_UPDATE_CONFLICT; } } @@ -311,11 +359,17 @@ public class Task extends Node { return SYNC_ACTION_ERROR; } + /** + * 判断任务是否值得保存 + * @return 是否值得保存 + */ public boolean isWorthSaving() { return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) || (getNotes() != null && getNotes().trim().length() > 0); } + // 以下为属性的getter和setter方法 + public void setCompleted(boolean completed) { this.mCompleted = completed; } @@ -347,5 +401,4 @@ public class Task extends Node { public TaskList getParent() { return this.mParent; } - -} +} \ No newline at end of file diff --git a/java/net/micode/notes/gtask/data/TaskList.java b/java/net/micode/notes/gtask/data/TaskList.java index 4ea21c5..3c55dd3 100644 --- a/java/net/micode/notes/gtask/data/TaskList.java +++ b/java/net/micode/notes/gtask/data/TaskList.java @@ -29,35 +29,47 @@ import org.json.JSONObject; import java.util.ArrayList; - +/** + * Google任务列表数据模型类,继承自Node抽象基类 + * 用于表示Google任务列表及其同步操作,管理子任务集合 + */ public class TaskList extends Node { private static final String TAG = TaskList.class.getSimpleName(); + // 任务列表在父容器中的索引位置 private int mIndex; - + // 子任务集合 private ArrayList mChildren; + /** + * 构造函数,初始化任务列表对象 + */ 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 +86,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 +120,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 +150,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 +162,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,16 +183,23 @@ 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(), folderName.length()); folder.put(NoteColumns.SNIPPET, folderName); + + // 根据名称确定文件夹类型 if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); @@ -183,28 +216,34 @@ 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 +255,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 +282,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 +298,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 +314,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 +326,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 +340,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()) { @@ -296,9 +361,16 @@ public class TaskList extends Node { if (pos == index) return true; + + // 通过先移除再添加实现移动 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 +381,20 @@ public class TaskList extends Node { return null; } + /** + * 获取子任务在列表中的索引位置 + * @param task 要查找的任务 + * @return 任务索引,未找到则返回-1 + */ public int getChildTaskIndex(Task task) { return mChildren.indexOf(task); } + /** + * 根据索引获取子任务 + * @param index 任务索引 + * @return 指定索引的任务,索引无效则返回null + */ public Task getChildTaskByIndex(int index) { if (index < 0 || index >= mChildren.size()) { Log.e(TAG, "getTaskByIndex: invalid index"); @@ -321,6 +403,11 @@ public class TaskList extends Node { return mChildren.get(index); } + /** + * 根据GID获取子任务(另一种实现方式) + * @param gid 任务GID + * @return 找到的任务,未找到则返回null + */ public Task getChilTaskByGid(String gid) { for (Task task : mChildren) { if (task.getGid().equals(gid)) @@ -329,15 +416,27 @@ 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; } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/gtask/exception/ActionFailureException.java b/java/net/micode/notes/gtask/exception/ActionFailureException.java index 15504be..1b10b42 100644 --- a/java/net/micode/notes/gtask/exception/ActionFailureException.java +++ b/java/net/micode/notes/gtask/exception/ActionFailureException.java @@ -16,18 +16,35 @@ package net.micode.notes.gtask.exception; +/** + * Google任务同步操作失败异常 + * 继承自RuntimeException,用于在任务同步过程中出现错误时抛出 + */ public class ActionFailureException extends RuntimeException { + // 序列化版本UID,确保序列化和反序列化的兼容性 private static final long serialVersionUID = 4425249765923293627L; + /** + * 默认构造函数 + */ public ActionFailureException() { super(); } + /** + * 使用错误消息创建异常 + * @param paramString 错误消息 + */ public ActionFailureException(String paramString) { super(paramString); } + /** + * 使用错误消息和原始异常创建异常 + * @param paramString 错误消息 + * @param paramThrowable 原始异常 + */ public ActionFailureException(String paramString, Throwable paramThrowable) { super(paramString, paramThrowable); } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/java/net/micode/notes/gtask/remote/GTaskASyncTask.java index f471044..b20e7b8 100644 --- a/java/net/micode/notes/gtask/remote/GTaskASyncTask.java +++ b/java/net/micode/notes/gtask/remote/GTaskASyncTask.java @@ -1,4 +1,3 @@ - /* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * @@ -29,100 +28,159 @@ import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesPreferenceActivity; +/** + * Google任务同步异步任务类 + * 负责在后台执行Google任务同步操作,并通过通知反馈同步状态 + * 继承自AsyncTask,实现异步操作与UI线程的交互 + */ 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任务管理器实例 private GTaskManager mTaskManager; - + // 同步完成监听器 private OnCompleteListener mOnCompleteListener; + /** + * 构造函数 + * @param context 应用上下文 + * @param listener 同步完成监听器 + */ public GTaskASyncTask(Context context, OnCompleteListener listener) { mContext = context; mOnCompleteListener = listener; + // 获取通知管理器实例 mNotifiManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); + // 获取Google任务管理器单例实例 mTaskManager = GTaskManager.getInstance(); } + /** + * 取消同步操作 + */ public void cancelSync() { mTaskManager.cancelSync(); } + /** + * 发布同步进度消息 + * @param message 进度消息内容 + */ public void publishProgess(String message) { publishProgress(new String[] { - message + message }); } + /** + * 显示同步状态通知 + * @param tickerId 通知标题资源ID + * @param content 通知内容 + */ private void showNotification(int tickerId, String content) { PendingIntent pendingIntent; + // 根据同步结果设置不同的点击跳转意图 if (tickerId != R.string.ticker_success) { + // 同步失败或进行中时跳转到设置页面 pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE); - } else { + // 同步成功时跳转到便签列表页面 pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE); } - // Use modern notification builder (API 21+ support) + // 构建通知对象(使用现代通知构建器) Notification notification = new Notification.Builder(mContext) - .setContentTitle(mContext.getString(R.string.app_name)) - .setContentText(content) - .setContentIntent(pendingIntent) - .setSmallIcon(R.drawable.notification) - .setDefaults(Notification.DEFAULT_LIGHTS) - .setAutoCancel(true) - .build(); - + .setContentTitle(mContext.getString(R.string.app_name)) // 设置通知标题 + .setContentText(content) // 设置通知内容 + .setContentIntent(pendingIntent) // 设置点击通知后的跳转意图 + .setSmallIcon(R.drawable.notification) // 设置通知小图标 + .setDefaults(Notification.DEFAULT_LIGHTS) // 设置通知默认灯光效果 + .setAutoCancel(true) // 设置通知点击后自动取消 + .build(); // 构建通知对象 + + // 显示通知 mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); } + /** + * 后台执行同步操作(异步任务核心方法) + * @param unused 未使用的参数 + * @return 同步结果状态码 + */ @Override protected Integer doInBackground(Void... unused) { + // 发布同步开始的进度消息 publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity .getSyncAccountName(mContext))); + // 执行Google任务同步并返回结果 return mTaskManager.sync(mContext, this); } + /** + * 更新同步进度(在UI线程执行) + * @param progress 进度消息数组 + */ @Override protected void onProgressUpdate(String... progress) { + // 显示同步中的通知 showNotification(R.string.ticker_syncing, progress[0]); + // 如果上下文是同步服务,则发送广播通知进度 if (mContext instanceof GTaskSyncService) { ((GTaskSyncService) mContext).sendBroadcast(progress[0]); } } + /** + * 同步完成后的处理(在UI线程执行) + * @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)); } + // 通知监听器同步完成(在新线程中执行,避免阻塞UI线程) if (mOnCompleteListener != null) { new Thread(new Runnable() { - public void run() { mOnCompleteListener.onComplete(); } }).start(); } } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/gtask/remote/GTaskClient.java b/java/net/micode/notes/gtask/remote/GTaskClient.java index c67dfdf..81b882d 100644 --- a/java/net/micode/notes/gtask/remote/GTaskClient.java +++ b/java/net/micode/notes/gtask/remote/GTaskClient.java @@ -61,35 +61,40 @@ import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; +/** + * Google任务客户端类,提供与Google Tasks API交互的功能 + * 负责处理与Google Tasks的登录认证、任务和任务列表的增删改查操作 + * 采用单例模式确保全局唯一实例 + */ public class GTaskClient { private static final String TAG = GTaskClient.class.getSimpleName(); + // Google Tasks API基本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; - 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 +107,10 @@ public class GTaskClient { mUpdateArray = null; } + /** + * 获取GTaskClient单例实例 + * @return GTaskClient实例 + */ public static synchronized GTaskClient getInstance() { if (mInstance == null) { mInstance = new GTaskClient(); @@ -109,18 +118,21 @@ public class GTaskClient { return mInstance; } + /** + * 登录Google账户并获取Tasks访问权限 + * @param 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))) { + // 账户切换后需要重新登录 + if (mLoggedin && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity + .getSyncAccountName(activity))) { mLoggedin = false; } @@ -136,7 +148,7 @@ public class GTaskClient { return false; } - // login with custom domain if necessary + // 处理自定义域名账户 if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() .endsWith("googlemail.com"))) { StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); @@ -151,7 +163,7 @@ public class GTaskClient { } } - // try to login with google official url + // 尝试使用Google官方URL登录 if (!mLoggedin) { mGetUrl = GTASK_GET_URL; mPostUrl = GTASK_POST_URL; @@ -164,6 +176,12 @@ public class GTaskClient { return true; } + /** + * 登录Google账户获取认证令牌 + * @param activity 活动上下文 + * @param invalidateToken 是否失效现有令牌 + * @return 认证令牌,失败时返回null + */ private String loginGoogleAccount(Activity activity, boolean invalidateToken) { String authToken; AccountManager accountManager = AccountManager.get(activity); @@ -174,6 +192,7 @@ public class GTaskClient { return null; } + // 获取设置中的同步账户 String accountName = NotesPreferenceActivity.getSyncAccountName(activity); Account account = null; for (Account a : accounts) { @@ -189,7 +208,7 @@ public class GTaskClient { return null; } - // get the token now + // 获取认证令牌 AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile", null, activity, null, null); try { @@ -207,10 +226,15 @@ public class GTaskClient { return authToken; } + /** + * 尝试登录Google Tasks服务 + * @param activity 活动上下文 + * @param authToken 认证令牌 + * @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 + // 令牌可能过期,失效后重试 authToken = loginGoogleAccount(activity, true); if (authToken == null) { Log.e(TAG, "login google account failed"); @@ -225,6 +249,11 @@ public class GTaskClient { return true; } + /** + * 使用认证令牌登录Google Tasks + * @param authToken 认证令牌 + * @return 登录是否成功 + */ private boolean loginGtask(String authToken) { int timeoutConnection = 10000; int timeoutSocket = 15000; @@ -236,14 +265,14 @@ public class GTaskClient { mHttpClient.setCookieStore(localBasicCookieStore); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); - // login gtask + // 执行登录请求 try { String loginUrl = mGetUrl + "?auth=" + authToken; HttpGet httpGet = new HttpGet(loginUrl); HttpResponse response = null; response = mHttpClient.execute(httpGet); - // get the cookie now + // 检查认证Cookie List cookies = mHttpClient.getCookieStore().getCookies(); boolean hasAuthCookie = false; for (Cookie cookie : cookies) { @@ -255,7 +284,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 +301,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 +308,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 +327,12 @@ public class GTaskClient { return httpPost; } + /** + * 从HTTP实体中获取响应内容 + * @param entity HTTP实体 + * @return 响应内容字符串 + * @throws IOException 读取内容时发生的异常 + */ private String getResponseContent(HttpEntity entity) throws IOException { String contentEncoding = null; if (entity.getContentEncoding() != null) { @@ -299,6 +341,7 @@ public class GTaskClient { } InputStream input = entity.getContent(); + // 处理压缩响应 if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { input = new GZIPInputStream(entity.getContent()); } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { @@ -323,6 +366,12 @@ public class GTaskClient { } } + /** + * 发送POST请求并获取JSON响应 + * @param js 请求JSON对象 + * @return 响应JSON对象 + * @throws NetworkFailureException 网络错误时抛出 + */ private JSONObject postRequest(JSONObject js) throws NetworkFailureException { if (!mLoggedin) { Log.e(TAG, "please login first"); @@ -336,7 +385,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 +409,25 @@ public class GTaskClient { } } + /** + * 创建新的Google任务 + * @param task 要创建的任务对象 + * @throws NetworkFailureException 网络错误时抛出 + */ public void createTask(Task task) throws NetworkFailureException { commitUpdate(); try { JSONObject jsPost = new JSONObject(); JSONArray actionList = new JSONArray(); - // action_list + // 添加创建任务的操作到动作列表 actionList.put(task.getCreateAction(getActionId())); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - // client_version + // 设置客户端版本 jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - // post + // 发送请求并处理响应 JSONObject jsResponse = postRequest(jsPost); JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( GTaskStringUtils.GTASK_JSON_RESULTS).get(0); @@ -386,20 +440,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 + // 添加创建任务列表的操作到动作列表 actionList.put(tasklist.getCreateAction(getActionId())); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - // client version + // 设置客户端版本 jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - // post + // 发送请求并处理响应 JSONObject jsResponse = postRequest(jsPost); JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( GTaskStringUtils.GTASK_JSON_RESULTS).get(0); @@ -412,15 +471,19 @@ public class GTaskClient { } } + /** + * 提交批量更新操作 + * @throws NetworkFailureException 网络错误时抛出 + */ public void commitUpdate() throws NetworkFailureException { if (mUpdateArray != null) { try { JSONObject jsPost = new JSONObject(); - // action_list + // 添加更新操作列表 jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); - // client_version + // 设置客户端版本 jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); postRequest(jsPost); @@ -433,10 +496,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 +514,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 +529,25 @@ public class GTaskClient { JSONArray actionList = new JSONArray(); JSONObject action = new JSONObject(); - // action_list + // 构建移动任务的操作 action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); if (preParent == curParent && task.getPriorSibling() != null) { - // put prioring_sibing_id only if moving within the tasklist and - // it is not the first one - action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); + // 仅在任务列表内移动且不是第一个时设置前一个兄弟任务 + action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling().getGid()); } action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); if (preParent != curParent) { - // put the dest_list only if moving between tasklists + // 在任务列表间移动时设置目标列表 action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); } actionList.put(action); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - // client_version + // 设置客户端版本 jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); postRequest(jsPost); @@ -486,18 +559,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 + // 标记节点为已删除并添加到动作列表 node.setDeleted(true); actionList.put(node.getUpdateAction(getActionId())); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - // client_version + // 设置客户端版本 jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); postRequest(jsPost); @@ -509,6 +587,11 @@ public class GTaskClient { } } + /** + * 获取所有任务列表 + * @return 任务列表JSON数组 + * @throws NetworkFailureException 网络错误时抛出 + */ public JSONArray getTaskLists() throws NetworkFailureException { if (!mLoggedin) { Log.e(TAG, "please login first"); @@ -520,7 +603,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 +630,12 @@ public class GTaskClient { } } + /** + * 获取指定任务列表中的所有任务 + * @param listGid 任务列表GID + * @return 任务JSON数组 + * @throws NetworkFailureException 网络错误时抛出 + */ public JSONArray getTaskList(String listGid) throws NetworkFailureException { commitUpdate(); try { @@ -554,7 +643,7 @@ public class GTaskClient { JSONArray actionList = new JSONArray(); JSONObject action = new JSONObject(); - // action_list + // 构建获取任务列表的操作 action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); @@ -563,7 +652,7 @@ public class GTaskClient { actionList.put(action); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - // client_version + // 设置客户端版本 jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); JSONObject jsResponse = postRequest(jsPost); @@ -575,11 +664,18 @@ public class GTaskClient { } } + /** + * 获取当前同步账户 + * @return 同步账户对象 + */ public Account getSyncAccount() { return mAccount; } + /** + * 重置更新操作队列 + */ public void resetUpdateArray() { mUpdateArray = null; } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/gtask/remote/GTaskManager.java b/java/net/micode/notes/gtask/remote/GTaskManager.java index d2b4082..b2f4213 100644 --- a/java/net/micode/notes/gtask/remote/GTaskManager.java +++ b/java/net/micode/notes/gtask/remote/GTaskManager.java @@ -48,45 +48,46 @@ import java.util.Iterator; import java.util.Map; +/** + * Google任务同步管理类 + * 核心功能:协调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; + // 同步状态枚举常量(使用int类型实现状态机) + 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; + // 单例实例引用(volatile确保可见性,synchronized保证线程安全) + private static volatile 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; - + // 同步状态控制标志(原子操作保证线程安全) + private volatile boolean mSyncing; + private volatile boolean mCancelled; + + // 数据映射集合(使用泛型HashMap实现高效查找) + private HashMap mGTaskListHashMap; // Google任务列表映射(GID -> TaskList) + private HashMap mGTaskHashMap; // Google任务映射(GID -> Node) + private HashMap mMetaHashMap; // 元数据映射(GID -> MetaData) + private TaskList mMetaList; // 元数据任务列表(存储同步元信息) + private HashSet mLocalDeleteIdMap; // 本地删除记录ID集合 + private HashMap mGidToNid; // GID到本地ID的映射 + private HashMap mNidToGid; // 本地ID到GID的映射 + + /** + * 私有构造函数(单例模式核心) + * 初始化数据结构并设置默认状态 + */ private GTaskManager() { mSyncing = false; mCancelled = false; @@ -99,6 +100,10 @@ public class GTaskManager { mNidToGid = new HashMap(); } + /** + * 获取单例实例(双重检查锁定模式) + * @return GTaskManager唯一实例 + */ public static synchronized GTaskManager getInstance() { if (mInstance == null) { mInstance = new GTaskManager(); @@ -106,43 +111,50 @@ public class GTaskManager { return mInstance; } + /** + * 设置活动上下文(用于获取账户认证令牌) + * @param activity 调用方Activity上下文 + */ public synchronized void setActivityContext(Activity activity) { - // used for getting authtoken mActivity = activity; } + /** + * 执行Google任务同步主流程 + * @param context 应用上下文 + * @param asyncTask 异步任务(用于更新UI进度) + * @return 同步状态码(参考STATE_常量) + */ public int sync(Context context, GTaskASyncTask asyncTask) { + // 同步状态检查(避免并发执行) if (mSyncing) { Log.d(TAG, "Sync is in progress"); return STATE_SYNC_IN_PROGRESS; } + + // 初始化上下文和状态 mContext = context; mContentResolver = mContext.getContentResolver(); mSyncing = true; mCancelled = false; - mGTaskListHashMap.clear(); - mGTaskHashMap.clear(); - mMetaHashMap.clear(); - mLocalDeleteIdMap.clear(); - mGidToNid.clear(); - mNidToGid.clear(); + clearAllMappings(); // 清空旧映射数据 try { GTaskClient client = GTaskClient.getInstance(); client.resetUpdateArray(); - // login google task + // 1. 登录Google任务服务 if (!mCancelled) { if (!client.login(mActivity)) { throw new NetworkFailureException("login google task failed"); } } - // get the task list from google + // 2. 初始化远程任务列表(UI进度更新) asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); initGTaskList(); - // do content sync work + // 3. 执行内容同步(核心逻辑) asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); syncContent(); } catch (NetworkFailureException e) { @@ -156,38 +168,48 @@ public class GTaskManager { e.printStackTrace(); return STATE_INTERNAL_ERROR; } finally { - mGTaskListHashMap.clear(); - mGTaskHashMap.clear(); - mMetaHashMap.clear(); - mLocalDeleteIdMap.clear(); - mGidToNid.clear(); - mNidToGid.clear(); + clearAllMappings(); // 清理资源 mSyncing = false; } return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; } + /** + * 清空所有数据映射(辅助方法) + */ + private void clearAllMappings() { + mGTaskListHashMap.clear(); + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + } + + /** + * 从Google服务器初始化任务列表 + * @throws NetworkFailureException 网络请求失败时抛出 + */ private void initGTaskList() throws NetworkFailureException { - if (mCancelled) - return; + if (mCancelled) return; GTaskClient client = GTaskClient.getInstance(); try { JSONArray jsTaskLists = client.getTaskLists(); - // init meta list first + // 初始化元数据列表(存储同步元信息) mMetaList = null; for (int i = 0; i < jsTaskLists.length(); i++) { JSONObject object = jsTaskLists.getJSONObject(i); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); - if (name - .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { + // 识别元数据专用文件夹 + if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { mMetaList = new TaskList(); mMetaList.setContentByRemoteJSON(object); - // load meta data + // 加载元数据任务 JSONArray jsMetas = client.getTaskList(gid); for (int j = 0; j < jsMetas.length(); j++) { object = (JSONObject) jsMetas.getJSONObject(j); @@ -203,29 +225,28 @@ public class GTaskManager { } } - // create meta list if not existed + // 不存在则创建元数据列表 if (mMetaList == null) { mMetaList = new TaskList(); - mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META); + mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META); GTaskClient.getInstance().createTaskList(mMetaList); } - // init task list + // 初始化普通任务列表 for (int i = 0; i < jsTaskLists.length(); i++) { JSONObject object = jsTaskLists.getJSONObject(i); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); + // 过滤应用专用文件夹 if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) - && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META)) { + && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { TaskList tasklist = new TaskList(); tasklist.setContentByRemoteJSON(object); mGTaskListHashMap.put(gid, tasklist); mGTaskHashMap.put(gid, tasklist); - // load tasks + // 加载任务列表中的任务 JSONArray jsTasks = client.getTaskList(gid); for (int j = 0; j < jsTasks.length(); j++) { object = (JSONObject) jsTasks.getJSONObject(j); @@ -247,6 +268,10 @@ public class GTaskManager { } } + /** + * 执行任务内容同步(核心逻辑) + * @throws NetworkFailureException 网络错误时抛出 + */ private void syncContent() throws NetworkFailureException { int syncType; Cursor c = null; @@ -259,7 +284,7 @@ public class GTaskManager { return; } - // for local deleted note + // 1. 处理本地已删除的便签 try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(type<>? AND parent_id=?)", new String[] { @@ -286,10 +311,10 @@ public class GTaskManager { } } - // sync folder first + // 2. 同步文件夹(先于普通任务同步) syncFolder(); - // for note existing in database + // 3. 处理数据库中存在的便签 try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(type=? AND parent_id<>?)", new String[] { @@ -305,11 +330,10 @@ public class GTaskManager { mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); 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 +350,7 @@ public class GTaskManager { } } - // go through remaining items + // 4. 处理剩余的远程任务(本地不存在的远程任务) Iterator> iter = mGTaskHashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = iter.next(); @@ -334,23 +358,24 @@ 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 + // 5. 批量删除本地标记为删除的记录 if (!mCancelled) { if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { throw new ActionFailureException("failed to batch-delete local deleted notes"); } } - // refresh local sync id + // 6. 刷新本地同步ID(更新最后同步时间) if (!mCancelled) { GTaskClient.getInstance().commitUpdate(); refreshLocalSyncId(); } - } + /** + * 同步文件夹(包含系统文件夹和用户自定义文件夹) + * @throws NetworkFailureException 网络错误时抛出 + */ private void syncFolder() throws NetworkFailureException { Cursor c = null; String gid; @@ -361,7 +386,7 @@ public class GTaskManager { return; } - // for root folder + // 1. 处理根文件夹(系统文件夹) try { c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); @@ -373,9 +398,8 @@ public class GTaskManager { mGTaskHashMap.remove(gid); mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); - // for system folder, only update remote name if necessary - if (!node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) + // 仅在名称变更时更新远程 + if (!node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); } else { doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); @@ -390,12 +414,10 @@ public class GTaskManager { } } - // for call-note folder + // 2. 处理通话记录文件夹(系统文件夹) try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", - new String[] { - String.valueOf(Notes.ID_CALL_RECORD_FOLDER) - }, null); + new String[] {String.valueOf(Notes.ID_CALL_RECORD_FOLDER)}, null); if (c != null) { if (c.moveToNext()) { gid = c.getString(SqlNote.GTASK_ID_COLUMN); @@ -404,11 +426,8 @@ public class GTaskManager { mGTaskHashMap.remove(gid); mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); - // for system folder, only update remote name if - // necessary - if (!node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_CALL_NOTE)) + // 仅在名称变更时更新远程 + if (!node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); } else { doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); @@ -424,7 +443,7 @@ public class GTaskManager { } } - // for local existing folders + // 3. 处理用户自定义文件夹 try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(type=? AND parent_id<>?)", new String[] { @@ -440,11 +459,10 @@ public class GTaskManager { mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); 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 +478,7 @@ public class GTaskManager { } } - // for remote add folders + // 4. 处理远程新增的文件夹(本地不存在的远程文件夹) Iterator> iter = mGTaskListHashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = iter.next(); @@ -476,6 +494,13 @@ public class GTaskManager { GTaskClient.getInstance().commitUpdate(); } + /** + * 执行具体的内容同步操作(状态机核心) + * @param syncType 同步操作类型(来自Node类定义) + * @param node 要同步的节点(Task或TaskList) + * @param c 数据库游标(可选,用于本地数据获取) + * @throws NetworkFailureException 网络错误时抛出 + */ private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -510,8 +535,7 @@ public class GTaskManager { updateRemoteNode(node, c); break; case Node.SYNC_ACTION_UPDATE_CONFLICT: - // merging both modifications maybe a good idea - // right now just use local update simply + // 冲突处理策略:当前简单使用本地更新覆盖远程 updateRemoteNode(node, c); break; case Node.SYNC_ACTION_NONE: @@ -522,6 +546,11 @@ public class GTaskManager { } } + /** + * 添加本地节点到远程服务器 + * @param node 要添加的节点(Task或TaskList) + * @throws NetworkFailureException 网络错误时抛出 + */ private void addLocalNode(Node node) throws NetworkFailureException { if (mCancelled) { return; @@ -529,27 +558,28 @@ public class GTaskManager { SqlNote sqlNote; if (node instanceof TaskList) { - if (node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { + // 处理系统文件夹特殊逻辑 + if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); - } else if (node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { + } else if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); } else { + // 普通文件夹创建 sqlNote = new SqlNote(mContext); sqlNote.setContent(node.getLocalJSONFromContent()); sqlNote.setParentId(Notes.ID_ROOT_FOLDER); } } else { + // 普通任务创建 sqlNote = new SqlNote(mContext); JSONObject js = node.getLocalJSONFromContent(); try { + // 处理ID冲突(避免本地ID与远程重复) if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); 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 note.remove(NoteColumns.ID); } } @@ -562,13 +592,10 @@ public class GTaskManager { if (data.has(DataColumns.ID)) { long dataId = data.getLong(DataColumns.ID); if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { - // the data id is not available, have to create - // a new one data.remove(DataColumns.ID); } } } - } } catch (JSONException e) { Log.w(TAG, e.toString()); @@ -576,6 +603,7 @@ public class GTaskManager { } sqlNote.setContent(js); + // 解析任务父级关系 Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); if (parentId == null) { Log.e(TAG, "cannot find task's parent id locally"); @@ -584,28 +612,35 @@ public class GTaskManager { sqlNote.setParentId(parentId.longValue()); } - // create the local node + // 提交本地数据库记录 sqlNote.setGtaskId(node.getGid()); sqlNote.commit(false); - // update gid-nid mapping + // 更新ID映射关系 mGidToNid.put(node.getGid(), sqlNote.getId()); mNidToGid.put(sqlNote.getId(), node.getGid()); - // update meta + // 更新元数据(同步辅助信息) updateRemoteMeta(node.getGid(), sqlNote); } + /** + * 更新本地节点数据 + * @param node 要更新的节点 + * @param c 数据库游标(包含旧数据) + * @throws NetworkFailureException 网络错误时抛出 + */ private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; } SqlNote sqlNote; - // update the note locally + // 从游标加载旧数据 sqlNote = new SqlNote(mContext, c); sqlNote.setContent(node.getLocalJSONFromContent()); + // 解析新的父级关系 Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) : new Long(Notes.ID_ROOT_FOLDER); if (parentId == null) { @@ -615,10 +650,16 @@ public class GTaskManager { sqlNote.setParentId(parentId.longValue()); sqlNote.commit(true); - // update meta info + // 更新元数据 updateRemoteMeta(node.getGid(), sqlNote); } + /** + * 添加远程节点到本地数据库 + * @param node 要添加的远程节点 + * @param c 数据库游标(可选,用于更新已有记录) + * @throws NetworkFailureException 网络错误时抛出 + */ private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -627,11 +668,12 @@ public class GTaskManager { SqlNote sqlNote = new SqlNote(mContext, c); Node n; - // update remotely + // 区分任务和文件夹处理逻辑 if (sqlNote.isNoteType()) { Task task = new Task(); task.setContentByLocalJSON(sqlNote.getContent()); + // 解析父级任务列表 String parentGid = mNidToGid.get(sqlNote.getParentId()); if (parentGid == null) { Log.e(TAG, "cannot find task's parent tasklist"); @@ -639,15 +681,16 @@ public class GTaskManager { } mGTaskListHashMap.get(parentGid).addChildTask(task); + // 调用远程API创建任务 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; @@ -656,6 +699,7 @@ public class GTaskManager { else folderName += sqlNote.getSnippet(); + // 查找是否已存在同名文件夹 Iterator> iter = mGTaskListHashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = iter.next(); @@ -671,7 +715,7 @@ public class GTaskManager { } } - // no match we can add now + // 不存在则创建新文件夹 if (tasklist == null) { tasklist = new TaskList(); tasklist.setContentByLocalJSON(sqlNote.getContent()); @@ -681,17 +725,23 @@ public class GTaskManager { n = (Node) tasklist; } - // update local note + // 更新本地数据库记录 sqlNote.setGtaskId(n.getGid()); sqlNote.commit(false); sqlNote.resetLocalModified(); sqlNote.commit(true); - // gid-id mapping + // 更新ID映射关系 mGidToNid.put(n.getGid(), sqlNote.getId()); mNidToGid.put(sqlNote.getId(), n.getGid()); } + /** + * 更新远程节点数据 + * @param node 要更新的节点 + * @param c 数据库游标(包含本地数据) + * @throws NetworkFailureException 网络错误时抛出 + */ private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -699,18 +749,19 @@ public class GTaskManager { SqlNote sqlNote = new SqlNote(mContext, c); - // update remotely + // 调用远程API更新节点 node.setContentByLocalJSON(sqlNote.getContent()); GTaskClient.getInstance().addUpdateNode(node); - // update meta + // 更新元数据 updateRemoteMeta(node.getGid(), sqlNote); - // move task if necessary + // 处理任务移动场景 if (sqlNote.isNoteType()) { Task task = (Task) node; TaskList preParentList = task.getParent(); + // 解析新的父级任务列表 String curParentGid = mNidToGid.get(sqlNote.getParentId()); if (curParentGid == null) { Log.e(TAG, "cannot find task's parent tasklist"); @@ -718,6 +769,7 @@ public class GTaskManager { } TaskList curParentList = mGTaskListHashMap.get(curParentGid); + // 执行任务移动操作 if (preParentList != curParentList) { preParentList.removeChildTask(task); curParentList.addChildTask(task); @@ -725,18 +777,26 @@ public class GTaskManager { } } - // clear local modified flag + // 清除本地修改标记 sqlNote.resetLocalModified(); sqlNote.commit(true); } + /** + * 更新远程元数据(同步辅助数据(同步辅助信息) + * @param gid 任务GID + * @param sqlNote 本地便签对象 + * @throws NetworkFailureException 网络错误时抛出 + */ private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { if (sqlNote != null && sqlNote.isNoteType()) { MetaData metaData = mMetaHashMap.get(gid); if (metaData != null) { + // 更新已有元数据 metaData.setMeta(gid, sqlNote.getContent()); GTaskClient.getInstance().addUpdateNode(metaData); } else { + // 创建新元数据 metaData = new MetaData(); metaData.setMeta(gid, sqlNote.getContent()); mMetaList.addChildTask(metaData); @@ -746,12 +806,16 @@ public class GTaskManager { } } + /** + * 刷新本地同步ID(更新最后同步时间戳) + * @throws NetworkFailureException 网络错误时抛出 + */ private void refreshLocalSyncId() throws NetworkFailureException { if (mCancelled) { return; } - // get the latest gtask list + // 重新获取最新远程任务列表 mGTaskHashMap.clear(); mGTaskListHashMap.clear(); mMetaHashMap.clear(); @@ -775,8 +839,7 @@ public class GTaskManager { c.getLong(SqlNote.ID_COLUMN)), values, null, null); } else { Log.e(TAG, "something is missed"); - throw new ActionFailureException( - "some local items don't have gid after sync"); + throw new ActionFailureException("some local items don't have gid after sync"); } } } else { @@ -790,11 +853,18 @@ public class GTaskManager { } } + /** + * 获取当前同步账户名称 + * @return 同步账户的邮箱地址 + */ public String getSyncAccount() { return GTaskClient.getInstance().getSyncAccount().name; } + /** + * 取消同步操作(线程安全) + */ public void cancelSync() { mCancelled = true; } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/gtask/remote/GTaskSyncService.java b/java/net/micode/notes/gtask/remote/GTaskSyncService.java index 42c1479..d9d1cfe 100644 --- a/java/net/micode/notes/gtask/remote/GTaskSyncService.java +++ b/java/net/micode/notes/gtask/remote/GTaskSyncService.java @@ -23,41 +23,78 @@ import android.content.Intent; import android.os.Bundle; import android.os.IBinder; +/** + * Google任务同步服务 + * + * 提供后台同步功能,处理与Google Tasks的双向数据同步 + * 通过Intent接收同步命令,使用广播机制通知UI同步状态 + * 采用单例模式确保服务实例唯一 + * + * 服务支持的操作: + * 1. 启动同步 + * 2. 取消同步 + * 3. 查询同步状态 + * + * 同步过程通过GTaskManager执行,服务负责生命周期管理和UI通知 + */ public class GTaskSyncService extends Service { + + // 服务命令常量定义 public final static String ACTION_STRING_NAME = "sync_action_type"; - public final static int ACTION_START_SYNC = 0; + public final static int ACTION_START_SYNC = 0; // 启动同步操作 - public final static int ACTION_CANCEL_SYNC = 1; + public final static int ACTION_CANCEL_SYNC = 1; // 取消同步操作 - public final static int ACTION_INVALID = 2; + public final static int ACTION_INVALID = 2; // 无效操作 + // 广播相关常量 public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; - // private static GTaskASyncTask mSyncTask = null; - - private static String mSyncProgress = ""; + // 同步状态跟踪 + private static String mSyncProgress = ""; // 当前同步进度消息 + /** + * 启动Google任务同步 + * 此方法将创建并执行异步同步任务 + */ private void startSync() { // Temporarily disabled sync functionality sendBroadcast("Sync functionality temporarily disabled"); stopSelf(); } + /** + * 取消正在进行的同步操作 + * 通知GTaskManager停止当前同步任务 + */ private void cancelSync() { // Temporarily disabled sync functionality sendBroadcast("Sync cancelled"); } + /** + * 服务创建时调用 + * 初始化服务资源,设置同步管理器上下文 + */ @Override public void onCreate() { // Temporarily disabled sync functionality } + /** + * 处理启动服务的请求 + * 根据Intent中的操作类型执行相应的同步操作 + * + * @param intent 启动服务的Intent,包含操作类型 + * @param flags 启动标志 + * @param startId 启动ID + * @return 服务重启策略 + */ @Override public int onStartCommand(Intent intent, int flags, int startId) { Bundle bundle = intent.getExtras(); @@ -72,20 +109,34 @@ public class GTaskSyncService extends Service { default: break; } - return START_STICKY; + return START_STICKY; // 系统内存不足时自动重启服务 } return super.onStartCommand(intent, flags, startId); } + /** + * 系统内存不足时调用 + * 释放不必要的资源,确保服务稳定运行 + */ @Override public void onLowMemory() { // Temporarily disabled sync functionality } + /** + * 返回服务的Binder接口 + * 由于本服务不支持绑定,返回null + */ public IBinder onBind(Intent intent) { return null; } + /** + * 发送同步状态广播 + * 更新当前同步进度并发送广播通知UI + * + * @param msg 同步状态消息 + */ public void sendBroadcast(String msg) { mSyncProgress = msg; Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); @@ -94,6 +145,12 @@ public class GTaskSyncService extends Service { sendBroadcast(intent); } + /** + * 静态方法:启动同步服务 + * 方便Activity直接调用启动同步 + * + * @param activity 调用此方法的Activity + */ public static void startSync(Activity activity) { // Temporarily disabled sync functionality Intent intent = new Intent(activity, GTaskSyncService.class); @@ -101,16 +158,32 @@ public class GTaskSyncService extends Service { activity.startService(intent); } + /** + * 静态方法:取消同步 + * 方便任何Context调用取消同步 + * + * @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 false; // Temporarily disabled sync functionality } + /** + * 获取当前同步进度消息 + * + * @return 同步进度文本描述 + */ public static String getProgressString() { return mSyncProgress; } diff --git a/java/net/micode/notes/model/Note.java b/java/net/micode/notes/model/Note.java index 6706cf6..bb7189f 100644 --- a/java/net/micode/notes/model/Note.java +++ b/java/net/micode/notes/model/Note.java @@ -15,6 +15,7 @@ */ package net.micode.notes.model; + import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentUris; @@ -33,25 +34,36 @@ import net.micode.notes.data.Notes.TextNote; import java.util.ArrayList; - +/** + * 表示一个便签的模型类,负责便签的创建、本地修改管理和数据同步 + */ public class Note { + // 存储便签元数据(如标题、父文件夹等)的变更值 private ContentValues mNoteDiffValues; + // 存储便签内容数据(文本/通话记录) private NoteData mNoteData; private static final String TAG = "Note"; + /** - * Create a new note id for adding a new note to databases + * 在指定文件夹中创建新便签并返回其ID + * @param context 上下文对象 + * @param folderId 父文件夹ID + * @return 新创建的便签ID(大于0) */ public static synchronized long getNewNoteId(Context context, long folderId) { - // Create a new note in the database + // 初始化便签基础属性 ContentValues values = new ContentValues(); long createdTime = System.currentTimeMillis(); values.put(NoteColumns.CREATED_DATE, createdTime); values.put(NoteColumns.MODIFIED_DATE, createdTime); values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); - values.put(NoteColumns.LOCAL_MODIFIED, 1); + values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改 values.put(NoteColumns.PARENT_ID, folderId); + + // 插入数据库并获取URI Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); + // 从URI解析便签ID long noteId = 0; try { noteId = Long.valueOf(uri.getPathSegments().get(1)); @@ -65,89 +77,104 @@ public class Note { return noteId; } + /** 构造函数:初始化便签数据和变更容器 */ public Note() { mNoteDiffValues = new ContentValues(); mNoteData = new NoteData(); } + /** + * 设置便签元数据(如标题、父ID等) + * @param key 字段名(NoteColumns中的常量) + * @param value 字段值 + */ public void setNoteValue(String key, String value) { mNoteDiffValues.put(key, value); - mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); - mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记本地修改 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新修改时间 } + /** 设置文本类型便签的内容数据 */ public void setTextData(String key, String value) { mNoteData.setTextData(key, value); } + /** 设置文本数据项的ID(用于更新现有数据) */ public void setTextDataId(long id) { mNoteData.setTextDataId(id); } + /** 获取文本数据项的ID */ public long getTextDataId() { return mNoteData.mTextDataId; } + /** 设置通话记录数据项的ID(用于更新现有数据) */ public void setCallDataId(long id) { mNoteData.setCallDataId(id); } + /** 设置通话记录类型便签的内容数据 */ public void setCallData(String key, String value) { mNoteData.setCallData(key, value); } + /** 检查便签是否有未同步的本地修改 */ public boolean isLocalModified() { return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); } + /** + * 同步便签数据到数据库 + * @param context 上下文对象 + * @param noteId 要同步的便签ID + * @return true 同步成功,false 同步失败 + */ public boolean syncNote(Context context, long noteId) { if (noteId <= 0) { throw new IllegalArgumentException("Wrong note id:" + noteId); } if (!isLocalModified()) { - return true; + return true; // 无修改直接返回成功 } - /** - * In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and - * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the - * note data info - */ + // 步骤1: 更新便签元数据 if (context.getContentResolver().update( - ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, - null) == 0) { + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + mNoteDiffValues, null, null) == 0) { Log.e(TAG, "Update note error, should not happen"); - // Do not return, fall through + // 继续尝试保存内容数据(即使元数据更新失败) } - mNoteDiffValues.clear(); + mNoteDiffValues.clear(); // 清空缓存 - if (mNoteData.isLocalModified() - && (mNoteData.pushIntoContentResolver(context, noteId) == null)) { - return false; + // 步骤2: 更新便签内容数据(文本/通话记录) + if (mNoteData.isLocalModified() && + (mNoteData.pushIntoContentResolver(context, noteId) == null)) { + return false; // 内容数据同步失败 } return true; } + /** + * 内部类:管理便签的内容数据(文本/通话记录) + */ private class NoteData { - private long mTextDataId; - - private ContentValues mTextDataValues; - - private long mCallDataId; - - private ContentValues mCallDataValues; - + private long mTextDataId; // 文本数据项在数据库中的ID + private ContentValues mTextDataValues; // 待同步的文本数据变更 + private long mCallDataId; // 通话记录数据项在数据库中的ID + private ContentValues mCallDataValues; // 待同步的通话记录变更 private static final String TAG = "NoteData"; public NoteData() { mTextDataValues = new ContentValues(); mCallDataValues = new ContentValues(); - mTextDataId = 0; + mTextDataId = 0; // 0表示新数据(未插入数据库) mCallDataId = 0; } + /** 检查内容数据是否有修改 */ boolean isLocalModified() { return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; } @@ -166,88 +193,92 @@ public class Note { mCallDataId = id; } + /** 设置通话记录数据并标记便签为已修改 */ void setCallData(String key, String value) { mCallDataValues.put(key, value); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); } + /** 设置文本数据并标记便签为已修改 */ void setTextData(String key, String value) { mTextDataValues.put(key, value); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); } + /** + * 将内容数据变更推送到数据库 + * @return Uri 成功时返回便签URI,失败返回null + */ Uri pushIntoContentResolver(Context context, long noteId) { - /** - * Check for safety - */ if (noteId <= 0) { throw new IllegalArgumentException("Wrong note id:" + noteId); } - ArrayList operationList = new ArrayList(); + ArrayList operationList = new ArrayList<>(); ContentProviderOperation.Builder builder = null; + // 处理文本数据变更 if(mTextDataValues.size() > 0) { - mTextDataValues.put(DataColumns.NOTE_ID, noteId); + mTextDataValues.put(DataColumns.NOTE_ID, noteId); // 关联便签ID if (mTextDataId == 0) { + // 新数据:插入操作 mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); - Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, - mTextDataValues); + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, mTextDataValues); try { - setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); - } catch (NumberFormatException e) { + setTextDataId(ContentUris.parseId(uri)); // 记录新数据的ID + } catch (Exception e) { Log.e(TAG, "Insert new text data fail with noteId" + noteId); mTextDataValues.clear(); return null; } } else { - builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mTextDataId)); + // 现有数据:更新操作 + builder = ContentProviderOperation.newUpdate( + ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, mTextDataId)); builder.withValues(mTextDataValues); operationList.add(builder.build()); } mTextDataValues.clear(); } + // 处理通话记录变更(逻辑同上) if(mCallDataValues.size() > 0) { mCallDataValues.put(DataColumns.NOTE_ID, noteId); if (mCallDataId == 0) { mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); - Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, - mCallDataValues); + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, mCallDataValues); try { - setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); - } catch (NumberFormatException e) { + setCallDataId(ContentUris.parseId(uri)); + } catch (Exception e) { Log.e(TAG, "Insert new call data fail with noteId" + noteId); mCallDataValues.clear(); return null; } } else { - builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mCallDataId)); + builder = ContentProviderOperation.newUpdate( + ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, mCallDataId)); builder.withValues(mCallDataValues); operationList.add(builder.build()); } mCallDataValues.clear(); } - if (operationList.size() > 0) { + // 批量执行更新操作(如果有) + if (!operationList.isEmpty()) { try { ContentProviderResult[] results = context.getContentResolver().applyBatch( Notes.AUTHORITY, operationList); - return (results == null || results.length == 0 || results[0] == null) ? null - : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); - } catch (RemoteException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); - return null; - } catch (OperationApplicationException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + // 返回便签URI表示成功 + return (results == null || results.length == 0) ? null : + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); + } catch (RemoteException | OperationApplicationException e) { + Log.e(TAG, "Batch operation error: " + e.getMessage()); return null; } } - return null; + return null; // 无内容数据更新 } } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/model/WorkingNote.java b/java/net/micode/notes/model/WorkingNote.java index be081e4..89f1e35 100644 --- a/java/net/micode/notes/model/WorkingNote.java +++ b/java/net/micode/notes/model/WorkingNote.java @@ -31,37 +31,43 @@ import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.TextNote; import net.micode.notes.tool.ResourceParser.NoteBgResources; - +/** + * 工作便签模型类 + * 负责管理正在编辑的便签数据,包括便签内容、属性和状态 + * 提供便签的创建、加载、保存和属性设置功能 + * 实现便签数据与UI的交互逻辑 + */ public class WorkingNote { - // Note for the working note + // 便签数据模型引用 private Note mNote; - // Note Id + // 便签ID private long mNoteId; - // Note content + // 便签内容 private String mContent; - // Note mode + // 便签模式(普通模式或清单模式) private int mMode; - + // 提醒日期 private long mAlertDate; - + // 最后修改日期 private long mModifiedDate; - + // 背景颜色ID private int mBgColorId; - + // 小部件ID private int mWidgetId; - + // 小部件类型 private int mWidgetType; - + // 所属文件夹ID private long mFolderId; - + // 应用上下文 private Context mContext; - + // 日志标签 private static final String TAG = "WorkingNote"; - + // 便签删除标记 private boolean mIsDeleted; - + // 便签设置变更监听器 private NoteSettingChangedListener mNoteSettingStatusListener; + // 数据查询投影(指定查询的列) public static final String[] DATA_PROJECTION = new String[] { DataColumns.ID, DataColumns.CONTENT, @@ -72,6 +78,7 @@ public class WorkingNote { DataColumns.DATA4, }; + // 便签查询投影 public static final String[] NOTE_PROJECTION = new String[] { NoteColumns.PARENT_ID, NoteColumns.ALERTED_DATE, @@ -81,27 +88,25 @@ public class WorkingNote { NoteColumns.MODIFIED_DATE }; + // 数据列索引 private static final int DATA_ID_COLUMN = 0; - private static final int DATA_CONTENT_COLUMN = 1; - private static final int DATA_MIME_TYPE_COLUMN = 2; - private static final int DATA_MODE_COLUMN = 3; + // 便签列索引 private static final int NOTE_PARENT_ID_COLUMN = 0; - private static final int NOTE_ALERTED_DATE_COLUMN = 1; - private static final int NOTE_BG_COLOR_ID_COLUMN = 2; - private static final int NOTE_WIDGET_ID_COLUMN = 3; - private static final int NOTE_WIDGET_TYPE_COLUMN = 4; - private static final int NOTE_MODIFIED_DATE_COLUMN = 5; - // New note construct + /** + * 新建便签构造函数 + * @param context 应用上下文 + * @param folderId 所属文件夹ID + */ private WorkingNote(Context context, long folderId) { mContext = context; mAlertDate = 0; @@ -114,7 +119,12 @@ public class WorkingNote { mWidgetType = Notes.TYPE_WIDGET_INVALIDE; } - // Existing note construct + /** + * 加载现有便签构造函数 + * @param context 应用上下文 + * @param noteId 便签ID + * @param folderId 所属文件夹ID + */ private WorkingNote(Context context, long noteId, long folderId) { mContext = context; mNoteId = noteId; @@ -124,6 +134,9 @@ public class WorkingNote { loadNote(); } + /** + * 从数据库加载便签基本信息 + */ private void loadNote() { Cursor cursor = mContext.getContentResolver().query( ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, @@ -146,10 +159,13 @@ public class WorkingNote { loadNoteData(); } + /** + * 从数据库加载便签内容数据 + */ private void loadNoteData() { Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { - String.valueOf(mNoteId) + String.valueOf(mNoteId) }, null); if (cursor != null) { @@ -174,8 +190,17 @@ public class WorkingNote { } } + /** + * 创建空便签 + * @param context 应用上下文 + * @param folderId 所属文件夹ID + * @param widgetId 小部件ID + * @param widgetType 小部件类型 + * @param defaultBgColorId 默认背景颜色ID + * @return 新建的工作便签实例 + */ public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, - int widgetType, int defaultBgColorId) { + int widgetType, int defaultBgColorId) { WorkingNote note = new WorkingNote(context, folderId); note.setBgColorId(defaultBgColorId); note.setWidgetId(widgetId); @@ -183,10 +208,20 @@ public class WorkingNote { return note; } + /** + * 加载现有便签 + * @param context 应用上下文 + * @param id 便签ID + * @return 加载的工作便签实例 + */ public static WorkingNote load(Context context, long id) { return new WorkingNote(context, id, 0); } + /** + * 保存便签到数据库 + * @return 保存是否成功 + */ public synchronized boolean saveNote() { if (isWorthSaving()) { if (!existInDatabase()) { @@ -199,7 +234,7 @@ public class WorkingNote { mNote.syncNote(mContext, mNoteId); /** - * Update widget content if there exist any widget of this note + * 更新小部件内容(如果有相关小部件) */ if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID && mWidgetType != Notes.TYPE_WIDGET_INVALIDE @@ -212,10 +247,18 @@ public class WorkingNote { } } + /** + * 检查便签是否存在于数据库 + * @return 是否存在 + */ public boolean existInDatabase() { return mNoteId > 0; } + /** + * 检查便签是否值得保存 + * @return 是否值得保存 + */ private boolean isWorthSaving() { if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) || (existInDatabase() && !mNote.isLocalModified())) { @@ -225,10 +268,19 @@ public class WorkingNote { } } + /** + * 设置便签设置变更监听器 + * @param l 监听器实例 + */ public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { mNoteSettingStatusListener = l; } + /** + * 设置提醒日期 + * @param date 提醒日期 + * @param set 是否设置提醒 + */ public void setAlertDate(long date, boolean set) { if (date != mAlertDate) { mAlertDate = date; @@ -239,14 +291,22 @@ public class WorkingNote { } } + /** + * 标记便签为已删除或取消删除 + * @param mark 是否删除 + */ public void markDeleted(boolean mark) { mIsDeleted = mark; if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { - mNoteSettingStatusListener.onWidgetChanged(); + mNoteSettingStatusListener.onWidgetChanged(); } } + /** + * 设置便签背景颜色 + * @param id 背景颜色ID + */ public void setBgColorId(int id) { if (id != mBgColorId) { mBgColorId = id; @@ -257,6 +317,10 @@ public class WorkingNote { } } + /** + * 设置便签清单模式 + * @param mode 模式(0-普通模式,1-清单模式) + */ public void setCheckListMode(int mode) { if (mMode != mode) { if (mNoteSettingStatusListener != null) { @@ -267,6 +331,10 @@ public class WorkingNote { } } + /** + * 设置小部件类型 + * @param type 小部件类型 + */ public void setWidgetType(int type) { if (type != mWidgetType) { mWidgetType = type; @@ -274,6 +342,10 @@ public class WorkingNote { } } + /** + * 设置小部件ID + * @param id 小部件ID + */ public void setWidgetId(int id) { if (id != mWidgetId) { mWidgetId = id; @@ -281,6 +353,10 @@ public class WorkingNote { } } + /** + * 设置便签内容 + * @param text 便签文本内容 + */ public void setWorkingText(String text) { if (!TextUtils.equals(mContent, text)) { mContent = text; @@ -288,81 +364,140 @@ public class WorkingNote { } } + /** + * 转换为通话便签 + * @param phoneNumber 电话号码 + * @param callDate 通话日期 + */ public void convertToCallNote(String phoneNumber, long callDate) { mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); } + /** + * 检查便签是否设置了提醒 + * @return 是否设置提醒 + */ public boolean hasClockAlert() { return (mAlertDate > 0 ? true : false); } + /** + * 获取便签内容 + * @return 便签文本内容 + */ public String getContent() { return mContent; } + /** + * 获取提醒日期 + * @return 提醒日期 + */ public long getAlertDate() { return mAlertDate; } + /** + * 获取最后修改日期 + * @return 最后修改日期 + */ public long getModifiedDate() { return mModifiedDate; } + /** + * 获取背景颜色资源ID + * @return 背景颜色资源ID + */ public int getBgColorResId() { return NoteBgResources.getNoteBgResource(mBgColorId); } + /** + * 获取背景颜色ID + * @return 背景颜色ID + */ public int getBgColorId() { return mBgColorId; } + /** + * 获取标题背景资源ID + * @return 标题背景资源ID + */ public int getTitleBgResId() { return NoteBgResources.getNoteTitleBgResource(mBgColorId); } + /** + * 获取便签模式 + * @return 便签模式(0-普通模式,1-清单模式) + */ public int getCheckListMode() { return mMode; } + /** + * 获取便签ID + * @return 便签ID + */ public long getNoteId() { return mNoteId; } + /** + * 获取所属文件夹ID + * @return 文件夹ID + */ public long getFolderId() { return mFolderId; } + /** + * 获取小部件ID + * @return 小部件ID + */ public int getWidgetId() { return mWidgetId; } + /** + * 获取小部件类型 + * @return 小部件类型 + */ public int getWidgetType() { return mWidgetType; } + /** + * 便签设置变更监听器接口 + * 用于监听便签设置变化并通知UI更新 + */ public interface NoteSettingChangedListener { /** - * Called when the background color of current note has just changed + * 当便签背景颜色变更时调用 */ void onBackgroundColorChanged(); /** - * Called when user set clock + * 当便签提醒设置变更时调用 + * @param date 提醒日期 + * @param set 是否设置提醒 */ void onClockAlertChanged(long date, boolean set); /** - * Call when user create note from widget + * 当便签相关小部件需要更新时调用 */ void onWidgetChanged(); /** - * Call when switch between check list mode and normal mode - * @param oldMode is previous mode before change - * @param newMode is new mode + * 当便签模式(普通/清单)变更时调用 + * @param oldMode 旧模式 + * @param newMode 新模式 */ void onCheckListModeChanged(int oldMode, int newMode); } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/tool/BackupUtils.java b/java/net/micode/notes/tool/BackupUtils.java index 39f6ec4..a5c32c9 100644 --- a/java/net/micode/notes/tool/BackupUtils.java +++ b/java/net/micode/notes/tool/BackupUtils.java @@ -35,12 +35,23 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; - +/** + * 便签备份工具类 + * 提供便签数据导出到文本文件的功能 + * 支持导出普通便签和通话记录便签 + * 导出格式为用户可读的文本格式,包含文件夹结构和时间戳 + * 使用单例模式确保全局唯一实例 + */ public class BackupUtils { private static final String TAG = "BackupUtils"; - // Singleton stuff + // 单例模式实现 private static BackupUtils sInstance; + /** + * 获取BackupUtils单例实例 + * @param context 应用上下文 + * @return BackupUtils实例 + */ public static synchronized BackupUtils getInstance(Context context) { if (sInstance == null) { sInstance = new BackupUtils(context); @@ -49,82 +60,108 @@ public class BackupUtils { } /** - * Following states are signs to represents backup or restore - * status + * 备份操作状态常量 + * 定义备份过程中的各种状态码 */ - // Currently, the sdcard is not mounted + // SD卡未挂载状态 public static final int STATE_SD_CARD_UNMOUONTED = 0; - // The backup file not exist + // 备份文件不存在状态 public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; - // The data is not well formated, may be changed by other programs + // 数据格式损坏状态 public static final int STATE_DATA_DESTROIED = 2; - // Some run-time exception which causes restore or backup fails + // 系统错误状态 public static final int STATE_SYSTEM_ERROR = 3; - // Backup or restore success + // 备份成功状态 public static final int STATE_SUCCESS = 4; private TextExport mTextExport; + /** + * 私有构造函数 + * @param context 应用上下文 + */ private BackupUtils(Context context) { mTextExport = new TextExport(context); } + /** + * 检查外部存储是否可用 + * @return 外部存储可用返回true,否则返回false + */ private static boolean externalStorageAvailable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } + /** + * 导出便签数据到文本文件 + * @return 导出状态码 + */ public int exportToText() { return mTextExport.exportToText(); } + /** + * 获取导出的文本文件名 + * @return 文件名 + */ public String getExportedTextFileName() { return mTextExport.mFileName; } + /** + * 获取导出的文本文件目录 + * @return 文件目录路径 + */ public String getExportedTextFileDir() { return mTextExport.mFileDirectory; } + /** + * 文本导出内部类 + * 负责将便签数据格式化为文本并写入文件 + */ private static class TextExport { + // 便签查询投影字段(减少不必要的字段查询) private static final String[] NOTE_PROJECTION = { - NoteColumns.ID, - NoteColumns.MODIFIED_DATE, - NoteColumns.SNIPPET, - NoteColumns.TYPE + NoteColumns.ID, // 便签ID + NoteColumns.MODIFIED_DATE, // 便签修改日期 + NoteColumns.SNIPPET, // 便签摘要 + NoteColumns.TYPE // 便签类型 }; private static final int NOTE_COLUMN_ID = 0; - private static final int NOTE_COLUMN_MODIFIED_DATE = 1; - private static final int NOTE_COLUMN_SNIPPET = 2; + // 便签数据查询投影字段 private static final String[] DATA_PROJECTION = { - DataColumns.CONTENT, - DataColumns.MIME_TYPE, - DataColumns.DATA1, - DataColumns.DATA2, - DataColumns.DATA3, - DataColumns.DATA4, + DataColumns.CONTENT, // 内容 + DataColumns.MIME_TYPE, // MIME类型 + DataColumns.DATA1, // 数据字段1 + DataColumns.DATA2, // 数据字段2 + DataColumns.DATA3, // 数据字段3 + DataColumns.DATA4, // 数据字段4 }; private static final int DATA_COLUMN_CONTENT = 0; - private static final int DATA_COLUMN_MIME_TYPE = 1; - private static final int DATA_COLUMN_CALL_DATE = 2; - private static final int DATA_COLUMN_PHONE_NUMBER = 4; + // 文本导出格式数组 private final String [] TEXT_FORMAT; - private static final int FORMAT_FOLDER_NAME = 0; - private static final int FORMAT_NOTE_DATE = 1; - private static final int FORMAT_NOTE_CONTENT = 2; + private static final int FORMAT_FOLDER_NAME = 0; // 文件夹名称格式 + private static final int FORMAT_NOTE_DATE = 1; // 便签日期格式 + private static final int FORMAT_NOTE_CONTENT = 2; // 便签内容格式 private Context mContext; - private String mFileName; - private String mFileDirectory; + private String mFileName; // 导出文件名 + private String mFileDirectory; // 导出文件目录 + /** + * 构造函数 + * @param context 应用上下文 + */ public TextExport(Context context) { TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); mContext = context; @@ -132,28 +169,35 @@ public class BackupUtils { mFileDirectory = ""; } + /** + * 获取文本格式字符串 + * @param id 格式ID + * @return 格式字符串 + */ private String getFormat(int id) { return TEXT_FORMAT[id]; } /** - * Export the folder identified by folder id to text + * 导出文件夹及其便签到文本 + * @param folderId 文件夹ID + * @param ps 输出流 */ private void exportFolderToText(String folderId, PrintStream ps) { - // Query notes belong to this folder + // 查询该文件夹下的所有便签 Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { - folderId + folderId }, null); if (notesCursor != null) { if (notesCursor.moveToFirst()) { do { - // Print note's last modified date + // 打印便签的最后修改日期 ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( mContext.getString(R.string.format_datetime_mdhm), notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); - // Query data belong to this note + // 导出该便签的内容 String noteId = notesCursor.getString(NOTE_COLUMN_ID); exportNoteToText(noteId, ps); } while (notesCursor.moveToNext()); @@ -163,12 +207,15 @@ public class BackupUtils { } /** - * Export note identified by id to a print stream + * 导出单个便签到文本 + * @param noteId 便签ID + * @param ps 输出流 */ private void exportNoteToText(String noteId, PrintStream ps) { + // 查询便签的所有数据项 Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { - noteId + noteId }, null); if (dataCursor != null) { @@ -176,25 +223,27 @@ public class BackupUtils { do { String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); if (DataConstants.CALL_NOTE.equals(mimeType)) { - // Print phone number + // 处理通话记录便签 String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); String location = dataCursor.getString(DATA_COLUMN_CONTENT); + // 打印电话号码 if (!TextUtils.isEmpty(phoneNumber)) { ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber)); } - // Print call date + // 打印通话日期 ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat .format(mContext.getString(R.string.format_datetime_mdhm), callDate))); - // Print call attachment location + // 打印通话附件位置 if (!TextUtils.isEmpty(location)) { ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), location)); } } else if (DataConstants.NOTE.equals(mimeType)) { + // 处理普通便签 String content = dataCursor.getString(DATA_COLUMN_CONTENT); if (!TextUtils.isEmpty(content)) { ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), @@ -205,7 +254,7 @@ public class BackupUtils { } dataCursor.close(); } - // print a line separator between note + // 打印便签间的分隔符 try { ps.write(new byte[] { Character.LINE_SEPARATOR, Character.LETTER_NUMBER @@ -216,20 +265,24 @@ public class BackupUtils { } /** - * Note will be exported as text which is user readable + * 导出所有便签到文本文件 + * @return 导出状态码 */ public int exportToText() { + // 检查SD卡是否挂载 if (!externalStorageAvailable()) { Log.d(TAG, "Media was not mounted"); return STATE_SD_CARD_UNMOUONTED; } + // 获取输出流 PrintStream ps = getExportToTextPrintStream(); if (ps == null) { Log.e(TAG, "get print stream error"); return STATE_SYSTEM_ERROR; } - // First export folder and its notes + + // 导出文件夹及其便签 Cursor folderCursor = mContext.getContentResolver().query( Notes.CONTENT_NOTE_URI, NOTE_PROJECTION, @@ -240,7 +293,7 @@ public class BackupUtils { if (folderCursor != null) { if (folderCursor.moveToFirst()) { do { - // Print folder's name + // 打印文件夹名称 String folderName = ""; if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { folderName = mContext.getString(R.string.call_record_folder_name); @@ -250,6 +303,7 @@ public class BackupUtils { if (!TextUtils.isEmpty(folderName)) { ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); } + // 导出文件夹内的便签 String folderId = folderCursor.getString(NOTE_COLUMN_ID); exportFolderToText(folderId, ps); } while (folderCursor.moveToNext()); @@ -257,7 +311,7 @@ public class BackupUtils { folderCursor.close(); } - // Export notes in root's folder + // 导出根文件夹中的便签 Cursor noteCursor = mContext.getContentResolver().query( Notes.CONTENT_NOTE_URI, NOTE_PROJECTION, @@ -267,10 +321,11 @@ public class BackupUtils { if (noteCursor != null) { if (noteCursor.moveToFirst()) { do { + // 打印便签日期 ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( mContext.getString(R.string.format_datetime_mdhm), noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); - // Query data belong to this note + // 导出便签内容 String noteId = noteCursor.getString(NOTE_COLUMN_ID); exportNoteToText(noteId, ps); } while (noteCursor.moveToNext()); @@ -283,9 +338,11 @@ public class BackupUtils { } /** - * Get a print stream pointed to the file {@generateExportedTextFile} + * 获取用于导出文本的打印流 + * @return 打印流 */ private PrintStream getExportToTextPrintStream() { + // 生成文件 File file = generateFileMountedOnSDcard(mContext, R.string.file_path, R.string.file_name_txt_format); if (file == null) { @@ -294,6 +351,8 @@ public class BackupUtils { } mFileName = file.getName(); mFileDirectory = mContext.getString(R.string.file_path); + + // 创建打印流 PrintStream ps = null; try { FileOutputStream fos = new FileOutputStream(file); @@ -310,13 +369,20 @@ public class BackupUtils { } /** - * Generate the text file to store imported data + * 在SD卡上生成文件 + * @param context 应用上下文 + * @param filePathResId 文件路径资源ID + * @param fileNameFormatResId 文件名格式资源ID + * @return 生成的文件对象 */ private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { StringBuilder sb = new StringBuilder(); + // 构建文件路径 sb.append(Environment.getExternalStorageDirectory()); sb.append(context.getString(filePathResId)); File filedir = new File(sb.toString()); + + // 构建文件名(包含时间戳) sb.append(context.getString( fileNameFormatResId, DateFormat.format(context.getString(R.string.format_date_ymd), @@ -324,6 +390,7 @@ public class BackupUtils { File file = new File(sb.toString()); try { + // 创建目录和文件 if (!filedir.exists()) { filedir.mkdir(); } @@ -339,6 +406,4 @@ public class BackupUtils { return null; } -} - - +} \ No newline at end of file diff --git a/java/net/micode/notes/tool/DataUtils.java b/java/net/micode/notes/tool/DataUtils.java index 2a14982..7ab553b 100644 --- a/java/net/micode/notes/tool/DataUtils.java +++ b/java/net/micode/notes/tool/DataUtils.java @@ -34,100 +34,139 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; import java.util.ArrayList; import java.util.HashSet; - +/** + * 数据工具类 + * 提供便签数据操作的实用方法,包括批量删除、移动便签、查询数据等功能 + * 所有方法均为静态方法,便于在其他类中直接调用 + */ public class DataUtils { public static final String TAG = "DataUtils"; + + /** + * 批量删除便签 + * 使用ContentProvider的批量操作功能删除多个便签 + * 跳过系统根文件夹的删除操作 + * + * @param resolver ContentResolver实例 + * @param ids 待删除的便签ID集合 + * @return 删除是否成功 + */ public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { if (ids == null) { - Log.d(TAG, "the ids is null"); + Log.d(TAG, "待删除的ID集合为null"); return true; } if (ids.size() == 0) { - Log.d(TAG, "no id is in the hashset"); + Log.d(TAG, "ID集合为空,无需删除"); return true; } ArrayList operationList = new ArrayList(); for (long id : ids) { - if(id == Notes.ID_ROOT_FOLDER) { - Log.e(TAG, "Don't delete system folder root"); + if (id == Notes.ID_ROOT_FOLDER) { + Log.e(TAG, "尝试删除系统根文件夹,已跳过"); continue; } + // 构建删除操作 ContentProviderOperation.Builder builder = ContentProviderOperation .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); operationList.add(builder.build()); } try { + // 执行批量操作 ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); if (results == null || results.length == 0 || results[0] == null) { - Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + Log.d(TAG, "删除便签失败,ID集合: " + ids.toString()); return false; } return true; } catch (RemoteException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + Log.e(TAG, "远程异常: " + e.toString()); } catch (OperationApplicationException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + Log.e(TAG, "操作应用异常: " + e.toString()); } return false; } + /** + * 将便签移动到指定文件夹 + * 更新便签的父文件夹ID,并标记为本地已修改 + * + * @param resolver ContentResolver实例 + * @param id 待移动的便签ID + * @param srcFolderId 源文件夹ID + * @param desFolderId 目标文件夹ID + */ public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { ContentValues values = new ContentValues(); - values.put(NoteColumns.PARENT_ID, desFolderId); - values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); - values.put(NoteColumns.LOCAL_MODIFIED, 1); + values.put(NoteColumns.PARENT_ID, desFolderId); // 设置新的父文件夹ID + values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 记录原始父文件夹ID + values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改 resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); } - public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, - long folderId) { + /** + * 批量将便签移动到指定文件夹 + * 使用ContentProvider的批量操作功能移动多个便签 + * + * @param resolver ContentResolver实例 + * @param ids 待移动的便签ID集合 + * @param folderId 目标文件夹ID + * @return 移动是否成功 + */ + public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, long folderId) { if (ids == null) { - Log.d(TAG, "the ids is null"); + Log.d(TAG, "待移动的ID集合为null"); return true; } ArrayList operationList = new ArrayList(); for (long id : ids) { + // 构建更新操作 ContentProviderOperation.Builder builder = ContentProviderOperation .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); - builder.withValue(NoteColumns.PARENT_ID, folderId); - builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); + builder.withValue(NoteColumns.PARENT_ID, folderId); // 设置新的父文件夹ID + builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改 operationList.add(builder.build()); } try { + // 执行批量操作 ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); if (results == null || results.length == 0 || results[0] == null) { - Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + Log.d(TAG, "移动便签失败,ID集合: " + ids.toString()); return false; } return true; } catch (RemoteException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + Log.e(TAG, "远程异常: " + e.toString()); } catch (OperationApplicationException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + Log.e(TAG, "操作应用异常: " + e.toString()); } return false; } /** - * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} + * 获取用户创建的文件夹数量(不包括系统文件夹) + * 查询类型为文件夹且不是垃圾文件夹的记录数量 + * + * @param resolver ContentResolver实例 + * @return 用户文件夹数量 */ public static int getUserFolderCount(ContentResolver resolver) { - Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI, + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, new String[] { "COUNT(*)" }, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", - new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, + new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) }, null); int count = 0; - if(cursor != null) { - if(cursor.moveToFirst()) { + if (cursor != null) { + if (cursor.moveToFirst()) { try { count = cursor.getInt(0); } catch (IndexOutOfBoundsException e) { - Log.e(TAG, "get folder count failed:" + e.toString()); + Log.e(TAG, "获取文件夹数量失败: " + e.toString()); } finally { cursor.close(); } @@ -136,11 +175,20 @@ public class DataUtils { return count; } + /** + * 检查便签在数据库中是否可见 + * 检查便签类型和父文件夹是否为非垃圾文件夹 + * + * @param resolver ContentResolver实例 + * @param noteId 便签ID + * @param type 便签类型 + * @return 是否可见 + */ public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, - new String [] {String.valueOf(type)}, + new String[] { String.valueOf(type) }, null); boolean exist = false; @@ -153,6 +201,13 @@ public class DataUtils { return exist; } + /** + * 检查便签是否存在于数据库 + * + * @param resolver ContentResolver实例 + * @param noteId 便签ID + * @return 是否存在 + */ public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null, null, null, null); @@ -167,6 +222,13 @@ public class DataUtils { return exist; } + /** + * 检查数据是否存在于数据库 + * + * @param resolver ContentResolver实例 + * @param dataId 数据ID + * @return 是否存在 + */ public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null, null, null, null); @@ -181,15 +243,22 @@ public class DataUtils { return exist; } + /** + * 检查文件夹名称是否已存在(不包括垃圾文件夹) + * + * @param resolver ContentResolver实例 + * @param name 文件夹名称 + * @return 是否存在同名文件夹 + */ public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + - " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + - " AND " + NoteColumns.SNIPPET + "=?", + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.SNIPPET + "=?", new String[] { name }, null); boolean exist = false; - if(cursor != null) { - if(cursor.getCount() > 0) { + if (cursor != null) { + if (cursor.getCount() > 0) { exist = true; } cursor.close(); @@ -197,6 +266,13 @@ public class DataUtils { return exist; } + /** + * 获取文件夹中便签的小部件信息 + * + * @param resolver ContentResolver实例 + * @param folderId 文件夹ID + * @return 小部件属性集合 + */ public static HashSet getFolderNoteWidget(ContentResolver resolver, long folderId) { Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, @@ -215,7 +291,7 @@ public class DataUtils { widget.widgetType = c.getInt(1); set.add(widget); } catch (IndexOutOfBoundsException e) { - Log.e(TAG, e.toString()); + Log.e(TAG, "获取小部件信息失败: " + e.toString()); } } while (c.moveToNext()); } @@ -224,18 +300,25 @@ public class DataUtils { return set; } + /** + * 根据便签ID获取通话便签的电话号码 + * + * @param resolver ContentResolver实例 + * @param noteId 便签ID + * @return 电话号码,不存在则返回空字符串 + */ public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, - new String [] { CallNote.PHONE_NUMBER }, + new String[] { CallNote.PHONE_NUMBER }, CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", - new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, + new String[] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, null); if (cursor != null && cursor.moveToFirst()) { try { return cursor.getString(0); } catch (IndexOutOfBoundsException e) { - Log.e(TAG, "Get call number fails " + e.toString()); + Log.e(TAG, "获取电话号码失败: " + e.toString()); } finally { cursor.close(); } @@ -243,12 +326,21 @@ public class DataUtils { return ""; } + /** + * 根据电话号码和通话日期获取通话便签的ID + * 使用PHONE_NUMBERS_EQUAL函数进行电话号码匹配(忽略格式) + * + * @param resolver ContentResolver实例 + * @param phoneNumber 电话号码 + * @param callDate 通话日期 + * @return 便签ID,不存在则返回0 + */ public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, - new String [] { CallNote.NOTE_ID }, + new String[] { CallNote.NOTE_ID }, CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" - + CallNote.PHONE_NUMBER + ",?)", - new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, + + CallNote.PHONE_NUMBER + ",?)", + new String[] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, null); if (cursor != null) { @@ -256,7 +348,7 @@ public class DataUtils { try { return cursor.getLong(0); } catch (IndexOutOfBoundsException e) { - Log.e(TAG, "Get call note id fails " + e.toString()); + Log.e(TAG, "获取通话便签ID失败: " + e.toString()); } } cursor.close(); @@ -264,11 +356,19 @@ public class DataUtils { return 0; } + /** + * 根据便签ID获取便签摘要 + * + * @param resolver ContentResolver实例 + * @param noteId 便签ID + * @return 便签摘要 + * @throws IllegalArgumentException 便签不存在时抛出 + */ public static String getSnippetById(ContentResolver resolver, long noteId) { Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, - new String [] { NoteColumns.SNIPPET }, + new String[] { NoteColumns.SNIPPET }, NoteColumns.ID + "=?", - new String [] { String.valueOf(noteId)}, + new String[] { String.valueOf(noteId) }, null); if (cursor != null) { @@ -279,9 +379,16 @@ public class DataUtils { cursor.close(); return snippet; } - throw new IllegalArgumentException("Note is not found with id: " + noteId); + throw new IllegalArgumentException("未找到ID为 " + noteId + " 的便签"); } + /** + * 格式化便签摘要 + * 去除前后空格,并截断第一个换行符之后的内容 + * + * @param snippet 原始摘要 + * @return 格式化后的摘要 + */ public static String getFormattedSnippet(String snippet) { if (snippet != null) { snippet = snippet.trim(); @@ -292,4 +399,4 @@ public class DataUtils { } return snippet; } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/tool/GTaskStringUtils.java b/java/net/micode/notes/tool/GTaskStringUtils.java index 666b729..7322bc3 100644 --- a/java/net/micode/notes/tool/GTaskStringUtils.java +++ b/java/net/micode/notes/tool/GTaskStringUtils.java @@ -16,98 +16,64 @@ package net.micode.notes.tool; +/** + * Google Tasks 数据格式工具类 + * 定义与Google Tasks同步相关的JSON字段常量和文件夹命名规范 + * 提供Google Tasks与本地便签系统的字段映射关系 + */ public class GTaskStringUtils { - public final static String GTASK_JSON_ACTION_ID = "action_id"; - - public final static String GTASK_JSON_ACTION_LIST = "action_list"; - - public final static String GTASK_JSON_ACTION_TYPE = "action_type"; - - public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; - - public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; - - public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; - - public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; - - public final static String GTASK_JSON_CREATOR_ID = "creator_id"; - - public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; - - public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; - - public final static String GTASK_JSON_COMPLETED = "completed"; - - public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; - - public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; - - public final static String GTASK_JSON_DELETED = "deleted"; - - public final static String GTASK_JSON_DEST_LIST = "dest_list"; - - public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; - - public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; - - public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; - - public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; - - public final static String GTASK_JSON_GET_DELETED = "get_deleted"; - - public final static String GTASK_JSON_ID = "id"; - - public final static String GTASK_JSON_INDEX = "index"; - - public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; - - public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; - - public final static String GTASK_JSON_LIST_ID = "list_id"; - - public final static String GTASK_JSON_LISTS = "lists"; - - public final static String GTASK_JSON_NAME = "name"; - - public final static String GTASK_JSON_NEW_ID = "new_id"; - - public final static String GTASK_JSON_NOTES = "notes"; - - public final static String GTASK_JSON_PARENT_ID = "parent_id"; - - public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; - - public final static String GTASK_JSON_RESULTS = "results"; - - public final static String GTASK_JSON_SOURCE_LIST = "source_list"; - - public final static String GTASK_JSON_TASKS = "tasks"; - - public final static String GTASK_JSON_TYPE = "type"; - - public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; - - public final static String GTASK_JSON_TYPE_TASK = "TASK"; - - public final static String GTASK_JSON_USER = "user"; - - public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; - - public final static String FOLDER_DEFAULT = "Default"; - - public final static String FOLDER_CALL_NOTE = "Call_Note"; - - public final static String FOLDER_META = "METADATA"; - - public final static String META_HEAD_GTASK_ID = "meta_gid"; - - public final static String META_HEAD_NOTE = "meta_note"; - - public final static String META_HEAD_DATA = "meta_data"; - - public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; - -} + // Google Tasks JSON 协议字段常量(动作相关) + public final static String GTASK_JSON_ACTION_ID = "action_id"; // 动作唯一标识 + public final static String GTASK_JSON_ACTION_LIST = "action_list"; // 动作列表 + public final static String GTASK_JSON_ACTION_TYPE = "action_type"; // 动作类型 + public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; // 创建动作 + public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; // 获取所有动作 + public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; // 移动动作 + public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; // 更新动作 + + // Google Tasks JSON 协议字段常量(实体相关) + public final static String GTASK_JSON_CREATOR_ID = "creator_id"; // 创建者ID + public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; // 子实体 + public final static String GTASK_JSON_CLIENT_VERSION = "client_version";// 客户端版本 + public final static String GTASK_JSON_COMPLETED = "completed"; // 完成状态 + public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; // 当前列表ID + public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; // 默认列表ID + public final static String GTASK_JSON_DELETED = "deleted"; // 删除标记 + public final static String GTASK_JSON_DEST_LIST = "dest_list"; // 目标列表 + public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; // 目标父级 + public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; // 目标父级类型 + public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; // 实体变更 + public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; // 实体类型 + public final static String GTASK_JSON_GET_DELETED = "get_deleted"; // 获取已删除项 + public final static String GTASK_JSON_ID = "id"; // 实体ID + public final static String GTASK_JSON_INDEX = "index"; // 索引位置 + public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; // 最后修改时间 + public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; // 最新同步点 + public final static String GTASK_JSON_LIST_ID = "list_id"; // 列表ID + public final static String GTASK_JSON_LISTS = "lists"; // 列表集合 + public final static String GTASK_JSON_NAME = "name"; // 名称 + public final static String GTASK_JSON_NEW_ID = "new_id"; // 新ID + public final static String GTASK_JSON_NOTES = "notes"; // 备注 + public final static String GTASK_JSON_PARENT_ID = "parent_id"; // 父级ID + public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; // 前一个兄弟ID + public final static String GTASK_JSON_RESULTS = "results"; // 结果集合 + public final static String GTASK_JSON_SOURCE_LIST = "source_list"; // 源列表 + public final static String GTASK_JSON_TASKS = "tasks"; // 任务集合 + public final static String GTASK_JSON_TYPE = "type"; // 类型 + public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; // 分组类型 + public final static String GTASK_JSON_TYPE_TASK = "TASK"; // 任务类型 + public final static String GTASK_JSON_USER = "user"; // 用户信息 + + // 本地文件夹与Google Tasks同步相关命名规范 + public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; // MIUI便签文件夹前缀 + public final static String FOLDER_DEFAULT = "Default"; // 默认文件夹 + public final static String FOLDER_CALL_NOTE = "Call_Note"; // 通话便签文件夹 + public final static String FOLDER_META = "METADATA"; // 元数据文件夹 + + // 元数据字段命名规范(用于本地与Google Tasks映射) + public final static String META_HEAD_GTASK_ID = "meta_gid"; // Google Tasks ID元数据头 + public final static String META_HEAD_NOTE = "meta_note"; // 便签元数据头 + public final static String META_HEAD_DATA = "meta_data"; // 数据元数据头 + public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; // 元数据便签名称(不可修改删除) +} \ No newline at end of file diff --git a/java/net/micode/notes/tool/ResourceParser.java b/java/net/micode/notes/tool/ResourceParser.java index 1ad3ad6..1a5d000 100644 --- a/java/net/micode/notes/tool/ResourceParser.java +++ b/java/net/micode/notes/tool/ResourceParser.java @@ -22,151 +22,242 @@ import android.preference.PreferenceManager; import net.micode.notes.R; import net.micode.notes.ui.NotesPreferenceActivity; +/** + * 资源解析工具类 + * 统一管理便签应用中的资源映射关系,包括: + * 1. 便签背景颜色资源 + * 2. 便签列表项背景资源 + * 3. 桌面小部件背景资源 + * 4. 文本样式资源 + * 提供资源ID与逻辑标识的映射转换方法 + */ public class ResourceParser { - public static final int YELLOW = 0; - public static final int BLUE = 1; - public static final int WHITE = 2; - public static final int GREEN = 3; - public static final int RED = 4; + // 便签背景颜色逻辑标识(与资源数组索引对应) + public static final int YELLOW = 0; // 黄色背景 + public static final int BLUE = 1; // 蓝色背景 + public static final int WHITE = 2; // 白色背景 + public static final int GREEN = 3; // 绿色背景 + public static final int RED = 4; // 红色背景 - public static final int BG_DEFAULT_COLOR = YELLOW; + public static final int BG_DEFAULT_COLOR = YELLOW; // 默认背景颜色(黄色) - public static final int TEXT_SMALL = 0; - public static final int TEXT_MEDIUM = 1; - public static final int TEXT_LARGE = 2; - public static final int TEXT_SUPER = 3; + // 文本大小逻辑标识 + public static final int TEXT_SMALL = 0; // 小字体 + public static final int TEXT_MEDIUM = 1; // 中等字体 + public static final int TEXT_LARGE = 2; // 大字体 + public static final int TEXT_SUPER = 3; // 超大字体 - public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; + public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; // 默认字体大小(中等) + /** + * 便签编辑界面背景资源管理类 + * 管理便签编辑界面的背景和标题栏背景资源 + */ public static class NoteBgResources { - private final static int [] BG_EDIT_RESOURCES = new int [] { - R.drawable.edit_yellow, - R.drawable.edit_blue, - R.drawable.edit_white, - R.drawable.edit_green, - R.drawable.edit_red + // 编辑界面背景资源数组(按颜色标识顺序排列) + private final static int[] BG_EDIT_RESOURCES = new int[]{ + R.drawable.edit_yellow, // 黄色编辑背景 + R.drawable.edit_blue, // 蓝色编辑背景 + R.drawable.edit_white, // 白色编辑背景 + R.drawable.edit_green, // 绿色编辑背景 + R.drawable.edit_red // 红色编辑背景 }; - private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] { - R.drawable.edit_title_yellow, - R.drawable.edit_title_blue, - R.drawable.edit_title_white, - R.drawable.edit_title_green, - R.drawable.edit_title_red + // 编辑界面标题栏背景资源数组 + private final static int[] BG_EDIT_TITLE_RESOURCES = new int[]{ + R.drawable.edit_title_yellow, // 黄色标题栏背景 + R.drawable.edit_title_blue, // 蓝色标题栏背景 + R.drawable.edit_title_white, // 白色标题栏背景 + R.drawable.edit_title_green, // 绿色标题栏背景 + R.drawable.edit_title_red // 红色标题栏背景 }; + /** + * 获取便签编辑界面背景资源ID + * @param id 颜色逻辑标识(0-4) + * @return 对应的背景资源ID + */ public static int getNoteBgResource(int id) { return BG_EDIT_RESOURCES[id]; } + /** + * 获取便签编辑界面标题栏背景资源ID + * @param id 颜色逻辑标识(0-4) + * @return 对应的标题栏背景资源ID + */ public static int getNoteTitleBgResource(int id) { return BG_EDIT_TITLE_RESOURCES[id]; } } + /** + * 获取默认背景颜色ID + * 逻辑:若用户启用随机背景,则随机返回一个颜色;否则返回默认颜色 + * @param context 应用上下文 + * @return 默认背景颜色逻辑标识 + */ public static int getDefaultBgId(Context context) { if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { + // 随机返回一个有效颜色标识 return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length); } else { return BG_DEFAULT_COLOR; } } + /** + * 便签列表项背景资源管理类 + * 管理列表项在不同位置的背景资源(首项/中间项/末项/单项) + */ public static class NoteItemBgResources { - private final static int [] BG_FIRST_RESOURCES = new int [] { - R.drawable.list_yellow_up, - R.drawable.list_blue_up, - R.drawable.list_white_up, - R.drawable.list_green_up, - R.drawable.list_red_up + // 列表首项背景资源数组 + private final static int[] BG_FIRST_RESOURCES = new int[]{ + R.drawable.list_yellow_up, // 黄色首项背景 + R.drawable.list_blue_up, // 蓝色首项背景 + R.drawable.list_white_up, // 白色首项背景 + R.drawable.list_green_up, // 绿色首项背景 + R.drawable.list_red_up // 红色首项背景 }; - private final static int [] BG_NORMAL_RESOURCES = new int [] { - R.drawable.list_yellow_middle, - R.drawable.list_blue_middle, - R.drawable.list_white_middle, - R.drawable.list_green_middle, - R.drawable.list_red_middle + // 列表中间项背景资源数组 + private final static int[] BG_NORMAL_RESOURCES = new int[]{ + R.drawable.list_yellow_middle, // 黄色中间项背景 + R.drawable.list_blue_middle, // 蓝色中间项背景 + R.drawable.list_white_middle, // 白色中间项背景 + R.drawable.list_green_middle, // 绿色中间项背景 + R.drawable.list_red_middle // 红色中间项背景 }; - private final static int [] BG_LAST_RESOURCES = new int [] { - R.drawable.list_yellow_down, - R.drawable.list_blue_down, - R.drawable.list_white_down, - R.drawable.list_green_down, - R.drawable.list_red_down, + // 列表末项背景资源数组 + private final static int[] BG_LAST_RESOURCES = new int[]{ + R.drawable.list_yellow_down, // 黄色末项背景 + R.drawable.list_blue_down, // 蓝色末项背景 + R.drawable.list_white_down, // 白色末项背景 + R.drawable.list_green_down, // 绿色末项背景 + R.drawable.list_red_down // 红色末项背景 }; - private final static int [] BG_SINGLE_RESOURCES = new int [] { - R.drawable.list_yellow_single, - R.drawable.list_blue_single, - R.drawable.list_white_single, - R.drawable.list_green_single, - R.drawable.list_red_single + // 列表单项背景资源数组(仅有一项时) + private final static int[] BG_SINGLE_RESOURCES = new int[]{ + R.drawable.list_yellow_single, // 黄色单项背景 + R.drawable.list_blue_single, // 蓝色单项背景 + R.drawable.list_white_single, // 白色单项背景 + R.drawable.list_green_single, // 绿色单项背景 + R.drawable.list_red_single // 红色单项背景 }; + /** + * 获取列表首项背景资源ID + * @param id 颜色逻辑标识(0-4) + * @return 对应的首项背景资源ID + */ public static int getNoteBgFirstRes(int id) { return BG_FIRST_RESOURCES[id]; } + /** + * 获取列表末项背景资源ID + * @param id 颜色逻辑标识(0-4) + * @return 对应的末项背景资源ID + */ public static int getNoteBgLastRes(int id) { return BG_LAST_RESOURCES[id]; } + /** + * 获取列表单项背景资源ID + * @param id 颜色逻辑标识(0-4) + * @return 对应的单项背景资源ID + */ public static int getNoteBgSingleRes(int id) { return BG_SINGLE_RESOURCES[id]; } + /** + * 获取列表中间项背景资源ID + * @param id 颜色逻辑标识(0-4) + * @return 对应的中间项背景资源ID + */ public static int getNoteBgNormalRes(int id) { return BG_NORMAL_RESOURCES[id]; } + /** + * 获取文件夹背景资源ID + * @return 文件夹背景资源ID + */ public static int getFolderBgRes() { return R.drawable.list_folder; } } + /** + * 桌面小部件背景资源管理类 + * 管理不同尺寸小部件的背景资源 + */ public static class WidgetBgResources { - private final static int [] BG_2X_RESOURCES = new int [] { - R.drawable.widget_2x_yellow, - R.drawable.widget_2x_blue, - R.drawable.widget_2x_white, - R.drawable.widget_2x_green, - R.drawable.widget_2x_red, + // 2x2小部件背景资源数组 + private final static int[] BG_2X_RESOURCES = new int[]{ + R.drawable.widget_2x_yellow, // 黄色2x2小部件背景 + R.drawable.widget_2x_blue, // 蓝色2x2小部件背景 + R.drawable.widget_2x_white, // 白色2x2小部件背景 + R.drawable.widget_2x_green, // 绿色2x2小部件背景 + R.drawable.widget_2x_red // 红色2x2小部件背景 }; + /** + * 获取2x2小部件背景资源ID + * @param id 颜色逻辑标识(0-4) + * @return 对应的2x2小部件背景资源ID + */ public static int getWidget2xBgResource(int id) { return BG_2X_RESOURCES[id]; } - private final static int [] BG_4X_RESOURCES = new int [] { - R.drawable.widget_4x_yellow, - R.drawable.widget_4x_blue, - R.drawable.widget_4x_white, - R.drawable.widget_4x_green, - R.drawable.widget_4x_red + // 4x4小部件背景资源数组 + private final static int[] BG_4X_RESOURCES = new int[]{ + R.drawable.widget_4x_yellow, // 黄色4x4小部件背景 + R.drawable.widget_4x_blue, // 蓝色4x4小部件背景 + R.drawable.widget_4x_white, // 白色4x4小部件背景 + R.drawable.widget_4x_green, // 绿色4x4小部件背景 + R.drawable.widget_4x_red // 红色4x4小部件背景 }; + /** + * 获取4x4小部件背景资源ID + * @param id 颜色逻辑标识(0-4) + * @return 对应的4x4小部件背景资源ID + */ public static int getWidget4xBgResource(int id) { return BG_4X_RESOURCES[id]; } } + /** + * 文本样式资源管理类 + * 管理不同字体大小的文本样式资源 + */ public static class TextAppearanceResources { - private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] { - R.style.TextAppearanceNormal, - R.style.TextAppearanceMedium, - R.style.TextAppearanceLarge, - R.style.TextAppearanceSuper + // 文本样式资源数组(按字体大小顺序排列) + private final static int[] TEXTAPPEARANCE_RESOURCES = new int[]{ + R.style.TextAppearanceNormal, // 普通文本样式 + R.style.TextAppearanceMedium, // 中等文本样式 + R.style.TextAppearanceLarge, // 大文本样式 + R.style.TextAppearanceSuper // 超大文本样式 }; + /** + * 获取文本样式资源ID + * @param id 字体大小逻辑标识(0-3) + * @return 对应的文本样式资源ID + */ public static int getTexAppearanceResource(int id) { /** - * HACKME: Fix bug of store the resource id in shared preference. - * The id may larger than the length of resources, in this case, - * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} + * 修复偏好设置中存储的资源ID可能超出范围的问题 + * 若ID无效则返回默认字体大小 */ if (id >= TEXTAPPEARANCE_RESOURCES.length) { return BG_DEFAULT_FONT_SIZE; @@ -174,8 +265,12 @@ public class ResourceParser { return TEXTAPPEARANCE_RESOURCES[id]; } + /** + * 获取文本样式资源数量 + * @return 文本样式资源数量 + */ public static int getResourcesSize() { return TEXTAPPEARANCE_RESOURCES.length; } } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/ui/AlarmAlertActivity.java b/java/net/micode/notes/ui/AlarmAlertActivity.java index 85723be..97df512 100644 --- a/java/net/micode/notes/ui/AlarmAlertActivity.java +++ b/java/net/micode/notes/ui/AlarmAlertActivity.java @@ -39,21 +39,39 @@ import net.micode.notes.tool.DataUtils; import java.io.IOException; - +/** + * 便签提醒闹钟活动 + * 用于显示便签提醒通知并播放提醒声音 + * 支持在锁屏状态下显示,确保用户不会错过重要提醒 + * 提供快速查看和进入便签编辑的功能 + */ public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { + // 便签ID private long mNoteId; + // 便签摘要 private String mSnippet; + // 摘要预览最大长度 private static final int SNIPPET_PREW_MAX_LEN = 60; + // 媒体播放器,用于播放提醒声音 MediaPlayer mPlayer; + /** + * 活动创建时调用 + * 初始化界面,设置窗口属性,播放提醒声音 + * @param savedInstanceState 保存的实例状态 + */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + // 不显示标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); + // 获取窗口并设置标志位 final Window win = getWindow(); + // 允许在锁屏状态下显示 win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); + // 如果屏幕关闭,设置唤醒屏幕的标志位 if (!isScreenOn()) { win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON @@ -61,11 +79,13 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); } + // 从意图中获取便签ID和摘要 Intent intent = getIntent(); try { mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); + // 限制摘要长度,超过最大长度时添加省略号 mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) : mSnippet; @@ -74,65 +94,92 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD return; } + // 初始化媒体播放器 mPlayer = new MediaPlayer(); + // 检查便签是否存在且有效 if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { + // 显示提醒对话框 showActionDialog(); + // 播放提醒声音 playAlarmSound(); } else { + // 便签不存在,结束活动 finish(); } } + /** + * 检查屏幕是否开启 + * @return 屏幕开启返回true,否则返回false + */ private boolean isScreenOn() { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); return pm.isScreenOn(); } + /** + * 播放闹钟提醒声音 + * 根据系统设置选择合适的音频流 + */ private void playAlarmSound() { + // 获取系统默认闹钟铃声URI Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); + // 获取受静音模式影响的音频流设置 int silentModeStreams = Settings.System.getInt(getContentResolver(), Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); + // 根据设置选择音频流类型 if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { mPlayer.setAudioStreamType(silentModeStreams); } else { mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); } + try { + // 设置音频源并准备播放 mPlayer.setDataSource(this, url); mPlayer.prepare(); + // 设置循环播放 mPlayer.setLooping(true); mPlayer.start(); } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { - // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { - // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { - // TODO Auto-generated catch block e.printStackTrace(); } } + /** + * 显示提醒操作对话框 + * 包含便签摘要和操作按钮 + */ private void showActionDialog() { AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle(R.string.app_name); dialog.setMessage(mSnippet); dialog.setPositiveButton(R.string.notealert_ok, this); + // 仅在屏幕开启时显示"进入"按钮 if (isScreenOn()) { dialog.setNegativeButton(R.string.notealert_enter, this); } + // 显示对话框并设置关闭监听器 dialog.show().setOnDismissListener(this); } + /** + * 处理对话框按钮点击事件 + * @param dialog 对话框 + * @param which 点击的按钮 + */ public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_NEGATIVE: + // 点击"进入"按钮,打开便签编辑界面 Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(Intent.EXTRA_UID, mNoteId); @@ -143,11 +190,20 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD } } + /** + * 处理对话框关闭事件 + * 停止播放声音并结束活动 + * @param dialog 对话框 + */ public void onDismiss(DialogInterface dialog) { stopAlarmSound(); finish(); } + /** + * 停止播放闹钟声音 + * 释放媒体播放器资源 + */ private void stopAlarmSound() { if (mPlayer != null) { mPlayer.stop(); @@ -155,4 +211,4 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD mPlayer = null; } } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/ui/AlarmInitReceiver.java b/java/net/micode/notes/ui/AlarmInitReceiver.java index f221202..6ed7244 100644 --- a/java/net/micode/notes/ui/AlarmInitReceiver.java +++ b/java/net/micode/notes/ui/AlarmInitReceiver.java @@ -27,39 +27,93 @@ import android.database.Cursor; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; - +/** + * 闹钟初始化接收器 - 在设备启动后重新设置所有未来的提醒闹钟 + * + * 功能: + * 1. 监听系统启动完成广播(BOOT_COMPLETED) + * 2. 查询所有需要未来提醒的便签 + * 3. 为每个便签重新设置闹钟 + * + * 注意:此接收器需要在AndroidManifest.xml中注册BOOT_COMPLETED权限 + */ public class AlarmInitReceiver extends BroadcastReceiver { - + // 查询需要的列:便签ID和提醒时间 private static final String [] PROJECTION = new String [] { - NoteColumns.ID, - NoteColumns.ALERTED_DATE + NoteColumns.ID, + NoteColumns.ALERTED_DATE }; - private static final int COLUMN_ID = 0; - private static final int COLUMN_ALERTED_DATE = 1; + // 列索引常量 + private static final int COLUMN_ID = 0; // 便签ID的列索引 + private static final int COLUMN_ALERTED_DATE = 1; // 提醒时间的列索引 + /** + * 接收广播时的处理逻辑(主要处理设备启动完成广播) + * @param context 上下文对象 + * @param intent 接收到的广播意图 + */ @Override public void onReceive(Context context, Intent intent) { + // 获取当前系统时间(用于筛选未来提醒) long currentDate = System.currentTimeMillis(); - Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, - PROJECTION, - NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, - new String[] { String.valueOf(currentDate) }, - null); + + /** + * 查询所有符合条件的便签: + * - 提醒时间大于当前时间(未来提醒) + * - 类型为普通便签(不包括文件夹等) + */ + Cursor c = context.getContentResolver().query( + Notes.CONTENT_NOTE_URI, // 便签内容URI + PROJECTION, // 需要查询的列 + NoteColumns.ALERTED_DATE + ">? AND " + // 提醒时间 > 当前时间 + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, // 类型为普通便签 + new String[] { String.valueOf(currentDate) }, // 当前时间作为参数 + null); // 无排序要求 if (c != null) { + // 遍历查询结果 if (c.moveToFirst()) { do { + // 获取便签的提醒时间 long alertDate = c.getLong(COLUMN_ALERTED_DATE); + // 获取便签ID + long noteId = c.getLong(COLUMN_ID); + + // 创建闹钟触发时发送的广播意图 Intent sender = new Intent(context, AlarmReceiver.class); - sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); - PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); - AlarmManager alermManager = (AlarmManager) context + // 设置便签URI作为数据标识(AlarmReceiver可通过此URI获取便签内容) + sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId)); + + /** + * 创建PendingIntent: + * - 使用广播类型 + * - requestCode为0(相同noteId会覆盖之前的闹钟) + * - FLAG_UPDATE_CURRENT:如果已存在则更新其extra数据 + */ + PendingIntent pendingIntent = PendingIntent.getBroadcast( + context, + 0, + sender, + PendingIntent.FLAG_UPDATE_CURRENT); + + // 获取系统闹钟服务 + AlarmManager alarmManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); - alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); - } while (c.moveToNext()); + + /** + * 设置精确闹钟: + * - RTC_WAKEUP:在指定时间唤醒设备并触发闹钟 + * - alertDate:提醒时间(毫秒级时间戳) + * - pendingIntent:触发时执行的广播 + */ + if (alarmManager != null) { + alarmManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + } + } while (c.moveToNext()); // 处理下一个便签 } + // 关闭游标释放资源 c.close(); } } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/ui/AlarmReceiver.java b/java/net/micode/notes/ui/AlarmReceiver.java index 54e503b..5cc07a6 100644 --- a/java/net/micode/notes/ui/AlarmReceiver.java +++ b/java/net/micode/notes/ui/AlarmReceiver.java @@ -20,11 +20,30 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; +/** + * 闹钟触发广播接收器 + * 核心功能:响应便签提醒闹钟触发事件 + * 工作流程:接收到闹钟触发广播后,启动提醒界面Activity + * 设计特点: + * - 支持在后台启动Activity(添加NEW_TASK标志) + * - 传递完整意图参数至提醒界面 + */ public class AlarmReceiver extends BroadcastReceiver { + /** + * 广播接收处理逻辑 + * @param context 应用上下文(用于启动Activity) + * @param intent 触发广播的意图(包含便签URI等参数) + */ @Override public void onReceive(Context context, Intent intent) { - intent.setClass(context, AlarmAlertActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); + // 构建提醒界面启动意图 + Intent alertIntent = new Intent(intent); // 复制原始意图参数 + alertIntent.setClass(context, AlarmAlertActivity.class); // 指定启动提醒界面 + + // 添加必要标志位确保Activity正确启动 + alertIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 在新任务栈中启动 + + // 启动提醒界面(由于在广播中启动Activity,必须使用NEW_TASK标志) + context.startActivity(alertIntent); } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/ui/DateTimePicker.java b/java/net/micode/notes/ui/DateTimePicker.java index 496b0cd..a95cc14 100644 --- a/java/net/micode/notes/ui/DateTimePicker.java +++ b/java/net/micode/notes/ui/DateTimePicker.java @@ -21,64 +21,93 @@ import java.util.Calendar; import net.micode.notes.R; - import android.content.Context; import android.text.format.DateFormat; import android.view.View; import android.widget.FrameLayout; import android.widget.NumberPicker; +/** + * 日期时间选择器 + * 自定义视图组件,用于选择日期和时间 + * 支持: + * - 日期选择(星期视图) + * - 时间选择(支持12/24小时制) + * - 实时监听日期时间变化 + * 设计特点: + * - 使用NumberPicker实现滚轮选择效果 + * - 支持日期循环选择(前后一周) + * - 自动处理AM/PM转换 + */ public class DateTimePicker extends FrameLayout { - + // 默认启用状态 private static final boolean DEFAULT_ENABLE_STATE = true; + // 时间格式相关常量 private static final int HOURS_IN_HALF_DAY = 12; private static final int HOURS_IN_ALL_DAY = 24; private static final int DAYS_IN_ALL_WEEK = 7; + + // 日期选择器范围 private static final int DATE_SPINNER_MIN_VAL = 0; private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; + + // 小时选择器范围(24小时制) private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; + + // 小时选择器范围(12小时制) private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; + + // 分钟选择器范围 private static final int MINUT_SPINNER_MIN_VAL = 0; private static final int MINUT_SPINNER_MAX_VAL = 59; + + // 上下午选择器范围 private static final int AMPM_SPINNER_MIN_VAL = 0; private static final int AMPM_SPINNER_MAX_VAL = 1; - private final NumberPicker mDateSpinner; - private final NumberPicker mHourSpinner; - private final NumberPicker mMinuteSpinner; - private final NumberPicker mAmPmSpinner; - private Calendar mDate; - - private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; + // 界面组件引用 + private final NumberPicker mDateSpinner; // 日期选择器 + private final NumberPicker mHourSpinner; // 小时选择器 + private final NumberPicker mMinuteSpinner; // 分钟选择器 + private final NumberPicker mAmPmSpinner; // 上下午选择器 - private boolean mIsAm; + // 日期时间数据 + private Calendar mDate; // 当前选择的日期时间 - private boolean mIs24HourView; + // 显示相关变量 + private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; // 日期显示文本 - private boolean mIsEnabled = DEFAULT_ENABLE_STATE; - - private boolean mInitialising; + // 状态变量 + private boolean mIsAm; // 是否为上午 + private boolean mIs24HourView; // 是否为24小时制 + private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 组件启用状态 + private boolean mInitialising; // 初始化标志 + // 监听器 private OnDateTimeChangedListener mOnDateTimeChangedListener; + // 日期选择变化监听器 private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + // 日期变化时更新日历数据 mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); updateDateControl(); onDateTimeChanged(); } }; + // 小时选择变化监听器 private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { boolean isDateChanged = false; Calendar cal = Calendar.getInstance(); if (!mIs24HourView) { + // 12小时制特殊处理 if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { cal.setTimeInMillis(mDate.getTimeInMillis()); cal.add(Calendar.DAY_OF_YEAR, 1); @@ -88,12 +117,14 @@ public class DateTimePicker extends FrameLayout { cal.add(Calendar.DAY_OF_YEAR, -1); isDateChanged = true; } + // 上下午切换处理 if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY || oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { mIsAm = !mIsAm; updateAmPmControl(); } } else { + // 24小时制特殊处理 if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { cal.setTimeInMillis(mDate.getTimeInMillis()); cal.add(Calendar.DAY_OF_YEAR, 1); @@ -104,9 +135,11 @@ public class DateTimePicker extends FrameLayout { isDateChanged = true; } } + // 更新小时数据 int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY); mDate.set(Calendar.HOUR_OF_DAY, newHour); onDateTimeChanged(); + // 日期变化时更新日期选择器 if (isDateChanged) { setCurrentYear(cal.get(Calendar.YEAR)); setCurrentMonth(cal.get(Calendar.MONTH)); @@ -115,21 +148,25 @@ public class DateTimePicker extends FrameLayout { } }; + // 分钟选择变化监听器 private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { int minValue = mMinuteSpinner.getMinValue(); int maxValue = mMinuteSpinner.getMaxValue(); int offset = 0; + // 分钟滚轮边界处理(0<->59) if (oldVal == maxValue && newVal == minValue) { offset += 1; } else if (oldVal == minValue && newVal == maxValue) { offset -= 1; } if (offset != 0) { + // 分钟边界变化时调整小时 mDate.add(Calendar.HOUR_OF_DAY, offset); mHourSpinner.setValue(getCurrentHour()); updateDateControl(); + // 调整上下午状态 int newHour = getCurrentHourOfDay(); if (newHour >= HOURS_IN_HALF_DAY) { mIsAm = false; @@ -139,14 +176,17 @@ public class DateTimePicker extends FrameLayout { updateAmPmControl(); } } + // 更新分钟数据 mDate.set(Calendar.MINUTE, newVal); onDateTimeChanged(); } }; + // 上下午选择变化监听器 private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + // 上下午切换时调整小时 mIsAm = !mIsAm; if (mIsAm) { mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); @@ -158,39 +198,73 @@ public class DateTimePicker extends FrameLayout { } }; + /** + * 日期时间变化监听器接口 + * 用于监听日期时间选择变化 + */ public interface OnDateTimeChangedListener { + /** + * 日期时间变化时回调 + * @param view 日期时间选择器视图 + * @param year 年份 + * @param month 月份(0-11) + * @param dayOfMonth 日期 + * @param hourOfDay 小时(24小时制) + * @param minute 分钟 + */ void onDateTimeChanged(DateTimePicker view, int year, int month, - int dayOfMonth, int hourOfDay, int minute); + int dayOfMonth, int hourOfDay, int minute); } + /** + * 构造函数 + * @param context 上下文 + */ public DateTimePicker(Context context) { this(context, System.currentTimeMillis()); } + /** + * 构造函数 + * @param context 上下文 + * @param date 初始日期时间(毫秒) + */ public DateTimePicker(Context context, long date) { this(context, date, DateFormat.is24HourFormat(context)); } + /** + * 构造函数 + * @param context 上下文 + * @param date 初始日期时间(毫秒) + * @param is24HourView 是否使用24小时制 + */ public DateTimePicker(Context context, long date, boolean is24HourView) { super(context); mDate = Calendar.getInstance(); mInitialising = true; mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; + // 加载布局 inflate(context, R.layout.datetime_picker, this); + // 初始化日期选择器 mDateSpinner = (NumberPicker) findViewById(R.id.date); mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); + // 初始化小时选择器 mHourSpinner = (NumberPicker) findViewById(R.id.hour); mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); - mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); + + // 初始化分钟选择器 + mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL); mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL); mMinuteSpinner.setOnLongPressUpdateInterval(100); mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); + // 初始化上下午选择器 String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); @@ -198,22 +272,28 @@ public class DateTimePicker extends FrameLayout { mAmPmSpinner.setDisplayedValues(stringsForAmPm); mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); - // update controls to initial state + // 更新控件到初始状态 updateDateControl(); updateHourControl(); updateAmPmControl(); + // 设置时间格式 set24HourView(is24HourView); - // set to current time + // 设置当前时间 setCurrentDate(date); + // 设置启用状态 setEnabled(isEnabled()); - // set the content descriptions + // 设置内容描述 mInitialising = false; } + /** + * 设置控件启用状态 + * @param enabled 是否启用 + */ @Override public void setEnabled(boolean enabled) { if (mIsEnabled == enabled) { @@ -227,24 +307,26 @@ public class DateTimePicker extends FrameLayout { mIsEnabled = enabled; } + /** + * 获取控件启用状态 + * @return 是否启用 + */ @Override public boolean isEnabled() { return mIsEnabled; } /** - * Get the current date in millis - * - * @return the current date in millis + * 获取当前日期时间(毫秒) + * @return 当前日期时间(毫秒) */ public long getCurrentDateInTimeMillis() { return mDate.getTimeInMillis(); } /** - * Set the current date - * - * @param date The current date in millis + * 设置当前日期时间(毫秒) + * @param date 日期时间(毫秒) */ public void setCurrentDate(long date) { Calendar cal = Calendar.getInstance(); @@ -254,16 +336,15 @@ public class DateTimePicker extends FrameLayout { } /** - * Set the current date - * - * @param year The current year - * @param month The current month - * @param dayOfMonth The current dayOfMonth - * @param hourOfDay The current hourOfDay - * @param minute The current minute + * 设置当前日期时间 + * @param year 年份 + * @param month 月份(0-11) + * @param dayOfMonth 日期 + * @param hourOfDay 小时(24小时制) + * @param minute 分钟 */ public void setCurrentDate(int year, int month, - int dayOfMonth, int hourOfDay, int minute) { + int dayOfMonth, int hourOfDay, int minute) { setCurrentYear(year); setCurrentMonth(month); setCurrentDay(dayOfMonth); @@ -272,18 +353,16 @@ public class DateTimePicker extends FrameLayout { } /** - * Get current year - * - * @return The current year + * 获取当前年份 + * @return 年份 */ public int getCurrentYear() { return mDate.get(Calendar.YEAR); } /** - * Set current year - * - * @param year The current year + * 设置当前年份 + * @param year 年份 */ public void setCurrentYear(int year) { if (!mInitialising && year == getCurrentYear()) { @@ -295,18 +374,16 @@ public class DateTimePicker extends FrameLayout { } /** - * Get current month in the year - * - * @return The current month in the year + * 获取当前月份(0-11) + * @return 月份(0-11) */ public int getCurrentMonth() { return mDate.get(Calendar.MONTH); } /** - * Set current month in the year - * - * @param month The month in the year + * 设置当前月份(0-11) + * @param month 月份(0-11) */ public void setCurrentMonth(int month) { if (!mInitialising && month == getCurrentMonth()) { @@ -318,18 +395,16 @@ public class DateTimePicker extends FrameLayout { } /** - * Get current day of the month - * - * @return The day of the month + * 获取当前日期 + * @return 日期 */ public int getCurrentDay() { return mDate.get(Calendar.DAY_OF_MONTH); } /** - * Set current day of the month - * - * @param dayOfMonth The day of the month + * 设置当前日期 + * @param dayOfMonth 日期 */ public void setCurrentDay(int dayOfMonth) { if (!mInitialising && dayOfMonth == getCurrentDay()) { @@ -341,13 +416,17 @@ public class DateTimePicker extends FrameLayout { } /** - * Get current hour in 24 hour mode, in the range (0~23) - * @return The current hour in 24 hour mode + * 获取当前小时(24小时制) + * @return 小时(0-23) */ public int getCurrentHourOfDay() { return mDate.get(Calendar.HOUR_OF_DAY); } + /** + * 获取当前小时(根据显示模式) + * @return 小时 + */ private int getCurrentHour() { if (mIs24HourView){ return getCurrentHourOfDay(); @@ -362,9 +441,8 @@ public class DateTimePicker extends FrameLayout { } /** - * Set current hour in 24 hour mode, in the range (0~23) - * - * @param hourOfDay + * 设置当前小时(24小时制) + * @param hourOfDay 小时(0-23) */ public void setCurrentHour(int hourOfDay) { if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { @@ -390,16 +468,16 @@ public class DateTimePicker extends FrameLayout { } /** - * Get currentMinute - * - * @return The Current Minute + * 获取当前分钟 + * @return 分钟(0-59) */ public int getCurrentMinute() { return mDate.get(Calendar.MINUTE); } /** - * Set current minute + * 设置当前分钟 + * @param minute 分钟(0-59) */ public void setCurrentMinute(int minute) { if (!mInitialising && minute == getCurrentMinute()) { @@ -411,22 +489,23 @@ public class DateTimePicker extends FrameLayout { } /** - * @return true if this is in 24 hour view else false. + * 是否使用24小时制 + * @return 是否使用24小时制 */ - public boolean is24HourView () { + public boolean is24HourView() { return mIs24HourView; } /** - * Set whether in 24 hour or AM/PM mode. - * - * @param is24HourView True for 24 hour mode. False for AM/PM mode. + * 设置时间显示模式 + * @param is24HourView 是否使用24小时制 */ public void set24HourView(boolean is24HourView) { if (mIs24HourView == is24HourView) { return; } mIs24HourView = is24HourView; + // 显示/隐藏上下午选择器 mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); int hour = getCurrentHourOfDay(); updateHourControl(); @@ -434,11 +513,15 @@ public class DateTimePicker extends FrameLayout { updateAmPmControl(); } + /** + * 更新日期选择器显示 + */ private void updateDateControl() { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(mDate.getTimeInMillis()); cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); mDateSpinner.setDisplayedValues(null); + // 生成未来一周的日期显示文本 for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) { cal.add(Calendar.DAY_OF_YEAR, 1); mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal); @@ -448,6 +531,9 @@ public class DateTimePicker extends FrameLayout { mDateSpinner.invalidate(); } + /** + * 更新上下午选择器显示 + */ private void updateAmPmControl() { if (mIs24HourView) { mAmPmSpinner.setVisibility(View.GONE); @@ -458,6 +544,9 @@ public class DateTimePicker extends FrameLayout { } } + /** + * 更新小时选择器显示范围 + */ private void updateHourControl() { if (mIs24HourView) { mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); @@ -469,17 +558,20 @@ public class DateTimePicker extends FrameLayout { } /** - * Set the callback that indicates the 'Set' button has been pressed. - * @param callback the callback, if null will do nothing + * 设置日期时间变化监听器 + * @param callback 监听器 */ public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { mOnDateTimeChangedListener = callback; } + /** + * 通知日期时间已变化 + */ private void onDateTimeChanged() { if (mOnDateTimeChangedListener != null) { mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); } } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/ui/DateTimePickerDialog.java b/java/net/micode/notes/ui/DateTimePickerDialog.java index 2c47ba4..11070fe 100644 --- a/java/net/micode/notes/ui/DateTimePickerDialog.java +++ b/java/net/micode/notes/ui/DateTimePickerDialog.java @@ -29,62 +29,133 @@ import android.content.DialogInterface.OnClickListener; import android.text.format.DateFormat; import android.text.format.DateUtils; +/** + * 日期时间选择对话框 + * 封装DateTimePicker组件的对话框,用于选择具体的日期和时间 + * 核心功能: + * 1. 提供直观的日期时间选择界面 + * 2. 支持12/24小时制显示 + * 3. 实时预览选择结果 + * 4. 提供回调接口返回选择结果 + * + * 使用场景: + * - 便签提醒时间设置 + * - 事件日程安排 + */ public class DateTimePickerDialog extends AlertDialog implements OnClickListener { - + // 当前选择的日期时间 private Calendar mDate = Calendar.getInstance(); + + // 是否使用24小时制 private boolean mIs24HourView; + + // 日期时间设置回调 private OnDateTimeSetListener mOnDateTimeSetListener; + + // 日期时间选择器组件 private DateTimePicker mDateTimePicker; + /** + * 日期时间设置回调接口 + * 用于将用户选择的日期时间传递给调用者 + */ public interface OnDateTimeSetListener { + /** + * 当用户确认日期时间选择时回调 + * @param dialog 对话框实例 + * @param date 选择的日期时间(毫秒时间戳) + */ void OnDateTimeSet(AlertDialog dialog, long date); } + /** + * 构造函数 + * @param context 上下文 + * @param date 初始日期时间(毫秒时间戳) + */ public DateTimePickerDialog(Context context, long date) { super(context); + + // 初始化日期时间选择器组件 mDateTimePicker = new DateTimePicker(context); setView(mDateTimePicker); + + // 设置日期时间变化监听器 mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { public void onDateTimeChanged(DateTimePicker view, int year, int month, - int dayOfMonth, int hourOfDay, int minute) { + int dayOfMonth, int hourOfDay, int minute) { + // 更新日期时间数据 mDate.set(Calendar.YEAR, year); mDate.set(Calendar.MONTH, month); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.MINUTE, minute); + + // 更新对话框标题显示 updateTitle(mDate.getTimeInMillis()); } }); + + // 初始化日期时间数据 mDate.setTimeInMillis(date); - mDate.set(Calendar.SECOND, 0); + mDate.set(Calendar.SECOND, 0); // 忽略秒,保持时间精度为分钟 mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); + + // 设置对话框按钮 setButton(context.getString(R.string.datetime_dialog_ok), this); setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); + + // 设置24小时制显示模式(根据系统设置) set24HourView(DateFormat.is24HourFormat(this.getContext())); + + // 更新标题显示 updateTitle(mDate.getTimeInMillis()); } + /** + * 设置时间显示模式 + * @param is24HourView true:24小时制 false:12小时制 + */ public void set24HourView(boolean is24HourView) { mIs24HourView = is24HourView; + mDateTimePicker.set24HourView(is24HourView); } + /** + * 设置日期时间选择回调 + * @param callBack 回调接口 + */ public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { mOnDateTimeSetListener = callBack; } + /** + * 更新对话框标题显示 + * @param date 日期时间(毫秒时间戳) + */ private void updateTitle(long date) { + // 设置日期时间显示标志 int flag = - DateUtils.FORMAT_SHOW_YEAR | - DateUtils.FORMAT_SHOW_DATE | - DateUtils.FORMAT_SHOW_TIME; + DateUtils.FORMAT_SHOW_YEAR | // 显示年份 + DateUtils.FORMAT_SHOW_DATE | // 显示日期 + DateUtils.FORMAT_SHOW_TIME; // 显示时间 + + // 根据24小时制设置显示格式 flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; + + // 更新标题显示 setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); } + /** + * 处理对话框按钮点击事件 + * @param arg0 对话框接口 + * @param arg1 按钮标识 + */ public void onClick(DialogInterface arg0, int arg1) { + // 点击确定按钮时,通过回调返回选择的日期时间 if (mOnDateTimeSetListener != null) { mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); } } - } \ No newline at end of file diff --git a/java/net/micode/notes/ui/DropdownMenu.java b/java/net/micode/notes/ui/DropdownMenu.java index 613dc74..b1b7e2b 100644 --- a/java/net/micode/notes/ui/DropdownMenu.java +++ b/java/net/micode/notes/ui/DropdownMenu.java @@ -27,17 +27,50 @@ import android.widget.PopupMenu.OnMenuItemClickListener; import net.micode.notes.R; +/** + * 下拉菜单组件 + * 封装PopupMenu的自定义下拉菜单控件 + * 功能特点: + * - 提供简洁的下拉菜单交互 + * - 支持自定义菜单项 + * - 支持菜单项点击事件监听 + * - 适配不同屏幕尺寸和布局 + * + * 使用场景: + * - 工具栏操作选项 + * - 上下文菜单 + * - 筛选条件选择 + */ public class DropdownMenu { + // 触发下拉菜单的按钮 private Button mButton; + + // 系统PopupMenu实例 private PopupMenu mPopupMenu; + + // 菜单对象 private Menu mMenu; + /** + * 构造函数 + * @param context 上下文 + * @param button 触发菜单的按钮 + * @param menuId 菜单资源ID + */ public DropdownMenu(Context context, Button button, int menuId) { mButton = button; + + // 设置按钮背景为下拉菜单图标 mButton.setBackgroundResource(R.drawable.dropdown_icon); + + // 初始化PopupMenu mPopupMenu = new PopupMenu(context, mButton); mMenu = mPopupMenu.getMenu(); + + // 加载菜单资源 mPopupMenu.getMenuInflater().inflate(menuId, mMenu); + + // 设置按钮点击事件,显示下拉菜单 mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mPopupMenu.show(); @@ -45,17 +78,30 @@ public class DropdownMenu { }); } + /** + * 设置菜单项点击监听器 + * @param listener 菜单项点击监听器 + */ public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { if (mPopupMenu != null) { mPopupMenu.setOnMenuItemClickListener(listener); } } + /** + * 根据ID查找菜单项 + * @param id 菜单项ID + * @return 对应的菜单项 + */ public MenuItem findItem(int id) { return mMenu.findItem(id); } + /** + * 设置按钮标题 + * @param title 标题文本 + */ public void setTitle(CharSequence title) { mButton.setText(title); } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/ui/FoldersListAdapter.java b/java/net/micode/notes/ui/FoldersListAdapter.java index 96b77da..6288c76 100644 --- a/java/net/micode/notes/ui/FoldersListAdapter.java +++ b/java/net/micode/notes/ui/FoldersListAdapter.java @@ -28,53 +28,107 @@ import net.micode.notes.R; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; - +/** + * 文件夹列表适配器 + * 用于在ListView/RecyclerView中展示便签文件夹列表 + * 核心功能: + * 1. 从数据库查询文件夹数据 + * 2. 自定义渲染文件夹名称 + * 3. 特殊处理根文件夹显示逻辑 + * 设计特点: + * - 使用CursorAdapter优化大数据量展示性能 + * - 复用ViewHolder减少内存占用 + * - 支持动态更新文件夹列表 + */ public class FoldersListAdapter extends CursorAdapter { - public static final String [] PROJECTION = { - NoteColumns.ID, - NoteColumns.SNIPPET + // 数据库查询投影字段 + public static final String[] PROJECTION = { + NoteColumns.ID, // 文件夹ID + NoteColumns.SNIPPET // 文件夹名称 }; - public static final int ID_COLUMN = 0; + // 投影字段索引(提升查询效率) + public static final int ID_COLUMN = 0; public static final int NAME_COLUMN = 1; + /** + * 构造函数 + * @param context 应用上下文 + * @param c 数据源Cursor + */ public FoldersListAdapter(Context context, Cursor c) { - super(context, c); - // TODO Auto-generated constructor stub + super(context, c, 0); // 0表示默认行为,不自动重新查询 } + /** + * 创建新的列表项视图 + * @param context 上下文 + * @param cursor 数据游标 + * @param parent 父容器 + * @return 文件夹列表项视图 + */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return new FolderListItem(context); } + /** + * 将数据绑定到已创建的视图 + * @param view 目标视图 + * @param context 上下文 + * @param cursor 数据游标 + */ @Override public void bindView(View view, Context context, Cursor cursor) { if (view instanceof FolderListItem) { - String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context - .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + // 特殊处理根文件夹名称显示 + String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? + context.getString(R.string.menu_move_parent_folder) : + cursor.getString(NAME_COLUMN); + + // 绑定文件夹名称到视图 ((FolderListItem) view).bind(folderName); } } + /** + * 获取指定位置的文件夹名称 + * @param context 上下文 + * @param position 列表位置 + * @return 文件夹名称 + */ public String getFolderName(Context context, int position) { Cursor cursor = (Cursor) getItem(position); - return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context - .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? + context.getString(R.string.menu_move_parent_folder) : + cursor.getString(NAME_COLUMN); } + /** + * 文件夹列表项视图组件 + * 封装单个文件夹项的UI逻辑 + */ private class FolderListItem extends LinearLayout { - private TextView mName; + private TextView mName; // 文件夹名称显示文本框 + /** + * 构造函数 + * @param context 上下文 + */ public FolderListItem(Context context) { super(context); + // 加载布局文件 inflate(context, R.layout.folder_list_item, this); + // 获取名称文本框引用 mName = (TextView) findViewById(R.id.tv_folder_name); } + /** + * 绑定文件夹名称到视图 + * @param name 文件夹名称 + */ public void bind(String name) { mName.setText(name); } } - -} +} \ No newline at end of file diff --git a/java/net/micode/notes/ui/NoteEditActivity.java b/java/net/micode/notes/ui/NoteEditActivity.java index 862883b..19018b6 100644 --- a/java/net/micode/notes/ui/NoteEditActivity.java +++ b/java/net/micode/notes/ui/NoteEditActivity.java @@ -358,8 +358,8 @@ public class NoteEditActivity extends Activity implements OnClickListener, || ev.getX() > (x + view.getWidth()) || ev.getY() < y || ev.getY() > (y + view.getHeight())) { - return false; - } + return false; + } return true; } @@ -418,7 +418,7 @@ public class NoteEditActivity extends Activity implements OnClickListener, } intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { - mWorkingNote.getWidgetId() + mWorkingNote.getWidgetId() }); sendBroadcast(intent); diff --git a/java/net/micode/notes/ui/NoteItemData.java b/java/net/micode/notes/ui/NoteItemData.java index 0f5a878..2d0fd43 100644 --- a/java/net/micode/notes/ui/NoteItemData.java +++ b/java/net/micode/notes/ui/NoteItemData.java @@ -25,58 +25,76 @@ import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.tool.DataUtils; - +/** + * 便签项数据模型类 + * 用于存储和管理便签列表项的所有数据 + * 从数据库查询便签数据并封装为对象 + * 提供便签属性的访问方法和位置信息判断 + */ public class NoteItemData { - static final String [] PROJECTION = 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, - NoteColumns.WIDGET_ID, - NoteColumns.WIDGET_TYPE, + // 数据库查询投影字段(定义从数据库查询的列) + static final String[] PROJECTION = new String[]{ + NoteColumns.ID, // 便签ID + NoteColumns.ALERTED_DATE, // 提醒日期 + NoteColumns.BG_COLOR_ID, // 背景颜色ID + NoteColumns.CREATED_DATE, // 创建日期 + NoteColumns.HAS_ATTACHMENT, // 是否有附件 + NoteColumns.MODIFIED_DATE, // 修改日期 + NoteColumns.NOTES_COUNT, // 子便签数量(用于文件夹) + NoteColumns.PARENT_ID, // 父文件夹ID + NoteColumns.SNIPPET, // 便签摘要 + NoteColumns.TYPE, // 便签类型(普通便签、文件夹等) + NoteColumns.WIDGET_ID, // 小部件ID + NoteColumns.WIDGET_TYPE, // 小部件类型 }; - private static final int ID_COLUMN = 0; - private static final int ALERTED_DATE_COLUMN = 1; - private static final int BG_COLOR_ID_COLUMN = 2; - private static final int CREATED_DATE_COLUMN = 3; - private static final int HAS_ATTACHMENT_COLUMN = 4; - private static final int MODIFIED_DATE_COLUMN = 5; - private static final int NOTES_COUNT_COLUMN = 6; - private static final int PARENT_ID_COLUMN = 7; - private static final int SNIPPET_COLUMN = 8; - private static final int TYPE_COLUMN = 9; - private static final int WIDGET_ID_COLUMN = 10; - private static final int WIDGET_TYPE_COLUMN = 11; - - private long mId; - private long mAlertDate; - private int mBgColorId; - private long mCreatedDate; - private boolean mHasAttachment; - private long mModifiedDate; - private int mNotesCount; - private long mParentId; - private String mSnippet; - private int mType; - private int mWidgetId; - private int mWidgetType; - private String mName; - private String mPhoneNumber; - - private boolean mIsLastItem; - private boolean mIsFirstItem; - private boolean mIsOnlyOneItem; - private boolean mIsOneNoteFollowingFolder; - private boolean mIsMultiNotesFollowingFolder; - + // 投影字段索引(用于从Cursor中获取数据) + private static final int ID_COLUMN = 0; + private static final int ALERTED_DATE_COLUMN = 1; + private static final int BG_COLOR_ID_COLUMN = 2; + private static final int CREATED_DATE_COLUMN = 3; + private static final int HAS_ATTACHMENT_COLUMN = 4; + private static final int MODIFIED_DATE_COLUMN = 5; + private static final int NOTES_COUNT_COLUMN = 6; + private static final int PARENT_ID_COLUMN = 7; + private static final int SNIPPET_COLUMN = 8; + private static final int TYPE_COLUMN = 9; + private static final int WIDGET_ID_COLUMN = 10; + private static final int WIDGET_TYPE_COLUMN = 11; + + // 便签基本属性 + private long mId; // 便签ID + private long mAlertDate; // 提醒日期时间戳 + private int mBgColorId; // 背景颜色ID + private long mCreatedDate; // 创建日期时间戳 + private boolean mHasAttachment; // 是否有附件 + private long mModifiedDate; // 修改日期时间戳 + private int mNotesCount; // 子便签数量(用于文件夹) + private long mParentId; // 父文件夹ID + private String mSnippet; // 便签摘要 + private int mType; // 便签类型 + private int mWidgetId; // 小部件ID + private int mWidgetType; // 小部件类型 + + // 通话记录相关属性 + private String mName; // 联系人名称 + private String mPhoneNumber; // 电话号码 + + // 便签在列表中的位置信息 + private boolean mIsLastItem; // 是否是列表最后一项 + private boolean mIsFirstItem; // 是否是列表第一项 + private boolean mIsOnlyOneItem; // 是否是列表中唯一一项 + private boolean mIsOneNoteFollowingFolder; // 是否是文件夹后的单个便签 + private boolean mIsMultiNotesFollowingFolder; // 是否是文件夹后的多个便签之一 + + /** + * 构造函数 + * 从数据库Cursor中初始化便签项数据 + * @param context 应用上下文 + * @param cursor 包含便签数据的Cursor + */ public NoteItemData(Context context, Cursor cursor) { + // 从Cursor中获取便签基本信息 mId = cursor.getLong(ID_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); @@ -86,19 +104,24 @@ public class NoteItemData { mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); mParentId = cursor.getLong(PARENT_ID_COLUMN); mSnippet = cursor.getString(SNIPPET_COLUMN); + + // 移除便签摘要中的特殊标签 mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( NoteEditActivity.TAG_UNCHECKED, ""); + mType = cursor.getInt(TYPE_COLUMN); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); + // 处理通话记录便签的联系人信息 mPhoneNumber = ""; if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); if (!TextUtils.isEmpty(mPhoneNumber)) { + // 从联系人数据中获取联系人名称 mName = Contact.getContact(context, mPhoneNumber); if (mName == null) { - mName = mPhoneNumber; + mName = mPhoneNumber; // 没有联系人信息时使用电话号码 } } } @@ -106,9 +129,15 @@ public class NoteItemData { if (mName == null) { mName = ""; } + + // 检查便签在列表中的位置信息 checkPostion(cursor); } + /** + * 检查便签在列表中的位置 + * @param cursor 包含便签数据的Cursor + */ private void checkPostion(Cursor cursor) { mIsLastItem = cursor.isLast() ? true : false; mIsFirstItem = cursor.isFirst() ? true : false; @@ -116,17 +145,20 @@ public class NoteItemData { mIsMultiNotesFollowingFolder = false; mIsOneNoteFollowingFolder = false; + // 判断便签是否在文件夹之后 if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { int position = cursor.getPosition(); if (cursor.moveToPrevious()) { + // 检查前一项是否为文件夹或系统项 if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { if (cursor.getCount() > (position + 1)) { - mIsMultiNotesFollowingFolder = true; + mIsMultiNotesFollowingFolder = true; // 文件夹后有多个便签 } else { - mIsOneNoteFollowingFolder = true; + mIsOneNoteFollowingFolder = true; // 文件夹后仅有一个便签 } } + // 恢复Cursor位置 if (!cursor.moveToNext()) { throw new IllegalStateException("cursor move to previous but can't move back"); } @@ -134,91 +166,180 @@ public class NoteItemData { } } + /** + * 判断是否是文件夹后的单个便签 + * @return true表示是文件夹后的单个便签 + */ public boolean isOneFollowingFolder() { return mIsOneNoteFollowingFolder; } + /** + * 判断是否是文件夹后的多个便签之一 + * @return true表示是文件夹后的多个便签之一 + */ public boolean isMultiFollowingFolder() { return mIsMultiNotesFollowingFolder; } + /** + * 判断是否是列表最后一项 + * @return true表示是列表最后一项 + */ public boolean isLast() { return mIsLastItem; } + /** + * 获取通话记录的联系人名称 + * @return 联系人名称或电话号码 + */ public String getCallName() { return mName; } + /** + * 判断是否是列表第一项 + * @return true表示是列表第一项 + */ public boolean isFirst() { return mIsFirstItem; } + /** + * 判断是否是列表中唯一一项 + * @return true表示是列表中唯一一项 + */ public boolean isSingle() { return mIsOnlyOneItem; } + /** + * 获取便签ID + * @return 便签ID + */ public long getId() { return mId; } + /** + * 获取提醒日期时间戳 + * @return 提醒日期时间戳 + */ public long getAlertDate() { return mAlertDate; } + /** + * 获取创建日期时间戳 + * @return 创建日期时间戳 + */ public long getCreatedDate() { return mCreatedDate; } + /** + * 判断是否有附件 + * @return true表示有附件 + */ public boolean hasAttachment() { return mHasAttachment; } + /** + * 获取修改日期时间戳 + * @return 修改日期时间戳 + */ public long getModifiedDate() { return mModifiedDate; } + /** + * 获取背景颜色ID + * @return 背景颜色ID + */ public int getBgColorId() { return mBgColorId; } + /** + * 获取父文件夹ID + * @return 父文件夹ID + */ public long getParentId() { return mParentId; } + /** + * 获取子便签数量(用于文件夹) + * @return 子便签数量 + */ public int getNotesCount() { return mNotesCount; } - public long getFolderId () { + /** + * 获取文件夹ID(与父文件夹ID相同) + * @return 文件夹ID + */ + public long getFolderId() { return mParentId; } + /** + * 获取便签类型 + * @return 便签类型 + */ public int getType() { return mType; } + /** + * 获取小部件类型 + * @return 小部件类型 + */ public int getWidgetType() { return mWidgetType; } + /** + * 获取小部件ID + * @return 小部件ID + */ public int getWidgetId() { return mWidgetId; } + /** + * 获取便签摘要 + * @return 便签摘要 + */ public String getSnippet() { return mSnippet; } + /** + * 判断是否设置了提醒 + * @return true表示设置了提醒 + */ public boolean hasAlert() { return (mAlertDate > 0); } + /** + * 判断是否是通话记录便签 + * @return true表示是通话记录便签 + */ public boolean isCallRecord() { return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); } + /** + * 从Cursor中获取便签类型 + * @param cursor 包含便签数据的Cursor + * @return 便签类型 + */ public static int getNoteType(Cursor cursor) { return cursor.getInt(TYPE_COLUMN); } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/ui/NotesListActivity.java b/java/net/micode/notes/ui/NotesListActivity.java index 9966422..b3b5aeb 100644 --- a/java/net/micode/notes/ui/NotesListActivity.java +++ b/java/net/micode/notes/ui/NotesListActivity.java @@ -78,96 +78,100 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashSet; +/** + * 便签列表主活动 + * 实现便签和文件夹的列表显示与管理功能 + * 主要功能包括: + * - 便签和文件夹的浏览、创建、编辑和删除 + * - 支持文件夹层级导航 + * - 提供批量操作功能(删除、移动) + * - 集成便签小部件(Widget)更新功能 + * - 支持便签数据导出备份 + */ public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { + // 查询令牌,用于标识不同的查询操作 private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; + private static final int FOLDER_LIST_QUERY_TOKEN = 1; - private static final int FOLDER_LIST_QUERY_TOKEN = 1; - + // 上下文菜单项ID private static final int MENU_FOLDER_DELETE = 0; - private static final int MENU_FOLDER_VIEW = 1; - private static final int MENU_FOLDER_CHANGE_NAME = 2; + // 偏好设置键 private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; + // 列表编辑状态枚举 private enum ListEditState { - NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER + NOTE_LIST, // 便签列表状态 + SUB_FOLDER, // 子文件夹状态 + CALL_RECORD_FOLDER // 通话记录文件夹状态 }; - private ListEditState mState; - - private BackgroundQueryHandler mBackgroundQueryHandler; - - private NotesListAdapter mNotesListAdapter; - - private ListView mNotesListView; - - private Button mAddNewNote; - - private boolean mDispatch; - - private int mOriginY; - - private int mDispatchY; - - private TextView mTitleBar; - - private long mCurrentFolderId; - - private ContentResolver mContentResolver; - - private ModeCallback mModeCallBack; - + // 成员变量 + private ListEditState mState; // 当前列表状态 + private BackgroundQueryHandler mBackgroundQueryHandler; // 后台查询处理器 + private NotesListAdapter mNotesListAdapter; // 便签列表适配器 + private ListView mNotesListView; // 便签列表视图 + private Button mAddNewNote; // 添加新便签按钮 + private boolean mDispatch; // 事件分发标志 + private int mOriginY; // 触摸事件原始Y坐标 + private int mDispatchY; // 事件分发Y坐标 + private TextView mTitleBar; // 标题栏 + private long mCurrentFolderId; // 当前文件夹ID + private ContentResolver mContentResolver; // 内容解析器 + private ModeCallback mModeCallBack; // 操作模式回调 private static final String TAG = "NotesListActivity"; + public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; // 列表滚动速率 + private NoteItemData mFocusNoteDataItem; // 聚焦的便签数据项 - public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; - - private NoteItemData mFocusNoteDataItem; - + // 查询条件 private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; - private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.NOTES_COUNT + ">0)"; + // 活动结果请求码 private final static int REQUEST_CODE_OPEN_NODE = 102; - private final static int REQUEST_CODE_NEW_NODE = 103; + private final static int REQUEST_CODE_NEW_NODE = 103; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.note_list); - initResources(); + initResources(); // 初始化资源和视图组件 - /** - * Insert an introduction when user firstly use this application - */ + // 首次使用应用时插入介绍便签 setAppInfoFromRawRes(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // 处理便签编辑活动返回结果 if (resultCode == RESULT_OK && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { - mNotesListAdapter.changeCursor(null); + mNotesListAdapter.changeCursor(null); // 刷新便签列表 } else { super.onActivityResult(requestCode, resultCode, data); } } + /** + * 从资源文件读取介绍内容并创建介绍便签 + */ private void setAppInfoFromRawRes() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { StringBuilder sb = new StringBuilder(); InputStream in = null; try { - in = getResources().openRawResource(R.raw.introduction); + // 读取介绍内容资源 + in = getResources().openRawResource(R.raw.introduction); if (in != null) { InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr); - char [] buf = new char[1024]; + char[] buf = new char[1024]; int len = 0; while ((len = br.read(buf)) > 0) { sb.append(buf, 0, len); @@ -180,16 +184,16 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt e.printStackTrace(); return; } finally { - if(in != null) { + if (in != null) { try { in.close(); } catch (IOException e) { - // TODO Auto-generated catch block e.printStackTrace(); } } } + // 创建介绍便签 WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, ResourceParser.RED); @@ -206,16 +210,21 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt @Override protected void onStart() { super.onStart(); - startAsyncNotesListQuery(); + startAsyncNotesListQuery(); // 启动异步便签列表查询 } + /** + * 初始化资源和视图组件 + */ private void initResources() { mContentResolver = this.getContentResolver(); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); - mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mCurrentFolderId = Notes.ID_ROOT_FOLDER; // 默认显示根文件夹 mNotesListView = (ListView) findViewById(R.id.notes_list); + // 添加列表页脚 mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), null, false); + // 设置列表项点击和长按监听器 mNotesListView.setOnItemClickListener(new OnListItemClickListener()); mNotesListView.setOnItemLongClickListener(this); mNotesListAdapter = new NotesListAdapter(this); @@ -228,18 +237,26 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt mOriginY = 0; mTitleBar = (TextView) findViewById(R.id.tv_title_bar); mState = ListEditState.NOTE_LIST; - mModeCallBack = new ModeCallback(); + mModeCallBack = new ModeCallback(); // 初始化操作模式回调 } + /** + * 操作模式回调类 + * 处理列表项多选模式的相关事件 + */ private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { private DropdownMenu mDropDownMenu; private ActionMode mActionMode; private MenuItem mMoveMenu; + /** + * 创建操作模式时调用 + */ public boolean onCreateActionMode(ActionMode mode, Menu menu) { getMenuInflater().inflate(R.menu.note_list_options, menu); menu.findItem(R.id.delete).setOnMenuItemClickListener(this); mMoveMenu = menu.findItem(R.id.move); + // 根据便签类型和文件夹数量设置移动菜单项可见性 if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER || DataUtils.getUserFolderCount(mContentResolver) == 0) { mMoveMenu.setVisible(false); @@ -252,26 +269,29 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt mNotesListView.setLongClickable(false); mAddNewNote.setVisibility(View.GONE); + // 设置自定义操作模式视图 View customView = LayoutInflater.from(NotesListActivity.this).inflate( R.layout.note_list_dropdown_menu, null); mode.setCustomView(customView); mDropDownMenu = new DropdownMenu(NotesListActivity.this, (Button) customView.findViewById(R.id.selection_menu), R.menu.note_list_dropdown); - mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ + mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); updateMenu(); return true; } - }); return true; } + /** + * 更新菜单状态 + */ private void updateMenu() { int selectedCount = mNotesListAdapter.getSelectedCount(); - // Update dropdown menu + // 更新下拉菜单标题 String format = getResources().getString(R.string.menu_select_title, selectedCount); mDropDownMenu.setTitle(format); MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); @@ -287,12 +307,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } public boolean onPrepareActionMode(ActionMode mode, Menu menu) { - // TODO Auto-generated method stub return false; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - // TODO Auto-generated method stub return false; } @@ -307,11 +325,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } public void onItemCheckedStateChanged(ActionMode mode, int position, long id, - boolean checked) { + boolean checked) { mNotesListAdapter.setCheckedItem(position, checked); updateMenu(); } + /** + * 菜单项点击处理 + */ public boolean onMenuItemClick(MenuItem item) { if (mNotesListAdapter.getSelectedCount() == 0) { Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), @@ -321,29 +342,32 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt int itemId = item.getItemId(); if (itemId == R.id.delete) { + // 显示删除确认对话框 AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(getString(R.string.alert_title_delete)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setMessage(getString(R.string.alert_message_delete_notes, - mNotesListAdapter.getSelectedCount())); + mNotesListAdapter.getSelectedCount())); builder.setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int which) { - batchDelete(); - } - }); + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + batchDelete(); // 批量删除便签 + } + }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); } else if (itemId == R.id.move) { - startQueryDestinationFolders(); - } else { - return false; + startQueryDestinationFolders(); // 查询目标文件夹 } return true; } } + /** + * 新便签按钮触摸监听器 + * 处理按钮透明区域的事件分发 + */ private class NewNoteOnTouchListener implements OnTouchListener { public boolean onTouch(View v, MotionEvent event) { @@ -356,21 +380,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt int newNoteViewHeight = mAddNewNote.getHeight(); int start = screenHeight - newNoteViewHeight; int eventY = start + (int) event.getY(); - /** - * Minus TitleBar's height - */ + // 减去标题栏高度(如果处于子文件夹状态) if (mState == ListEditState.SUB_FOLDER) { eventY -= mTitleBar.getHeight(); start -= mTitleBar.getHeight(); } /** - * HACKME:When click the transparent part of "New Note" button, dispatch - * the event to the list view behind this button. The transparent part of - * "New Note" button could be expressed by formula y=-0.12x+94(Unit:pixel) - * and the line top of the button. The coordinate based on left of the "New - * Note" button. The 94 represents maximum height of the transparent part. - * Notice that, if the background of the button changes, the formula should - * also change. This is very bad, just for the UI designer's strong requirement. + * 处理按钮透明区域的事件分发 + * 透明区域由公式 y=-0.12x+94 定义(基于按钮左侧坐标) */ if (event.getY() < (event.getX() * (-0.12) + 94)) { View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 @@ -408,15 +425,23 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt }; + /** + * 启动异步便签列表查询 + */ private void startAsyncNotesListQuery() { + // 根据当前文件夹设置查询条件 String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION : NORMAL_SELECTION; mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { - String.valueOf(mCurrentFolderId) + String.valueOf(mCurrentFolderId) }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); } + /** + * 后台查询处理器 + * 处理异步查询结果 + */ private final class BackgroundQueryHandler extends AsyncQueryHandler { public BackgroundQueryHandler(ContentResolver contentResolver) { super(contentResolver); @@ -426,11 +451,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt protected void onQueryComplete(int token, Object cookie, Cursor cursor) { switch (token) { case FOLDER_NOTE_LIST_QUERY_TOKEN: - mNotesListAdapter.changeCursor(cursor); + mNotesListAdapter.changeCursor(cursor); // 更新列表适配器数据 break; case FOLDER_LIST_QUERY_TOKEN: if (cursor != null && cursor.getCount() > 0) { - showFolderListMenu(cursor); + showFolderListMenu(cursor); // 显示文件夹选择菜单 } else { Log.e(TAG, "Query folder failed"); } @@ -441,6 +466,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } } + /** + * 显示文件夹选择菜单 + */ private void showFolderListMenu(Cursor cursor) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(R.string.menu_title_select_folder); @@ -448,6 +476,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { + // 批量移动便签到选择的文件夹 DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); Toast.makeText( @@ -462,6 +491,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt builder.show(); } + /** + * 创建新便签 + */ private void createNewNote() { Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_INSERT_OR_EDIT); @@ -469,20 +501,22 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); } + /** + * 批量删除便签 + */ private void batchDelete() { new AsyncTask>() { protected HashSet doInBackground(Void... unused) { HashSet widgets = mNotesListAdapter.getSelectedWidget(); if (!isSyncMode()) { - // if not synced, delete notes directly + // 非同步模式下直接删除 if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter .getSelectedItemIds())) { } else { Log.e(TAG, "Delete notes error, should not happens"); } } else { - // in sync mode, we'll move the deleted note into the trash - // folder + // 同步模式下移动到废纸篓 if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) { Log.e(TAG, "Move notes to trash folder error, should not happens"); @@ -497,7 +531,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt for (AppWidgetAttribute widget : widgets) { if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { - updateWidget(widget.widgetId, widget.widgetType); + updateWidget(widget.widgetId, widget.widgetType); // 更新相关Widget } } } @@ -506,6 +540,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt }.execute(); } + /** + * 删除文件夹 + */ private void deleteFolder(long folderId) { if (folderId == Notes.ID_ROOT_FOLDER) { Log.e(TAG, "Wrong folder id, should not happen " + folderId); @@ -517,22 +554,25 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt HashSet widgets = DataUtils.getFolderNoteWidget(mContentResolver, folderId); if (!isSyncMode()) { - // if not synced, delete folder directly + // 非同步模式下直接删除 DataUtils.batchDeleteNotes(mContentResolver, ids); } else { - // in sync mode, we'll move the deleted folder into the trash folder + // 同步模式下移动到废纸篓 DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER); } if (widgets != null) { for (AppWidgetAttribute widget : widgets) { if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { - updateWidget(widget.widgetId, widget.widgetType); + updateWidget(widget.widgetId, widget.widgetType); // 更新相关Widget } } } } + /** + * 打开便签 + */ private void openNode(NoteItemData data) { Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_VIEW); @@ -540,15 +580,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); } + /** + * 打开文件夹 + */ private void openFolder(NoteItemData data) { mCurrentFolderId = data.getId(); - startAsyncNotesListQuery(); + startAsyncNotesListQuery(); // 刷新列表显示文件夹内容 if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { mState = ListEditState.CALL_RECORD_FOLDER; mAddNewNote.setVisibility(View.GONE); } else { mState = ListEditState.SUB_FOLDER; } + // 更新标题栏显示 if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { mTitleBar.setText(R.string.call_record_folder_name); } else { @@ -557,13 +601,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt mTitleBar.setVisibility(View.VISIBLE); } + /** + * 视图点击事件处理 + */ public void onClick(View v) { int viewId = v.getId(); if (viewId == R.id.btn_new_note) { - createNewNote(); + createNewNote(); // 创建新便签 } } + /** + * 显示软键盘 + */ private void showSoftInput() { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null) { @@ -571,11 +621,17 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } } + /** + * 隐藏软键盘 + */ private void hideSoftInput(View view) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } + /** + * 显示创建或修改文件夹对话框 + */ private void showCreateOrModifyFolderDialog(final boolean create) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); @@ -607,6 +663,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt public void onClick(View v) { hideSoftInput(etName); String name = etName.getText().toString(); + // 检查文件夹名称是否已存在 if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), Toast.LENGTH_LONG).show(); @@ -615,16 +672,18 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } if (!create) { if (!TextUtils.isEmpty(name)) { + // 修改文件夹名称 ContentValues values = new ContentValues(); values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); values.put(NoteColumns.LOCAL_MODIFIED, 1); mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + "=?", new String[] { - String.valueOf(mFocusNoteDataItem.getId()) + String.valueOf(mFocusNoteDataItem.getId()) }); } } else if (!TextUtils.isEmpty(name)) { + // 创建新文件夹 ContentValues values = new ContentValues(); values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); @@ -634,17 +693,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } }); + // 根据输入内容启用/禁用确定按钮 if (TextUtils.isEmpty(etName.getText())) { positive.setEnabled(false); } - /** - * When the name edit text is null, disable the positive button - */ etName.addTextChangedListener(new TextWatcher() { - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - // TODO Auto-generated method stub - - } + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void onTextChanged(CharSequence s, int start, int before, int count) { if (TextUtils.isEmpty(etName.getText())) { @@ -654,15 +708,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } } - public void afterTextChanged(Editable s) { - // TODO Auto-generated method stub - - } + public void afterTextChanged(Editable s) {} }); } @Override public void onBackPressed() { + // 处理返回按钮,根据当前状态导航到上级文件夹 switch (mState) { case SUB_FOLDER: mCurrentFolderId = Notes.ID_ROOT_FOLDER; @@ -685,8 +737,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } } + /** + * 更新便签小部件 + */ private void updateWidget(int appWidgetId, int appWidgetType) { Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + // 根据小部件类型设置目标类 if (appWidgetType == Notes.TYPE_WIDGET_2X) { intent.setClass(this, NoteWidgetProvider_2x.class); } else if (appWidgetType == Notes.TYPE_WIDGET_4X) { @@ -697,13 +753,16 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { - appWidgetId + appWidgetId }); sendBroadcast(intent); setResult(RESULT_OK, intent); } + /** + * 文件夹上下文菜单创建监听器 + */ private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (mFocusNoteDataItem != null) { @@ -731,9 +790,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } switch (item.getItemId()) { case MENU_FOLDER_VIEW: - openFolder(mFocusNoteDataItem); + openFolder(mFocusNoteDataItem); // 打开文件夹 break; case MENU_FOLDER_DELETE: + // 显示删除文件夹确认对话框 AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.alert_title_delete)); builder.setIcon(android.R.drawable.ic_dialog_alert); @@ -741,14 +801,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { - deleteFolder(mFocusNoteDataItem.getId()); + deleteFolder(mFocusNoteDataItem.getId()); // 删除文件夹 } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); break; case MENU_FOLDER_CHANGE_NAME: - showCreateOrModifyFolderDialog(false); + showCreateOrModifyFolderDialog(false); // 显示重命名对话框 break; default: break; @@ -760,10 +820,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); + // 根据当前状态加载不同的菜单资源 if (mState == ListEditState.NOTE_LIST) { getMenuInflater().inflate(R.menu.note_list, menu); - // set sync or sync_cancel - // Temporarily disabled sync functionality + // 设置同步菜单项 menu.findItem(R.id.menu_sync).setTitle(R.string.menu_sync); } else if (mState == ListEditState.SUB_FOLDER) { getMenuInflater().inflate(R.menu.sub_folder, menu); @@ -779,19 +839,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_new_folder) { - showCreateOrModifyFolderDialog(true); + showCreateOrModifyFolderDialog(true); // 显示创建文件夹对话框 } else if (itemId == R.id.menu_export_text) { - exportNoteToText(); + exportNoteToText(); // 导出便签数据到文本 } else if (itemId == R.id.menu_sync) { - // Temporarily disabled sync functionality + // 同步功能暂时禁用 Toast.makeText(this, "Sync functionality temporarily disabled", Toast.LENGTH_SHORT).show(); startPreferenceActivity(); } else if (itemId == R.id.menu_setting) { - startPreferenceActivity(); + startPreferenceActivity(); // 启动设置活动 } else if (itemId == R.id.menu_new_note) { - createNewNote(); + createNewNote(); // 创建新便签 } else if (itemId == R.id.menu_search) { - onSearchRequested(); + onSearchRequested(); // 启动搜索 } return true; } @@ -802,17 +862,21 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt return true; } + /** + * 导出便签数据到文本文件 + */ private void exportNoteToText() { final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); new AsyncTask() { @Override protected Integer doInBackground(Void... unused) { - return backup.exportToText(); + return backup.exportToText(); // 执行导出操作 } @Override protected void onPostExecute(Integer result) { + // 处理导出结果 if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(NotesListActivity.this @@ -845,7 +909,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } private boolean isSyncMode() { - // Temporarily disabled sync functionality + // 同步功能暂时禁用 return false; // return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; } @@ -856,12 +920,16 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt from.startActivityIfNeeded(intent, -1); } + /** + * 列表项点击监听器 + */ private class OnListItemClickListener implements OnItemClickListener { public void onItemClick(AdapterView parent, View view, int position, long id) { if (view instanceof NotesListItem) { NoteItemData item = ((NotesListItem) view).getItemData(); if (mNotesListAdapter.isInChoiceMode()) { + // 多选模式下处理选中状态 if (item.getType() == Notes.TYPE_NOTE) { position = position - mNotesListView.getHeaderViewsCount(); mModeCallBack.onItemCheckedStateChanged(null, position, id, @@ -870,13 +938,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt return; } + // 根据当前状态处理点击事件 switch (mState) { case NOTE_LIST: if (item.getType() == Notes.TYPE_FOLDER || item.getType() == Notes.TYPE_SYSTEM) { - openFolder(item); + openFolder(item); // 打开文件夹 } else if (item.getType() == Notes.TYPE_NOTE) { - openNode(item); + openNode(item); // 打开便签 } else { Log.e(TAG, "Wrong note type in NOTE_LIST"); } @@ -884,7 +953,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt case SUB_FOLDER: case CALL_RECORD_FOLDER: if (item.getType() == Notes.TYPE_NOTE) { - openNode(item); + openNode(item); // 打开便签 } else { Log.e(TAG, "Wrong note type in SUB_FOLDER"); } @@ -897,10 +966,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } + /** + * 启动查询目标文件夹 + */ private void startQueryDestinationFolders() { String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; + // 根据当前状态调整查询条件 selection = (mState == ListEditState.NOTE_LIST) ? selection: - "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; + "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, null, @@ -915,10 +988,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt NoteColumns.MODIFIED_DATE + " DESC"); } + /** + * 列表项长按事件处理 + */ public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { if (view instanceof NotesListItem) { mFocusNoteDataItem = ((NotesListItem) view).getItemData(); if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) { + // 启动多选操作模式 if (mNotesListView.startActionMode(mModeCallBack) != null) { mModeCallBack.onItemCheckedStateChanged(null, position, id, true); mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); @@ -926,9 +1003,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt Log.e(TAG, "startActionMode fails"); } } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { + // 显示文件夹上下文菜单 mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); } } return false; } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/ui/NotesListAdapter.java b/java/net/micode/notes/ui/NotesListAdapter.java index 51c9cb9..971a311 100644 --- a/java/net/micode/notes/ui/NotesListAdapter.java +++ b/java/net/micode/notes/ui/NotesListAdapter.java @@ -30,19 +30,31 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; - +/** + * 便签列表适配器 + * 负责将数据库中的便签数据绑定到ListView上 + * 支持多选模式和便签小部件属性管理 + */ public class NotesListAdapter extends CursorAdapter { private static final String TAG = "NotesListAdapter"; - private Context mContext; - private HashMap mSelectedIndex; - private int mNotesCount; - private boolean mChoiceMode; + private Context mContext; // 上下文环境 + private HashMap mSelectedIndex; // 记录选中项的位置和状态 + private int mNotesCount; // 便签数量统计 + private boolean mChoiceMode; // 多选模式标志 + /** + * 便签小部件属性类 + * 存储便签关联的小部件ID和类型 + */ public static class AppWidgetAttribute { - public int widgetId; - public int widgetType; + public int widgetId; // 小部件ID + public int widgetType; // 小部件类型 }; + /** + * 构造函数 + * 初始化适配器并设置上下文环境 + */ public NotesListAdapter(Context context) { super(context, null); mSelectedIndex = new HashMap(); @@ -50,38 +62,64 @@ public class NotesListAdapter extends CursorAdapter { mNotesCount = 0; } + /** + * 创建新的列表项视图 + * 每次需要创建新的列表项视图时调用 + */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return new NotesListItem(context); } + /** + * 将数据绑定到视图 + * 将游标中的数据绑定到已有的列表项视图上 + */ @Override public void bindView(View view, Context context, Cursor cursor) { if (view instanceof NotesListItem) { + // 创建便签项数据对象并绑定到视图 NoteItemData itemData = new NoteItemData(context, cursor); ((NotesListItem) view).bind(context, itemData, mChoiceMode, isSelectedItem(cursor.getPosition())); } } + /** + * 设置选中项状态 + * 根据位置设置便签项的选中状态 + */ public void setCheckedItem(final int position, final boolean checked) { mSelectedIndex.put(position, checked); - notifyDataSetChanged(); + notifyDataSetChanged(); // 通知适配器数据已更改,触发视图刷新 } + /** + * 检查是否处于多选模式 + * 返回当前适配器是否处于多选模式 + */ public boolean isInChoiceMode() { return mChoiceMode; } + /** + * 设置多选模式 + * 切换适配器的多选模式,并清空选中状态 + */ public void setChoiceMode(boolean mode) { mSelectedIndex.clear(); mChoiceMode = mode; } + /** + * 全选或取消全选 + * 根据参数设置所有便签项的选中状态 + */ public void selectAll(boolean checked) { Cursor cursor = getCursor(); for (int i = 0; i < getCount(); i++) { if (cursor.moveToPosition(i)) { + // 只处理便签类型的项,不包括文件夹等其他类型 if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { setCheckedItem(i, checked); } @@ -89,6 +127,10 @@ public class NotesListAdapter extends CursorAdapter { } } + /** + * 获取选中项ID集合 + * 返回所有选中便签项的ID集合 + */ public HashSet getSelectedItemIds() { HashSet itemSet = new HashSet(); for (Integer position : mSelectedIndex.keySet()) { @@ -105,19 +147,24 @@ public class NotesListAdapter extends CursorAdapter { return itemSet; } + /** + * 获取选中项关联的小部件属性集合 + * 返回所有选中便签项关联的小部件属性集合 + */ public HashSet getSelectedWidget() { HashSet itemSet = new HashSet(); for (Integer position : mSelectedIndex.keySet()) { if (mSelectedIndex.get(position) == true) { Cursor c = (Cursor) getItem(position); if (c != null) { + // 创建小部件属性对象并添加到集合 AppWidgetAttribute widget = new AppWidgetAttribute(); NoteItemData item = new NoteItemData(mContext, c); widget.widgetId = item.getWidgetId(); widget.widgetType = item.getWidgetType(); itemSet.add(widget); /** - * Don't close cursor here, only the adapter could close it + * 注意:不要在这里关闭游标,只有适配器可以关闭它 */ } else { Log.e(TAG, "Invalid cursor"); @@ -128,6 +175,10 @@ public class NotesListAdapter extends CursorAdapter { return itemSet; } + /** + * 获取选中项数量 + * 统计当前选中的便签项数量 + */ public int getSelectedCount() { Collection values = mSelectedIndex.values(); if (null == values) { @@ -143,11 +194,19 @@ public class NotesListAdapter extends CursorAdapter { return count; } + /** + * 检查是否全部选中 + * 判断是否所有便签项都被选中 + */ public boolean isAllSelected() { int checkedCount = getSelectedCount(); return (checkedCount != 0 && checkedCount == mNotesCount); } + /** + * 检查指定位置的项是否被选中 + * 判断特定位置的便签项是否处于选中状态 + */ public boolean isSelectedItem(final int position) { if (null == mSelectedIndex.get(position)) { return false; @@ -155,23 +214,36 @@ public class NotesListAdapter extends CursorAdapter { return mSelectedIndex.get(position); } + /** + * 内容变化时的回调 + * 当数据源内容发生变化时调用,重新计算便签数量 + */ @Override protected void onContentChanged() { super.onContentChanged(); calcNotesCount(); } + /** + * 更改游标 + * 替换当前游标并重新计算便签数量 + */ @Override public void changeCursor(Cursor cursor) { super.changeCursor(cursor); calcNotesCount(); } + /** + * 计算便签数量 + * 统计数据集中便签类型项的总数 + */ private void calcNotesCount() { mNotesCount = 0; for (int i = 0; i < getCount(); i++) { Cursor c = (Cursor) getItem(i); if (c != null) { + // 只统计便签类型的项 if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { mNotesCount++; } @@ -181,4 +253,4 @@ public class NotesListAdapter extends CursorAdapter { } } } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/ui/NotesListItem.java b/java/net/micode/notes/ui/NotesListItem.java index 1221e80..542bd04 100644 --- a/java/net/micode/notes/ui/NotesListItem.java +++ b/java/net/micode/notes/ui/NotesListItem.java @@ -29,18 +29,32 @@ import net.micode.notes.data.Notes; import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.ResourceParser.NoteItemBgResources; - +/** + * 便签列表项视图 + * 自定义LinearLayout,用于展示便签列表中的单个项目 + * 支持不同类型便签(普通便签、文件夹、通话记录)的差异化显示 + * 实现多选模式下的选择框显示与交互 + * 根据便签在列表中的位置设置不同背景样式 + */ public class NotesListItem extends LinearLayout { - private ImageView mAlert; - private TextView mTitle; - private TextView mTime; - private TextView mCallName; - private NoteItemData mItemData; - private CheckBox mCheckBox; + // 视图组件引用 + private ImageView mAlert; // 提醒图标 + private TextView mTitle; // 便签标题/内容摘要 + private TextView mTime; // 最后修改时间 + private TextView mCallName; // 联系人名称(通话记录便签) + private NoteItemData mItemData; // 便签数据模型 + private CheckBox mCheckBox; // 多选模式选择框 + /** + * 构造函数 + * 初始化视图组件并加载布局 + * @param context 应用上下文 + */ public NotesListItem(Context context) { super(context); + // 加载便签列表项布局 inflate(context, R.layout.note_item, this); + // 获取视图组件引用 mAlert = (ImageView) findViewById(R.id.iv_alert_icon); mTitle = (TextView) findViewById(R.id.tv_title); mTime = (TextView) findViewById(R.id.tv_time); @@ -48,7 +62,16 @@ public class NotesListItem extends LinearLayout { mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); } + /** + * 绑定数据到视图 + * 根据便签类型和状态更新视图显示 + * @param context 应用上下文 + * @param data 便签数据模型 + * @param choiceMode 是否为多选模式 + * @param checked 选中状态(多选模式下) + */ public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { + // 处理多选模式下的选择框显示 if (choiceMode && data.getType() == Notes.TYPE_NOTE) { mCheckBox.setVisibility(View.VISIBLE); mCheckBox.setChecked(checked); @@ -57,6 +80,7 @@ public class NotesListItem extends LinearLayout { } mItemData = data; + // 处理通话记录文件夹的显示 if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { mCallName.setVisibility(View.GONE); mAlert.setVisibility(View.VISIBLE); @@ -64,28 +88,36 @@ public class NotesListItem extends LinearLayout { mTitle.setText(context.getString(R.string.call_record_folder_name) + context.getString(R.string.format_folder_files_count, data.getNotesCount())); mAlert.setImageResource(R.drawable.call_record); - } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { + } + // 处理通话记录便签的显示 + else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { mCallName.setVisibility(View.VISIBLE); mCallName.setText(data.getCallName()); - mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); + mTitle.setTextAppearance(context, R.style.TextAppearanceSecondaryItem); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); + // 显示提醒图标(如果有提醒) if (data.hasAlert()) { mAlert.setImageResource(R.drawable.clock); mAlert.setVisibility(View.VISIBLE); } else { mAlert.setVisibility(View.GONE); } - } else { + } + // 处理普通便签和文件夹的显示 + else { mCallName.setVisibility(View.GONE); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); if (data.getType() == Notes.TYPE_FOLDER) { + // 文件夹显示(包含子项数量) mTitle.setText(data.getSnippet() + context.getString(R.string.format_folder_files_count, - data.getNotesCount())); + data.getNotesCount())); mAlert.setVisibility(View.GONE); } else { + // 普通便签显示 mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); + // 显示提醒图标(如果有提醒) if (data.hasAlert()) { mAlert.setImageResource(R.drawable.clock); mAlert.setVisibility(View.VISIBLE); @@ -94,29 +126,46 @@ public class NotesListItem extends LinearLayout { } } } + // 显示相对时间(如"5分钟前") mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); + // 设置便签项背景 setBackground(data); } + /** + * 设置便签项背景 + * 根据便签类型和在列表中的位置设置不同背景 + * @param data 便签数据模型 + */ private void setBackground(NoteItemData data) { int id = data.getBgColorId(); if (data.getType() == Notes.TYPE_NOTE) { + // 普通便签背景设置 if (data.isSingle() || data.isOneFollowingFolder()) { + // 单独一项或文件夹后的单个便签 setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); } else if (data.isLast()) { + // 列表最后一项 setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); } else if (data.isFirst() || data.isMultiFollowingFolder()) { + // 列表第一项或文件夹后的多个便签之一 setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); } else { + // 列表中间项 setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); } } else { + // 文件夹背景设置 setBackgroundResource(NoteItemBgResources.getFolderBgRes()); } } + /** + * 获取便签数据模型 + * @return 便签数据模型对象 + */ public NoteItemData getItemData() { return mItemData; } -} +} \ No newline at end of file diff --git a/java/net/micode/notes/widget/NoteWidgetProvider.java b/java/net/micode/notes/widget/NoteWidgetProvider.java index ec6f819..561dd56 100644 --- a/java/net/micode/notes/widget/NoteWidgetProvider.java +++ b/java/net/micode/notes/widget/NoteWidgetProvider.java @@ -15,6 +15,7 @@ */ package net.micode.notes.widget; + import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; @@ -32,23 +33,39 @@ import net.micode.notes.tool.ResourceParser; import net.micode.notes.ui.NoteEditActivity; import net.micode.notes.ui.NotesListActivity; +/** + * 便签桌面小部件基类 + * 实现便签小部件的基础功能,包括: + * - 小部件删除时的资源释放 + * - 小部件内容更新逻辑 + * - 便签数据与小部件的绑定关系管理 + * 子类需实现特定尺寸小部件的布局和资源获取逻辑 + */ public abstract class NoteWidgetProvider extends AppWidgetProvider { - public static final String [] PROJECTION = new String [] { - NoteColumns.ID, - NoteColumns.BG_COLOR_ID, - NoteColumns.SNIPPET + // 数据库查询字段投影(仅获取必要字段提升性能) + public static final String[] PROJECTION = new String[]{ + NoteColumns.ID, // 便签ID + NoteColumns.BG_COLOR_ID, // 便签背景颜色ID + NoteColumns.SNIPPET // 便签摘要 }; - public static final int COLUMN_ID = 0; - public static final int COLUMN_BG_COLOR_ID = 1; - public static final int COLUMN_SNIPPET = 2; + // 投影字段索引(提升查询效率) + public static final int COLUMN_ID = 0; + public static final int COLUMN_BG_COLOR_ID = 1; + public static final int COLUMN_SNIPPET = 2; private static final String TAG = "NoteWidgetProvider"; + /** + * 处理小部件删除事件 + * 当用户删除小部件时,清除数据库中关联的Widget ID + * @param context 应用上下文 + * @param appWidgetIds 被删除的小部件ID数组 + */ @Override public void onDeleted(Context context, int[] appWidgetIds) { ContentValues values = new ContentValues(); - values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // 设置为无效ID for (int i = 0; i < appWidgetIds.length; i++) { context.getContentResolver().update(Notes.CONTENT_NOTE_URI, values, @@ -57,6 +74,12 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider { } } + /** + * 获取与小部件关联的便签信息 + * @param context 应用上下文 + * @param widgetId 小部件ID + * @return 包含便签ID、背景色ID和摘要的Cursor + */ private Cursor getNoteWidgetInfo(Context context, int widgetId) { return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, PROJECTION, @@ -65,21 +88,35 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider { null); } + /** + * 更新小部件显示内容(公共接口) + * @param context 应用上下文 + * @param appWidgetManager AppWidgetManager实例 + * @param appWidgetIds 待更新的小部件ID数组 + */ protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { update(context, appWidgetManager, appWidgetIds, false); } + /** + * 更新小部件显示内容(私有实现) + * @param context 应用上下文 + * @param appWidgetManager AppWidgetManager实例 + * @param appWidgetIds 待更新的小部件ID数组 + * @param privacyMode 是否隐私模式(显示保护信息) + */ private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, - boolean privacyMode) { + boolean privacyMode) { for (int i = 0; i < appWidgetIds.length; i++) { if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { - int bgId = ResourceParser.getDefaultBgId(context); - String snippet = ""; + int bgId = ResourceParser.getDefaultBgId(context); // 默认背景色 + String snippet = ""; // 便签摘要 Intent intent = new Intent(context, NoteEditActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); + // 从数据库获取关联的便签信息 Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]); if (c != null && c.moveToFirst()) { if (c.getCount() > 1) { @@ -90,29 +127,29 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider { snippet = c.getString(COLUMN_SNIPPET); bgId = c.getInt(COLUMN_BG_COLOR_ID); intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); - intent.setAction(Intent.ACTION_VIEW); + intent.setAction(Intent.ACTION_VIEW); // 设置为查看动作 } else { snippet = context.getResources().getString(R.string.widget_havenot_content); - intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 设置为新建/编辑动作 } if (c != null) { c.close(); } + // 构建RemoteViews并设置内容 RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); - /** - * Generate the pending intent to start host for the widget - */ - PendingIntent pendingIntent = null; + + PendingIntent pendingIntent; if (privacyMode) { - rv.setTextViewText(R.id.widget_text, - context.getString(R.string.widget_under_visit_mode)); + // 隐私模式下显示保护信息 + rv.setTextViewText(R.id.widget_text, context.getString(R.string.widget_under_visit_mode)); pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent( context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); } else { + // 正常模式下显示便签摘要 rv.setTextViewText(R.id.widget_text, snippet); pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, PendingIntent.FLAG_UPDATE_CURRENT); @@ -124,9 +161,25 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider { } } + /** + * 获取小部件背景资源ID(抽象方法) + * 由子类实现不同尺寸小部件的背景资源获取逻辑 + * @param bgId 背景颜色逻辑ID + * @return 对应的背景资源ID + */ protected abstract int getBgResourceId(int bgId); + /** + * 获取小部件布局资源ID(抽象方法) + * 由子类实现不同尺寸小部件的布局资源获取逻辑 + * @return 布局资源ID + */ protected abstract int getLayoutId(); + /** + * 获取小部件类型(抽象方法) + * 由子类实现不同类型小部件的类型标识 + * @return 小部件类型 + */ protected abstract int getWidgetType(); -} +} \ No newline at end of file diff --git a/java/net/micode/notes/widget/NoteWidgetProvider_2x.java b/java/net/micode/notes/widget/NoteWidgetProvider_2x.java index adcb2f7..1f39126 100644 --- a/java/net/micode/notes/widget/NoteWidgetProvider_2x.java +++ b/java/net/micode/notes/widget/NoteWidgetProvider_2x.java @@ -14,6 +14,11 @@ * limitations under the License. */ +/** + * 便签小部件实现类:2x尺寸版本 + * 继承自NoteWidgetProvider基类,用于在桌面显示2x2网格大小的便签小部件 + * 支持自定义背景、文本样式和便签内容展示 + */ package net.micode.notes.widget; import android.appwidget.AppWidgetManager; @@ -25,21 +30,36 @@ import net.micode.notes.tool.ResourceParser; public class NoteWidgetProvider_2x extends NoteWidgetProvider { + /** + * 小部件更新回调:当小部件被添加到桌面或需要更新时调用 + * 调用父类的update方法处理实际更新逻辑 + */ @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.update(context, appWidgetManager, appWidgetIds); } + /** + * 获取布局资源ID:返回2x尺寸小部件对应的布局文件 + */ @Override protected int getLayoutId() { return R.layout.widget_2x; } + /** + * 获取背景资源ID:根据背景样式ID返回对应的背景资源 + * @param bgId 背景样式ID,由ResourceParser定义 + */ @Override protected int getBgResourceId(int bgId) { return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); } + /** + * 获取小部件类型:返回当前小部件的类型标识 + * 用于数据库存储和区分不同尺寸的便签小部件 + */ @Override protected int getWidgetType() { return Notes.TYPE_WIDGET_2X; diff --git a/java/net/micode/notes/widget/NoteWidgetProvider_4x.java b/java/net/micode/notes/widget/NoteWidgetProvider_4x.java index c12a02e..27dc62c 100644 --- a/java/net/micode/notes/widget/NoteWidgetProvider_4x.java +++ b/java/net/micode/notes/widget/NoteWidgetProvider_4x.java @@ -23,24 +23,53 @@ import net.micode.notes.R; import net.micode.notes.data.Notes; import net.micode.notes.tool.ResourceParser; - +/** + * 4x4尺寸便签桌面小部件实现类 + * 继承自NoteWidgetProvider基类,实现4x4尺寸小部件的特定逻辑 + * 负责: + * 1. 提供4x4小部件的布局资源 + * 2. 提供4x4小部件的背景资源 + * 3. 定义4x4小部件的类型标识 + */ public class NoteWidgetProvider_4x extends NoteWidgetProvider { + /** + * 小部件更新处理 + * 调用基类的更新逻辑 + * @param context 应用上下文 + * @param appWidgetManager AppWidgetManager实例 + * @param appWidgetIds 待更新的小部件ID数组 + */ @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.update(context, appWidgetManager, appWidgetIds); } + /** + * 获取4x4小部件的布局资源ID + * @return 布局资源ID(R.layout.widget_4x) + */ + @Override protected int getLayoutId() { return R.layout.widget_4x; } + /** + * 获取4x4小部件的背景资源ID + * 调用ResourceParser获取4x4尺寸的背景资源 + * @param bgId 背景颜色逻辑ID + * @return 对应的4x4小部件背景资源ID + */ @Override protected int getBgResourceId(int bgId) { return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); } + /** + * 获取4x4小部件的类型标识 + * @return 小部件类型标识(Notes.TYPE_WIDGET_4X) + */ @Override protected int getWidgetType() { return Notes.TYPE_WIDGET_4X; } -} +} \ No newline at end of file