diff --git a/README.md b/README.md
deleted file mode 100644
index 40626f4..0000000
--- a/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-# git-test
-
diff --git a/doc/6.txt b/doc/6.txt
deleted file mode 100644
index 3cacc0b..0000000
--- a/doc/6.txt
+++ /dev/null
@@ -1 +0,0 @@
-12
\ No newline at end of file
diff --git a/doc/小米便签泛读、标注和维护报告文档 .docx b/doc/小米便签泛读、标注和维护报告文档 .docx
new file mode 100644
index 0000000..ccfc012
Binary files /dev/null and b/doc/小米便签泛读、标注和维护报告文档 .docx differ
diff --git a/doc/小米便签的质量分析报告文档.docx b/doc/小米便签的质量分析报告文档.docx
new file mode 100644
index 0000000..38d5263
Binary files /dev/null and b/doc/小米便签的质量分析报告文档.docx differ
diff --git a/src/androidTest/java/net/micode/notes/ExampleInstrumentedTest.java b/src/androidTest/java/net/micode/notes/ExampleInstrumentedTest.java
new file mode 100644
index 0000000..a889a75
--- /dev/null
+++ b/src/androidTest/java/net/micode/notes/ExampleInstrumentedTest.java
@@ -0,0 +1,26 @@
+package net.micode.notes;
+
+import android.content.Context;
+
+import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.*;
+
+/**
+ * Instrumented test, which will execute on an Android device.
+ *
+ * @see Testing documentation
+ */
+@RunWith(AndroidJUnit4.class)
+public class ExampleInstrumentedTest {
+ @Test
+ public void useAppContext() {
+ // Context of the app under test.
+ Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+ assertEquals("net.micode.notes", appContext.getPackageName());
+ }
+}
\ No newline at end of file
diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..243ffcc
--- /dev/null
+++ b/src/main/AndroidManifest.xml
@@ -0,0 +1,164 @@
+
+
+ * 该类提供了获取联系人信息的静态方法,并使用缓存机制提高查询效率 + *
+ */ +public class Contact { + /** + * 联系人缓存,用于存储已查询过的电话号码和对应联系人姓名 + */ + private static HashMap+ * 该方法会先检查缓存,如果缓存中存在则直接返回,否则查询联系人数据库 + *
+ * @param context 上下文对象 + * @param phoneNumber 电话号码 + * @return 联系人姓名,若未找到则返回null + */ + public static String getContact(Context context, String phoneNumber) { + if(sContactCache == null) { + sContactCache = new HashMap+ * 该类包含了便签应用的核心数据定义,包括便签类型、系统文件夹ID、意图额外参数、 + * 组件类型、以及各种URI定义。同时还定义了便签表和数据表的列名,以及文本便签和 + * 通话便签的具体数据结构。 + *
+ */ +public class Notes { + /** + * 内容提供者的授权名称,用于构建内容URI + */ + public static final String AUTHORITY = "micode_notes"; + /** + * 日志标签,用于日志输出 + */ + public static final String TAG = "Notes"; + /** + * 便签类型:普通便签 + */ + public static final int TYPE_NOTE = 0; + /** + * 便签类型:文件夹 + */ + public static final int TYPE_FOLDER = 1; + /** + * 便签类型:系统便签 + */ + public static final int TYPE_SYSTEM = 2; + + /** + * 以下是系统文件夹的标识符 + * {@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; + /** + * 回收站文件夹ID,用于存储被删除的便签和文件夹 + */ + public static final int ID_TRASH_FOLER = -3; + + /** + * 意图额外参数:提醒日期 + */ + public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; + /** + * 意图额外参数:背景颜色ID + */ + 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"; + /** + * 意图额外参数:组件类型 + */ + public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; + /** + * 意图额外参数:文件夹ID + */ + 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; + /** + * 组件类型:2x2大小的便签组件 + */ + public static final int TYPE_WIDGET_2X = 0; + /** + * 组件类型:4x4大小的便签组件 + */ + public static final int TYPE_WIDGET_4X = 1; + + /** + * 锁类型:便签锁 + */ + public static final int LOCK_TYPE_NOTE = 0; + + /** + * 锁类型:文件夹锁 + */ + public static final int LOCK_TYPE_FOLDER = 1; + + /** + * 数据类型常量类,定义了不同类型便签的数据项类型 + */ + public static class DataConstants { + /** + * 文本便签的数据项类型 + */ + public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; + /** + * 通话便签的数据项类型 + */ + public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; + } + + /** + * 用于查询所有便签和文件夹的Uri + */ + public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); + + /** + * 用于查询数据的Uri + */ + public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); + + public interface NoteColumns { + /** + * 行的唯一ID + *类型: INTEGER (long)
+ */ + public static final String ID = "_id"; + + /** + * 便签或文件夹的父ID + *类型: INTEGER (long)
+ */ + public static final String PARENT_ID = "parent_id"; + + /** + * 便签或文件夹的创建日期 + *类型: INTEGER (long)
+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * 最近修改日期 + *类型: INTEGER (long)
+ */ + public static final String MODIFIED_DATE = "modified_date"; + + + /** + * 提醒日期 + *类型: INTEGER (long)
+ */ + public static final String ALERTED_DATE = "alert_date"; + + /** + * 文件夹名称或便签的文本内容 + *类型: TEXT
+ */ + public static final String SNIPPET = "snippet"; + + /** + * 便签的组件ID + *类型: INTEGER (long)
+ */ + public static final String WIDGET_ID = "widget_id"; + + /** + * 便签的组件类型 + *类型: INTEGER (long)
+ */ + public static final String WIDGET_TYPE = "widget_type"; + + /** + * 便签的背景颜色ID + *类型: INTEGER (long)
+ */ + public static final String BG_COLOR_ID = "bg_color_id"; + + /** + * 对于文本便签,没有附件;对于多媒体便签,至少有一个附件 + *类型: INTEGER
+ */ + public static final String HAS_ATTACHMENT = "has_attachment"; + + /** + * 文件夹中的便签数量 + *类型: INTEGER (long)
+ */ + public static final String NOTES_COUNT = "notes_count"; + + /** + * 文件类型:文件夹或便签 + *类型: INTEGER
+ */ + public static final String TYPE = "type"; + + /** + * 最后同步ID + *类型: INTEGER (long)
+ */ + public static final String SYNC_ID = "sync_id"; + + /** + * 表示本地是否修改的标志 + *类型: INTEGER
+ */ + public static final String LOCAL_MODIFIED = "local_modified"; + + /** + * 原始父ID + *类型: INTEGER (long)
+ */ + public static final String ORIGIN_PARENT_ID = "origin_parent_id"; + + /** + * GTASK ID + *类型: TEXT
+ */ + public static final String GTASK_ID = "gtask_id"; + + /** + * 版本号 + *类型: INTEGER
+ */ + public static final String VERSION = "version"; + + /** + * 置顶状态 + *类型: INTEGER
+ *0表示未置顶,1表示置顶
+ */ + public static final String PINNED = "pinned"; + + /** + * 是否上锁 + *类型: INTEGER
+ *0表示未上锁,1表示上锁
+ */ + public static final String IS_LOCKED = "is_locked"; + + /** + * 加密后的密码 + *类型: TEXT
+ */ + public static final String LOCK_PASSWORD = "lock_password"; + + /** + * 锁类型 + *类型: INTEGER
+ *0表示便签锁,1表示文件夹锁
+ */ + public static final String LOCK_TYPE = "lock_type"; + + /** + * 便签或文件夹被删除的时间 + *类型: INTEGER (long)
+ *0表示未被删除,其他值表示删除时间戳
+ */ + public static final String DELETED_DATE = "deleted_date"; + } + + public interface DataColumns { + /** + * 行的唯一ID + *类型: INTEGER (long)
+ */ + public static final String ID = "_id"; + + /** + * 该行表示的项目的MIME类型 + *类型: Text
+ */ + public static final String MIME_TYPE = "mime_type"; + + /** + * 该数据所属便签的引用ID + *类型: INTEGER (long)
+ */ + public static final String NOTE_ID = "note_id"; + + /** + * 便签或文件夹的创建日期 + *类型: INTEGER (long)
+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * 最近修改日期 + *类型: INTEGER (long)
+ */ + public static final String MODIFIED_DATE = "modified_date"; + + /** + * 数据内容 + *类型: TEXT
+ */ + public static final String CONTENT = "content"; + + + /** + * 通用数据列,含义由{@link # MIMETYPE}决定,用于整数数据类型 + *类型: INTEGER
+ */ + public static final String DATA1 = "data1"; + + /** + * 通用数据列,含义由{@link # MIMETYPE}决定,用于整数数据类型 + *类型: INTEGER
+ */ + public static final String DATA2 = "data2"; + + /** + * 通用数据列,含义由{@link # MIMETYPE}决定,用于文本数据类型 + *类型: TEXT
+ */ + public static final String DATA3 = "data3"; + + /** + * 通用数据列,含义由{@link # MIMETYPE}决定,用于文本数据类型 + *类型: TEXT
+ */ + public static final String DATA4 = "data4"; + + /** + * 通用数据列,含义由{@link # MIMETYPE}决定,用于文本数据类型 + *类型: TEXT
+ */ + public static final String DATA5 = "data5"; + } + + public static final class TextNote implements DataColumns { + /** + * 指示文本是否处于清单模式 + *类型: Integer 1:清单模式 0:普通模式
+ */ + public static final String MODE = DATA1; + + /** + * 清单模式 + */ + public static final int MODE_CHECK_LIST = 1; + + /** + * 文本便签的目录MIME类型 + */ + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; + + /** + * 文本便签的单项MIME类型 + */ + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; + + /** + * 文本便签的内容URI + */ + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); + } + + public static final class CallNote implements DataColumns { + /** + * 此记录的通话日期 + *类型: INTEGER (long)
+ */ + public static final String CALL_DATE = DATA1; + + /** + * 此记录的电话号码 + *类型: TEXT
+ */ + public static final String PHONE_NUMBER = DATA3; + + /** + * 通话便签的目录MIME类型 + */ + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; + + /** + * 通话便签的单项MIME类型 + */ + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; + + /** + * 通话便签的内容URI + */ + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); + } +} diff --git a/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java b/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java new file mode 100644 index 0000000..4edf21d --- /dev/null +++ b/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java @@ -0,0 +1,533 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.data; + +import android.content.ContentValues; +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; + + +/** + * 笔记数据库帮助类,负责数据库的创建、升级及触发器管理 + * 采用单例模式确保数据库连接的唯一性,封装了表结构定义、系统文件夹初始化等核心操作 + */ +public class NotesDatabaseHelper extends SQLiteOpenHelper { + // 数据库文件名 + private static final String DB_NAME = "note.db"; + // 数据库版本号,用于升级控制 + private static final int DB_VERSION = 7; + + /** + * 数据库表名常量定义 + */ + public interface TABLE { + // 笔记表,存储笔记和文件夹的元数据 + public static final String NOTE = "note"; + // 数据表,存储笔记的具体内容(如文本、通话记录等) + public static final String DATA = "data"; + } + + // 日志标签 + private static final String TAG = "NotesDatabaseHelper"; + // 单例实例 + private static NotesDatabaseHelper mInstance; + + /** + * 笔记表创建SQL语句 + * 包含笔记/文件夹的基本属性:ID、父文件夹ID、提醒时间、背景色、创建/修改时间等 + */ + private static final String CREATE_NOTE_TABLE_SQL = + "CREATE TABLE " + TABLE.NOTE + "(" + + NoteColumns.ID + " INTEGER PRIMARY KEY," + + 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," + + NoteColumns.PINNED + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.IS_LOCKED + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.LOCK_PASSWORD + " TEXT NOT NULL DEFAULT ''," + + NoteColumns.LOCK_TYPE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.DELETED_DATE + " INTEGER NOT NULL DEFAULT 0" + + ")"; + + /** + * 数据表创建SQL语句 + * 存储笔记的具体内容,支持多种类型(文本、通话记录等),通过MIME_TYPE区分 + */ + 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 ''" + + ")"; + + /** + * 为数据表的NOTE_ID字段创建索引 + * 优化根据笔记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 + ");"; + + /** + * 触发器:更新笔记父文件夹时,增加新父文件夹的笔记计数 + */ + 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"; + + /** + * 触发器:更新笔记父文件夹时,减少旧父文件夹的笔记计数 + */ + 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"; + + /** + * 触发器:插入新笔记时,增加其父文件夹的笔记计数 + */ + 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"; + + /** + * 触发器:删除笔记时,减少其父文件夹的笔记计数 + */ + 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"; + + /** + * 触发器:插入文本笔记数据时,更新对应笔记的摘要内容 + */ + 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"; + + /** + * 触发器:更新文本笔记数据时,同步更新对应笔记的摘要内容 + */ + 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"; + + /** + * 触发器:删除文本笔记数据时,清空对应笔记的摘要内容 + */ + 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"; + + /** + * 触发器:删除笔记时,级联删除其关联的数据记录 + */ + 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"; + + /** + * 触发器:删除文件夹时,级联删除其包含的所有笔记 + */ + 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"; + + /** + * 触发器:当文件夹被移到回收站时,其包含的所有笔记也自动移到回收站 + */ + 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"; + + /** + * 私有构造方法,防止外部实例化 + * @param context 上下文对象 + */ + public NotesDatabaseHelper(Context context) { + super(context, DB_NAME, null, DB_VERSION); + } + + /** + * 创建笔记表并初始化相关触发器和系统文件夹 + * @param db 数据库实例 + */ + public void createNoteTable(SQLiteDatabase db) { + db.execSQL(CREATE_NOTE_TABLE_SQL); + reCreateNoteTableTriggers(db); + createSystemFolder(db); + Log.d(TAG, "note table has been created"); + } + + /** + * 重新创建笔记表的所有触发器(先删除旧触发器再创建新的) + * @param db 数据库实例 + */ + private void reCreateNoteTableTriggers(SQLiteDatabase db) { + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); + db.execSQL("DROP TRIGGER IF EXISTS record_deleted_date_on_trash"); + db.execSQL("DROP TRIGGER IF EXISTS clear_deleted_date_on_restore"); + + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); + db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER); + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER); + db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER); + db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); + + // 创建记录删除时间触发器 + db.execSQL("CREATE TRIGGER record_deleted_date_on_trash " + + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " AND old." + NoteColumns.PARENT_ID + "!=" + Notes.ID_TRASH_FOLER + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.DELETED_DATE + "=strftime('%s','now') * 1000" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.ID + ";" + + " END"); + + // 创建清除删除时间触发器 + db.execSQL("CREATE TRIGGER clear_deleted_date_on_restore " + + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " WHEN new." + NoteColumns.PARENT_ID + "!=" + Notes.ID_TRASH_FOLER + + " AND old." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.DELETED_DATE + "=0" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.ID + ";" + + " END"); + } + + /** + * 初始化系统文件夹(通话记录文件夹、根目录、临时文件夹、回收站) + * @param db 数据库实例 + */ + private void createSystemFolder(SQLiteDatabase db) { + ContentValues values = new ContentValues(); + + // 通话记录文件夹:存储通话笔记 + values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + // 根目录:默认文件夹 + values.clear(); + values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + // 临时文件夹:用于移动笔记的中间存储 + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + // 回收站:存储被删除的笔记和文件夹 + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + /** + * 创建数据表并初始化相关触发器和索引 + * @param db 数据库实例 + */ + public void createDataTable(SQLiteDatabase db) { + db.execSQL(CREATE_DATA_TABLE_SQL); + reCreateDataTableTriggers(db); + db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); + Log.d(TAG, "data table has been created"); + } + + /** + * 重新创建数据表的所有触发器(先删除旧触发器再创建新的) + * @param db 数据库实例 + */ + private void reCreateDataTableTriggers(SQLiteDatabase db) { + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); + + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); + } + + /** + * 获取单例实例 + * @param context 上下文对象 + * @return 数据库帮助类实例 + */ + static synchronized NotesDatabaseHelper getInstance(Context context) { + if (mInstance == null) { + mInstance = new NotesDatabaseHelper(context); + } + return mInstance; + } + + /** + * 数据库首次创建时调用,初始化表结构 + * @param db 数据库实例 + */ + @Override + public void onCreate(SQLiteDatabase db) { + createNoteTable(db); + createDataTable(db); + } + + /** + * 数据库版本升级时调用 + * @param db 数据库实例 + * @param oldVersion 旧版本号 + * @param newVersion 新版本号 + */ + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + boolean reCreateTriggers = false; + boolean skipV2 = false; + + // 版本1升级到版本2 + if (oldVersion == 1) { + upgradeToV2(db); + skipV2 = true; // 此升级包含了从v2到v3的升级 + oldVersion++; + } + + // 版本2升级到版本3(跳过已包含在v1->v2中的情况) + if (oldVersion == 2 && !skipV2) { + upgradeToV3(db); + reCreateTriggers = true; + oldVersion++; + } + + // 版本3升级到版本4 + if (oldVersion == 3) { + upgradeToV4(db); + oldVersion++; + } + + // 版本4升级到版本5 + if (oldVersion == 4) { + upgradeToV5(db); + oldVersion++; + } + + // 版本5升级到版本6:添加锁相关字段 + if (oldVersion == 5) { + upgradeToV6(db); + oldVersion++; + } + + // 版本6升级到版本7:添加删除时间字段和相关触发器 + if (oldVersion == 6) { + upgradeToV7(db); + oldVersion++; + } + + // 如果需要,重新创建触发器 + if (reCreateTriggers) { + reCreateNoteTableTriggers(db); + reCreateDataTableTriggers(db); + } + + // 验证升级是否完成 + if (oldVersion != newVersion) { + throw new IllegalStateException("Upgrade notes database to version " + newVersion + + " fails"); + } + } + + /** + * 升级到版本2:删除旧表并重新创建(结构调整) + * @param db 数据库实例 + */ + private void upgradeToV2(SQLiteDatabase db) { + db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); + db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); + createNoteTable(db); + createDataTable(db); + } + + /** + * 升级到版本3:添加GTask ID字段和回收站文件夹 + * @param db 数据库实例 + */ + private void upgradeToV3(SQLiteDatabase db) { + // 删除未使用的触发器 + 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"); + // 添加GTask ID字段,用于同步 + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID + + " TEXT NOT NULL DEFAULT ''"); + // 添加回收站系统文件夹 + ContentValues values = new ContentValues(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + /** + * 升级到版本4:添加版本号字段,用于数据同步控制 + * @param db 数据库实例 + */ + private void upgradeToV4(SQLiteDatabase db) { + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION + + " INTEGER NOT NULL DEFAULT 0"); + } + + /** + * 升级到版本5:添加置顶字段,用于便签置顶功能 + * @param db 数据库实例 + */ + private void upgradeToV5(SQLiteDatabase db) { + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.PINNED + + " INTEGER NOT NULL DEFAULT 0"); + } + + /** + * 升级到版本6:添加锁相关字段,用于便签和文件夹上锁功能 + * @param db 数据库实例 + */ + private void upgradeToV6(SQLiteDatabase db) { + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.IS_LOCKED + + " INTEGER NOT NULL DEFAULT 0"); + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.LOCK_PASSWORD + + " TEXT NOT NULL DEFAULT ''"); + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.LOCK_TYPE + + " INTEGER NOT NULL DEFAULT 0"); + } + + /** + * 升级到版本7:添加删除时间字段和相关触发器,用于最近删除功能 + * @param db 数据库实例 + */ + private void upgradeToV7(SQLiteDatabase db) { + // 添加DELETED_DATE字段,用于记录便签被删除的时间 + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.DELETED_DATE + + " INTEGER NOT NULL DEFAULT 0"); + + // 创建触发器:当便签被移动到回收站时,自动记录删除时间 + db.execSQL("CREATE TRIGGER record_deleted_date_on_trash " + + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " AND old." + NoteColumns.PARENT_ID + "!=" + Notes.ID_TRASH_FOLER + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.DELETED_DATE + "=strftime('%s','now') * 1000" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.ID + ";" + + " END"); + + // 创建触发器:当便签从回收站恢复时,自动清除删除时间 + db.execSQL("CREATE TRIGGER clear_deleted_date_on_restore " + + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " WHEN new." + NoteColumns.PARENT_ID + "!=" + Notes.ID_TRASH_FOLER + + " AND old." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.DELETED_DATE + "=0" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.ID + ";" + + " END"); + } +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/data/NotesProvider.java b/src/main/java/net/micode/notes/data/NotesProvider.java new file mode 100644 index 0000000..ceb1020 --- /dev/null +++ b/src/main/java/net/micode/notes/data/NotesProvider.java @@ -0,0 +1,424 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.data; + +import android.app.SearchManager; +import android.content.ContentProvider; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Intent; +import android.content.UriMatcher; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.net.Uri; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE; + +/** + * 便签应用的内容提供者(ContentProvider) + * 负责管理便签数据的CRUD操作,包括搜索功能 + */ +public class NotesProvider extends ContentProvider { + /** + * URI匹配器,用于匹配不同的URI请求,根据URI类型执行相应的操作 + */ + private static final UriMatcher mMatcher; + + /** + * 数据库帮助类实例,用于获取数据库连接 + */ + private NotesDatabaseHelper mHelper; + + /** + * 日志标签,用于日志输出 + */ + private static final String TAG = "NotesProvider"; + + /** + * URI匹配类型常量定义,用于区分不同的URI请求类型 + */ + 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匹配规则 + * 为不同类型的URI请求配置对应的匹配类型 + */ + static { + 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' 在SQLite中代表 '\n' 字符 + * 对于搜索结果中的标题和内容,我们将修剪 '\n' 和空白字符以显示更多信息 + */ + 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; + + /** + * 便签片段搜索查询的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; + + /** + * 初始化内容提供者 + * @return 如果初始化成功返回true,否则返回false + */ + @Override + public boolean onCreate() { + mHelper = NotesDatabaseHelper.getInstance(getContext()); + return true; + } + + /** + * 查询数据 + * @param uri 要查询的URI + * @param projection 要返回的列,null表示所有列 + * @param selection 查询条件,null表示无条件 + * @param selectionArgs 查询条件参数 + * @param sortOrder 排序方式,null表示默认排序 + * @return 包含查询结果的Cursor对象 + */ + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + String sortOrder) { + Cursor c = null; + SQLiteDatabase db = mHelper.getReadableDatabase(); + String id = null; + + // 根据URI类型执行不同的查询操作 + switch (mMatcher.match(uri)) { + case URI_NOTE: + // 查询所有便签 + c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_NOTE_ITEM: + // 查询单条便签记录 + id = uri.getPathSegments().get(1); + c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_DATA: + // 查询所有数据记录 + c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_DATA_ITEM: + // 查询单条数据记录 + id = uri.getPathSegments().get(1); + c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_SEARCH: + case URI_SEARCH_SUGGEST: + // 处理搜索和搜索建议请求 + if (sortOrder != null || projection != null) { + throw new IllegalArgumentException( + "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); + } + + String searchString = null; + // 根据URI类型获取搜索关键词 + if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { + if (uri.getPathSegments().size() > 1) { + searchString = uri.getPathSegments().get(1); + } + } else { + // 支持Android搜索框架的标准参数名"query"和当前实现使用的"pattern" + searchString = uri.getQueryParameter(SearchManager.QUERY); + if (TextUtils.isEmpty(searchString)) { + searchString = uri.getQueryParameter("pattern"); + } + } + + // 如果搜索关键词为空,返回null + if (TextUtils.isEmpty(searchString)) { + return null; + } + + try { + // 构造模糊查询字符串 + searchString = String.format("%%%s%%", searchString); + c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, + new String[] { searchString }); + } catch (IllegalStateException ex) { + Log.e(TAG, "got exception: " + ex.toString()); + } + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + + // 设置内容观察者,以便在数据变化时通知相关组件 + if (c != null) { + c.setNotificationUri(getContext().getContentResolver(), uri); + } + return c; + } + + /** + * 插入数据 + * @param uri 要插入数据的URI + * @param values 要插入的数据值 + * @return 新插入数据的URI + */ + @Override + public Uri insert(Uri uri, ContentValues values) { + SQLiteDatabase db = mHelper.getWritableDatabase(); + 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: + // 插入数据表记录 + if (values.containsKey(DataColumns.NOTE_ID)) { + noteId = values.getAsLong(DataColumns.NOTE_ID); + } else { + Log.d(TAG, "Wrong data format without note id:" + values.toString()); + } + insertedId = dataId = db.insert(TABLE.DATA, null, values); + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + + // 通知便签URI的数据变化 + if (noteId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); + } + + // 通知数据URI的数据变化 + if (dataId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); + } + + // 返回新插入数据的URI + return ContentUris.withAppendedId(uri, insertedId); + } + + /** + * 删除数据 + * @param uri 要删除数据的URI + * @param selection 删除条件,null表示无条件 + * @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: + // 删除便签记录(不删除ID小于0的系统文件夹) + selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; + count = db.delete(TABLE.NOTE, selection, selectionArgs); + break; + case URI_NOTE_ITEM: + // 删除单条便签记录 + id = uri.getPathSegments().get(1); + /** + * ID小于0的是系统文件夹,不允许删除(移动到回收站) + */ + long noteId = Long.valueOf(id); + if (noteId <= 0) { + break; + } + count = db.delete(TABLE.NOTE, + NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + break; + case URI_DATA: + // 删除数据记录 + count = db.delete(TABLE.DATA, selection, selectionArgs); + deleteData = true; + break; + case URI_DATA_ITEM: + // 删除单条数据记录 + id = uri.getPathSegments().get(1); + count = db.delete(TABLE.DATA, + DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + deleteData = true; + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + + // 如果成功删除数据,发送数据变化通知 + if (count > 0) { + if (deleteData) { + // 如果删除的是数据表记录,通知便签URI数据变化 + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + // 通知当前URI数据变化 + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } + + /** + * 更新数据 + * @param uri 要更新数据的URI + * @param values 更新的数据值 + * @param selection 更新条件,null表示无条件 + * @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 = uri.getPathSegments().get(1); + increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); + count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); + break; + case URI_DATA: + // 更新数据记录 + count = db.update(TABLE.DATA, values, selection, selectionArgs); + updateData = true; + break; + case URI_DATA_ITEM: + // 更新单条数据记录 + id = uri.getPathSegments().get(1); + count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); + updateData = true; + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + + // 如果成功更新数据,发送数据变化通知 + if (count > 0) { + if (updateData) { + // 如果更新的是数据表记录,通知便签URI数据变化 + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + // 通知当前URI数据变化 + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } + + /** + * 解析查询/更新条件 + * 将原始条件转换为SQL语句中的AND条件 + * @param selection 原始条件字符串 + * @return 格式化后的条件字符串 + */ + private String parseSelection(String selection) { + return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); + } + + /** + * 增加便签版本号 + * 当便签被修改时,调用此方法增加版本号 + * @param id 便签ID,如果id>0则更新指定便签,否则更新所有匹配条件的便签 + * @param selection 更新条件 + * @param selectionArgs 更新条件参数 + */ + private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { + StringBuilder sql = new StringBuilder(120); + sql.append("UPDATE "); + sql.append(TABLE.NOTE); + sql.append(" SET "); + sql.append(NoteColumns.VERSION); + sql.append("=" + NoteColumns.VERSION + "+1 "); + + // 构造WHERE子句 + if (id > 0 || !TextUtils.isEmpty(selection)) { + sql.append(" WHERE "); + } + if (id > 0) { + sql.append(NoteColumns.ID + "=" + String.valueOf(id)); + } + if (!TextUtils.isEmpty(selection)) { + String selectString = id > 0 ? parseSelection(selection) : selection; + // 替换预编译语句中的占位符 + for (String args : selectionArgs) { + selectString = selectString.replaceFirst("\\?", args); + } + sql.append(selectString); + } + + // 执行SQL语句更新版本号 + mHelper.getWritableDatabase().execSQL(sql.toString()); + } + + /** + * 返回指定URI的MIME类型 + * @param uri 要获取MIME类型的URI + * @return MIME类型字符串 + */ + @Override + public String getType(Uri uri) { + // TODO: 实现此方法,返回合适的MIME类型 + return null; + } +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/gtask/data/MetaData.java b/src/main/java/net/micode/notes/gtask/data/MetaData.java new file mode 100644 index 0000000..2a39a68 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/data/MetaData.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONException; +import org.json.JSONObject; + +/** + * MetaData类是Task的子类,用于存储与Google Tasks同步相关的元数据信息。 + *+ * 该类主要用于在GTask同步过程中存储任务的关联信息,将元数据以JSON格式存储在 + * Task的notes字段中,并提供了相应的解析和访问方法。 + *
+ */ +public class MetaData extends Task { + private final static String TAG = MetaData.class.getSimpleName(); + + /** + * 与当前元数据相关联的Google Task ID + */ + private String mRelatedGid = null; + + /** + * 设置元数据信息 + *+ * 将Google Task ID添加到元数据JSON对象中,并将其存储在Task的notes字段中。 + * 同时设置任务名称为元数据标识名称。 + *
+ * + * @param gid 与元数据关联的Google Task ID + * @param metaInfo 包含元数据信息的JSON对象 + */ + public void setMeta(String gid, JSONObject metaInfo) { + try { + // 将关联的Google Task ID添加到元数据中 + metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); + } catch (JSONException e) { + Log.e(TAG, "failed to put related gid"); + } + // 将元数据JSON对象转换为字符串并存储在notes字段中 + setNotes(metaInfo.toString()); + // 设置任务名称为元数据标识名称 + setName(GTaskStringUtils.META_NOTE_NAME); + } + + /** + * 获取与当前元数据相关联的Google Task ID + * + * @return 关联的Google Task ID,如果没有则返回null + */ + public String getRelatedGid() { + return mRelatedGid; + } + + /** + * 判断当前元数据是否值得保存 + *+ * 只有当notes字段不为null时,元数据才值得保存 + *
+ * + * @return 如果notes字段不为null则返回true,否则返回false + */ + @Override + public boolean isWorthSaving() { + return getNotes() != null; + } + + /** + * 从远程JSON数据设置内容 + *+ * 从远程获取的JSON数据中解析元信息,并提取关联的Google Task ID + *
+ * + * @param js 包含远程数据的JSON对象 + */ + @Override + public void setContentByRemoteJSON(JSONObject js) { + // 调用父类方法设置基本内容 + super.setContentByRemoteJSON(js); + // 如果notes字段不为null,则解析元数据 + if (getNotes() != null) { + try { + // 解析notes字段中的JSON元数据 + JSONObject metaInfo = new JSONObject(getNotes().trim()); + // 提取关联的Google Task ID + mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); + } catch (JSONException e) { + Log.w(TAG, "failed to get related gid"); + mRelatedGid = null; + } + } + } + + /** + * 从本地JSON数据设置内容(不支持) + *+ * 该方法不应该被调用,因为MetaData主要用于处理远程同步数据 + *
+ * + * @param js 本地JSON对象 + * @throws IllegalAccessError 总是抛出此异常,表示该方法不应该被调用 + */ + @Override + public void setContentByLocalJSON(JSONObject js) { + // 此方法不应该被调用 + throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); + } + + /** + * 从内容获取本地JSON数据(不支持) + *+ * 该方法不应该被调用,因为MetaData主要用于处理远程同步数据 + *
+ * + * @return 本地JSON对象 + * @throws IllegalAccessError 总是抛出此异常,表示该方法不应该被调用 + */ + @Override + public JSONObject getLocalJSONFromContent() { + throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); + } + + /** + * 获取同步操作(不支持) + *+ * 该方法不应该被调用,因为MetaData主要用于处理远程同步数据 + *
+ * + * @param c 本地数据库游标 + * @return 同步操作类型 + * @throws IllegalAccessError 总是抛出此异常,表示该方法不应该被调用 + */ + @Override + public int getSyncAction(Cursor c) { + throw new IllegalAccessError("MetaData:getSyncAction should not be called"); + } + +} diff --git a/src/main/java/net/micode/notes/gtask/data/Node.java b/src/main/java/net/micode/notes/gtask/data/Node.java new file mode 100644 index 0000000..dea45d5 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/data/Node.java @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; + +import org.json.JSONObject; + +/** + * Node类是GTask同步系统中的抽象基类,定义了同步节点的基本属性和操作接口。 + *+ * 该类为所有参与GTask同步的实体(如Task、TaskList等)提供了统一的接口和基础属性, + * 包括唯一标识符、名称、最后修改时间、删除状态等,并定义了同步操作所需的抽象方法。 + *
+ */ +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; + + /** + * 节点的唯一标识符(Google Task ID) + */ + private String mGid; + + /** + * 节点的名称 + */ + private String mName; + + /** + * 节点的最后修改时间戳 + */ + private long mLastModified; + + /** + * 节点的删除状态 + */ + private boolean mDeleted; + + /** + * 构造函数,初始化节点的默认值 + */ + public Node() { + mGid = null; + mName = ""; + mLastModified = 0; + 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 同步操作类型(参考SYNC_ACTION_*常量) + */ + public abstract int getSyncAction(Cursor c); + + /** + * 设置节点的唯一标识符 + * + * @param gid 节点的唯一标识符(Google Task ID) + */ + public void setGid(String gid) { + this.mGid = gid; + } + + /** + * 设置节点的名称 + * + * @param name 节点的名称 + */ + public void setName(String name) { + this.mName = name; + } + + /** + * 设置节点的最后修改时间戳 + * + * @param lastModified 最后修改时间戳 + */ + public void setLastModified(long lastModified) { + this.mLastModified = lastModified; + } + + /** + * 设置节点的删除状态 + * + * @param deleted 是否删除 + */ + public void setDeleted(boolean deleted) { + this.mDeleted = deleted; + } + + /** + * 获取节点的唯一标识符 + * + * @return 节点的唯一标识符(Google Task ID) + */ + public String getGid() { + return this.mGid; + } + + /** + * 获取节点的名称 + * + * @return 节点的名称 + */ + public String getName() { + return this.mName; + } + + /** + * 获取节点的最后修改时间戳 + * + * @return 最后修改时间戳 + */ + public long getLastModified() { + return this.mLastModified; + } + + /** + * 获取节点的删除状态 + * + * @return 是否删除 + */ + public boolean getDeleted() { + return this.mDeleted; + } + +} diff --git a/src/main/java/net/micode/notes/gtask/data/SqlData.java b/src/main/java/net/micode/notes/gtask/data/SqlData.java new file mode 100644 index 0000000..3d537ca --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/data/SqlData.java @@ -0,0 +1,337 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE; +import net.micode.notes.gtask.exception.ActionFailureException; + +import org.json.JSONException; +import org.json.JSONObject; + + +/** + * SqlData类是小米笔记应用中GTask同步模块的核心数据处理类,负责本地SQL数据的CRUD操作。CRUD 是数据库操作的四种基本功能缩写: + +- C(Create):创建新笔记数据 +- R(Read):读取现有笔记数据 +- U(Update):更新笔记数据 +- D(Delete):删除笔记数据 + *+ * 在Notes与Google Tasks的同步过程中,该类扮演着桥梁角色: + * 1. 接收并解析来自GTask的JSON格式数据 + * 2. 将数据转换为本地数据库可存储的格式 + * 3. 通过ContentResolver与本地ContentProvider交互,执行数据的插入、更新和删除操作 + * 4. 支持数据差异跟踪,仅提交修改的字段以优化性能 + * 5. 提供版本验证机制,避免同步冲突 + *
+ *+ * 该类是同步流程中的关键组件,确保本地笔记数据与Google Tasks之间的数据一致性和完整性。 + *
+ */ +public class SqlData { + private static final String TAG = SqlData.class.getSimpleName(); + + /** + * 无效ID常量,用于标记未初始化或无效的数据ID + * 在同步过程中用于区分新创建的数据和已存在的数据 + */ + private static final int INVALID_ID = -99999; + + /** + * 数据库查询投影列,定义了从数据库中获取的数据字段 + * 包含数据ID、MIME类型、内容以及扩展字段DATA1和DATA3 + */ + public static final String[] PROJECTION_DATA = new String[] { + DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, + DataColumns.DATA3 + }; + + /** + * 数据ID列在投影中的索引位置 + */ + public static final int DATA_ID_COLUMN = 0; + + /** + * 数据MIME类型列在投影中的索引位置 + * 用于区分不同类型的数据(如文本笔记、通话记录等) + */ + public static final int DATA_MIME_TYPE_COLUMN = 1; + + /** + * 数据内容列在投影中的索引位置 + * 存储笔记的主要内容 + */ + public static final int DATA_CONTENT_COLUMN = 2; + + /** + * 数据内容DATA1字段在投影中的索引位置 + * 用于存储整数类型的扩展数据(如笔记模式、通话日期等) + */ + public static final int DATA_CONTENT_DATA_1_COLUMN = 3; + + /** + * 数据内容DATA3字段在投影中的索引位置 + * 用于存储字符串类型的扩展数据(如电话号码等) + */ + public static final int DATA_CONTENT_DATA_3_COLUMN = 4; + + /** + * 用于访问ContentProvider的ContentResolver实例 + * 是与本地数据库交互的核心接口 + */ + private ContentResolver mContentResolver; + + /** + * 标记是否为新建数据 + * true表示该数据需要插入数据库,false表示需要更新数据库 + */ + private boolean mIsCreate; + + /** + * 数据ID + * 唯一标识数据库中的数据记录 + */ + private long mDataId; + + /** + * 数据MIME类型 + * 定义数据的类型,如文本笔记(DataConstants.NOTE)或通话记录 + */ + private String mDataMimeType; + + /** + * 数据内容 + * 存储笔记的主要文本内容 + */ + private String mDataContent; + + /** + * 数据内容的DATA1字段 + * 根据MIME类型不同存储不同的整数数据,如: + * - 对于文本笔记:存储笔记模式(普通模式或 checklist 模式) + * - 对于通话记录:存储通话日期 + */ + private long mDataContentData1; + + /** + * 数据内容的DATA3字段 + * 根据MIME类型不同存储不同的字符串数据,如: + * - 对于通话记录:存储电话号码 + */ + private String mDataContentData3; + + /** + * 用于跟踪数据变化的ContentValues对象 + * 只包含已修改的字段,用于优化数据库更新操作 + */ + private ContentValues mDiffDataValues; + + /** + * 构造函数,用于创建新的SqlData实例(用于插入新数据) + *+ * 初始化所有字段为默认值,并将mIsCreate标记设置为true + *
+ * + * @param context 上下文对象,用于获取ContentResolver实例 + */ + public SqlData(Context context) { + mContentResolver = context.getContentResolver(); + mIsCreate = true; + mDataId = INVALID_ID; + mDataMimeType = DataConstants.NOTE; + mDataContent = ""; + mDataContentData1 = 0; + mDataContentData3 = ""; + mDiffDataValues = new ContentValues(); + } + + /** + * 构造函数,用于从数据库Cursor加载SqlData实例(用于更新现有数据) + *+ * 从Cursor中读取数据并初始化所有字段,将mIsCreate标记设置为false + *
+ * + * @param context 上下文对象,用于获取ContentResolver实例 + * @param c 数据库Cursor对象,包含要加载的数据记录 + */ + public SqlData(Context context, Cursor c) { + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(c); + mDiffDataValues = new ContentValues(); + } + + /** + * 从数据库Cursor中加载数据到当前SqlData实例 + *+ * 根据PROJECTION_DATA中定义的列顺序,从Cursor中读取对应字段的值 + *
+ * + * @param c 包含数据的Cursor对象,必须指向有效的数据行 + */ + private void loadFromCursor(Cursor c) { + mDataId = c.getLong(DATA_ID_COLUMN); + mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); + mDataContent = c.getString(DATA_CONTENT_COLUMN); + mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); + mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); + } + + /** + * 从JSON对象设置数据内容,并跟踪数据变化 + *+ * 该方法是同步过程中的关键方法,用于将从GTask获取的JSON数据转换为本地数据格式 + * 同时会跟踪数据变化,仅将修改的字段记录到mDiffDataValues中 + *
+ * + * @param js 包含GTask数据的JSON对象 + * @throws JSONException 如果JSON解析失败 + */ + public void setContent(JSONObject js) throws JSONException { + long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; + if (mIsCreate || mDataId != dataId) { + mDiffDataValues.put(DataColumns.ID, dataId); + } + mDataId = dataId; + + String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) + : DataConstants.NOTE; + if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { + mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); + } + mDataMimeType = dataMimeType; + + String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; + if (mIsCreate || !mDataContent.equals(dataContent)) { + mDiffDataValues.put(DataColumns.CONTENT, dataContent); + } + mDataContent = dataContent; + + long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; + if (mIsCreate || mDataContentData1 != dataContentData1) { + mDiffDataValues.put(DataColumns.DATA1, dataContentData1); + } + mDataContentData1 = dataContentData1; + + String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; + if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { + mDiffDataValues.put(DataColumns.DATA3, dataContentData3); + } + mDataContentData3 = dataContentData3; + } + + /** + * 获取当前数据的JSON表示 + *+ * 将本地数据转换为JSON格式,用于与GTask进行数据交换 + * 注意:只有已提交到数据库的数据才能获取JSON表示 + *
+ * + * @return 包含当前数据的JSON对象,如果数据未提交到数据库则返回null + * @throws JSONException 如果JSON构建失败 + */ + public JSONObject getContent() throws JSONException { + if (mIsCreate) { + Log.e(TAG, "it seems that we haven't created this in database yet"); + return null; + } + JSONObject js = new JSONObject(); + js.put(DataColumns.ID, mDataId); + js.put(DataColumns.MIME_TYPE, mDataMimeType); + js.put(DataColumns.CONTENT, mDataContent); + js.put(DataColumns.DATA1, mDataContentData1); + js.put(DataColumns.DATA3, mDataContentData3); + return js; + } + + /** + * 将数据提交到本地数据库 + *+ * 这是SqlData类的核心方法,根据mIsCreate标记执行插入或更新操作: + * 1. 如果是新数据(mIsCreate=true),执行插入操作 + * 2. 如果是现有数据(mIsCreate=false),仅当有数据变化时执行更新操作 + * 3. 支持版本验证机制,避免在同步过程中出现数据冲突 + *
+ * + * @param noteId 所属的Note ID,用于关联到具体的笔记 + * @param validateVersion 是否验证版本,true表示需要进行版本检查 + * @param version 版本号,用于版本验证 + * @throws ActionFailureException 如果数据提交失败 + */ + public void commit(long noteId, boolean validateVersion, long version) { + + if (mIsCreate) { + if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { + mDiffDataValues.remove(DataColumns.ID); + } + + mDiffDataValues.put(DataColumns.NOTE_ID, noteId); + Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); + try { + mDataId = Long.valueOf(uri.getPathSegments().get(1)); + } 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, + " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { + String.valueOf(noteId), String.valueOf(version) + }); + } + if (result == 0) { + Log.w(TAG, "there is no update. maybe user updates note when syncing"); + } + } + } + + mDiffDataValues.clear(); + mIsCreate = false; + } + + /** + * 获取数据ID + *+ * 返回当前数据的唯一标识符,用于在数据库中定位该记录 + *
+ * + * @return 数据ID,如果数据未提交到数据库则返回INVALID_ID + */ + public long getId() { + return mDataId; + } +} diff --git a/src/main/java/net/micode/notes/gtask/data/SqlNote.java b/src/main/java/net/micode/notes/gtask/data/SqlNote.java new file mode 100644 index 0000000..ad39ff5 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/data/SqlNote.java @@ -0,0 +1,714 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.appwidget.AppWidgetManager; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.tool.GTaskStringUtils; +import net.micode.notes.tool.ResourceParser; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + + +/** + * SqlNote类是小米笔记应用中GTask同步模块的核心类,负责本地笔记数据的CRUD操作。 + *+ * 在Notes与Google Tasks的同步过程中,该类扮演着重要角色: + * 1. 封装本地笔记数据模型,支持笔记和文件夹两种类型 + * 2. 通过ContentResolver与本地ContentProvider交互,执行数据的插入、更新和删除操作 + * 3. 支持将JSON格式的GTask数据转换为本地数据模型 + * 4. 支持将本地数据模型转换为JSON格式以便与GTask同步 + * 5. 实现数据差异跟踪,仅提交修改的字段以优化性能 + * 6. 提供版本验证机制,避免同步冲突 + *
+ */ +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, + NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE, + NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID, + NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID, + NoteColumns.VERSION + }; + +/** + * 投影列索引:笔记ID + */ + public static final int ID_COLUMN = 0; + + /** + * 投影列索引:提醒日期 + */ + public static final int ALERTED_DATE_COLUMN = 1; + + /** + * 投影列索引:背景颜色ID + */ + 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; + + /** + * 投影列索引:父文件夹ID + */ + public static final int PARENT_ID_COLUMN = 7; + + /** + * 投影列索引:笔记摘要 + */ + public static final int SNIPPET_COLUMN = 8; + + /** + * 投影列索引:笔记类型(笔记或文件夹) + */ + public static final int TYPE_COLUMN = 9; + + /** + * 投影列索引:小部件ID + */ + public static final int WIDGET_ID_COLUMN = 10; + + /** + * 投影列索引:小部件类型 + */ + public static final int WIDGET_TYPE_COLUMN = 11; + + /** + * 投影列索引:同步ID + */ + public static final int SYNC_ID_COLUMN = 12; + + /** + * 投影列索引:本地修改标记 + */ + public static final int LOCAL_MODIFIED_COLUMN = 13; + + /** + * 投影列索引:原始父文件夹ID + */ + public static final int ORIGIN_PARENT_ID_COLUMN = 14; + + /** + * 投影列索引:Google Task ID + */ + public static final int GTASK_ID_COLUMN = 15; + + /** + * 投影列索引:版本号 + */ + public static final int VERSION_COLUMN = 16; + + /** + * 上下文对象,用于访问系统服务 + */ + private Context mContext; + + /** + * ContentResolver对象,用于与ContentProvider交互 + */ + private ContentResolver mContentResolver; + + /** + * 标记是否为新创建的笔记 + */ + private boolean mIsCreate; + + /** + * 笔记ID + */ + private long mId; + + /** + * 提醒日期 + */ + private long mAlertDate; + + /** + * 背景颜色ID + */ + private int mBgColorId; + + /** + * 创建日期 + */ + private long mCreatedDate; + + /** + * 是否有附件(0:无,1:有) + */ + private int mHasAttachment; + + /** + * 修改日期 + */ + private long mModifiedDate; + + /** + * 父文件夹ID + */ + private long mParentId; + + /** + * 笔记摘要 + */ + private String mSnippet; + + /** + * 笔记类型(笔记或文件夹) + */ + private int mType; + + /** + * 小部件ID + */ + private int mWidgetId; + + /** + * 小部件类型 + */ + private int mWidgetType; + + /** + * 原始父文件夹ID + */ + private long mOriginParent; + + /** + * 版本号,用于避免同步冲突 + */ + private long mVersion; + + /** + * 记录笔记数据的变更,仅提交修改的字段以优化性能 + */ + private ContentValues mDiffNoteValues; + + /** + * 笔记内容列表,每个SqlData对象代表笔记的一个内容部分 + */ + private ArrayList+ * 在小米笔记与Google Tasks的同步过程中,该类负责: + * 1. 封装Google Tasks任务的数据模型 + * 2. 实现任务的创建、更新等同步操作 + * 3. 处理本地数据与Google Tasks数据之间的转换 + * 4. 管理任务的层次结构和关系 + *
+ */ +public class Task extends Node { + private static final String TAG = Task.class.getSimpleName(); + + /** + * 任务是否已完成 + */ + private boolean mCompleted; + + /** + * 任务的备注信息 + */ + private String mNotes; + + /** + * 任务的元信息,包含与本地笔记的关联数据 + */ + private JSONObject mMetaInfo; + + /** + * 任务的前一个兄弟节点(在同一父任务列表中的前一个任务) + */ + private Task mPriorSibling; + + /** + * 任务的父任务列表 + */ + private TaskList mParent; + +/** + * 构造函数,创建一个新的Task对象 + */ + public Task() { + super(); + mCompleted = false; + mNotes = null; + mPriorSibling = null; + mParent = null; + mMetaInfo = null; + } + +/** + * 获取创建任务的JSON动作 + *+ * 该方法生成用于向Google Tasks服务器发送创建任务请求的JSON数据 + *
+ * + * @param actionId 动作ID,用于标识当前操作 + * @return 包含创建任务信息的JSON对象 + * @throws ActionFailureException 如果生成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 + 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"); + entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, + GTaskStringUtils.GTASK_JSON_TYPE_TASK); + if (getNotes() != null) { + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); + } + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + // parent_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 + js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); + + // prior_sibling_id + if (mPriorSibling != null) { + js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate task-create jsonobject"); + } + + return js; + } + +/** + * 获取更新任务的JSON动作 + *+ * 该方法生成用于向Google Tasks服务器发送更新任务请求的JSON数据 + *
+ * + * @param actionId 动作ID,用于标识当前操作 + * @return 包含更新任务信息的JSON对象 + * @throws ActionFailureException 如果生成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 + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // id + js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); + + // entity_delta + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + if (getNotes() != null) { + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); + } + entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate task-update jsonobject"); + } + + return js; + } + +/** + * 从Google Tasks服务器返回的JSON数据设置任务内容 + * + * @param js 包含Google Tasks任务数据的JSON对象 + * @throws ActionFailureException 如果解析JSON数据失败 + */ + public void setContentByRemoteJSON(JSONObject js) { + if (js != null) { + try { + // 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)); + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to get task content from jsonobject"); + } + } + } + +/** + * 从本地JSON数据设置任务内容 + * + * @param js 包含本地笔记数据的JSON对象 + */ + public void setContentByLocalJSON(JSONObject js) { + if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) + || !js.has(GTaskStringUtils.META_HEAD_DATA)) { + Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); + } + + 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)) { + setName(data.getString(DataColumns.CONTENT)); + break; + } + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + } + +/** + * 获取任务内容的本地JSON表示 + *+ * 该方法将任务数据转换为本地笔记系统使用的JSON格式 + *
+ * + * @return 包含任务数据的本地JSON对象,如果转换失败返回null + */ + 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; + } + + JSONObject js = new JSONObject(); + JSONObject note = new JSONObject(); + JSONArray dataArray = new JSONArray(); + JSONObject data = new JSONObject(); + data.put(DataColumns.CONTENT, name); + dataArray.put(data); + js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + 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)) { + data.put(DataColumns.CONTENT, getName()); + break; + } + } + + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + return mMetaInfo; + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return null; + } + } + +/** + * 设置任务的元信息 + *+ * 元信息包含任务与本地笔记的关联数据 + *
+ * + * @param metaData 包含元信息的MetaData对象 + */ + public void setMetaInfo(MetaData metaData) { + if (metaData != null && metaData.getNotes() != null) { + try { + mMetaInfo = new JSONObject(metaData.getNotes()); + } catch (JSONException e) { + Log.w(TAG, e.toString()); + mMetaInfo = null; + } + } + } + +/** + * 获取任务的同步动作类型 + *+ * 该方法根据本地数据和远程数据的状态,确定需要执行的同步操作类型 + *
+ * + * @param c 包含本地笔记数据的Cursor对象 + * @return 同步动作类型,取值为SYNC_ACTION_*常量之一 + */ + 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); + } + + if (noteInfo == null) { + Log.w(TAG, "it seems that note meta has been deleted"); + return SYNC_ACTION_UPDATE_REMOTE; + } + + 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 + 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; + } + } + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + + return SYNC_ACTION_ERROR; + } + +/** + * 判断任务是否值得保存 + *+ * 如果任务有元信息、名称或备注,则认为值得保存 + *
+ * + * @return 任务值得保存返回true,否则返回false + */ + public boolean isWorthSaving() { + return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) + || (getNotes() != null && getNotes().trim().length() > 0); + } + +/** + * 设置任务的完成状态 + * + * @param completed 任务是否已完成 + */ + public void setCompleted(boolean completed) { + this.mCompleted = completed; + } + +/** + * 设置任务的备注信息 + * + * @param notes 任务的备注信息 + */ + public void setNotes(String notes) { + this.mNotes = notes; + } + +/** + * 设置任务的前一个兄弟节点 + * + * @param priorSibling 前一个兄弟任务 + */ + public void setPriorSibling(Task priorSibling) { + this.mPriorSibling = priorSibling; + } + +/** + * 设置任务的父任务列表 + * + * @param parent 父任务列表 + */ + public void setParent(TaskList parent) { + this.mParent = parent; + } + +/** + * 获取任务的完成状态 + * + * @return 任务是否已完成 + */ + public boolean getCompleted() { + return this.mCompleted; + } + +/** + * 获取任务的备注信息 + * + * @return 任务的备注信息 + */ + public String getNotes() { + return this.mNotes; + } + +/** + * 获取任务的前一个兄弟节点 + * + * @return 前一个兄弟任务 + */ + public Task getPriorSibling() { + return this.mPriorSibling; + } + +/** + * 获取任务的父任务列表 + * + * @return 父任务列表 + */ + public TaskList getParent() { + return this.mParent; + } + +} diff --git a/src/main/java/net/micode/notes/gtask/data/TaskList.java b/src/main/java/net/micode/notes/gtask/data/TaskList.java new file mode 100644 index 0000000..1cfab78 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/data/TaskList.java @@ -0,0 +1,486 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + + +/** + * TaskList类是Node类的子类,用于表示Google Tasks中的任务列表。 + *+ * 在小米笔记与Google Tasks的同步过程中,该类负责: + * 1. 封装Google Tasks任务列表的数据模型 + * 2. 管理任务列表中的子任务(Task对象) + * 3. 实现任务列表的创建、更新等同步操作 + * 4. 处理本地文件夹与Google Tasks列表之间的转换 + *
+ */ +public class TaskList extends Node { + private static final String TAG = TaskList.class.getSimpleName(); + + /** + * 任务列表的索引位置 + */ + private int mIndex; + + /** + * 任务列表中的子任务列表 + */ + private ArrayList+ * 该方法生成用于向Google Tasks服务器发送创建任务列表请求的JSON数据 + *
+ * + * @param actionId 动作ID,用于标识当前操作 + * @return 包含创建任务列表信息的JSON对象 + * @throws ActionFailureException 如果生成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 + 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"); + entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, + GTaskStringUtils.GTASK_JSON_TYPE_GROUP); + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate tasklist-create jsonobject"); + } + + return js; + } + +/** + * 获取更新任务列表的JSON动作 + *+ * 该方法生成用于向Google Tasks服务器发送更新任务列表请求的JSON数据 + *
+ * + * @param actionId 动作ID,用于标识当前操作 + * @return 包含更新任务列表信息的JSON对象 + * @throws ActionFailureException 如果生成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 + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // 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()); + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate tasklist-update jsonobject"); + } + + return js; + } + +/** + * 从Google Tasks服务器返回的JSON数据设置任务列表内容 + * + * @param js 包含Google Tasks任务列表数据的JSON对象 + * @throws ActionFailureException 如果解析JSON数据失败 + */ + public void setContentByRemoteJSON(JSONObject js) { + if (js != null) { + try { + // 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)); + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to get tasklist content from jsonobject"); + } + } + } + +/** + * 从本地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"); + } + + 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); + } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { + if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); + else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_CALL_NOTE); + else + Log.e(TAG, "invalid system folder"); + } else { + Log.e(TAG, "error type"); + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + } + +/** + * 获取任务列表内容的本地JSON表示 + *+ * 该方法将任务列表数据转换为本地文件夹系统使用的JSON格式 + *
+ * + * @return 包含任务列表数据的本地JSON对象,如果转换失败返回null + */ + 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); + else + folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + + js.put(GTaskStringUtils.META_HEAD_NOTE, folder); + + return js; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return null; + } + } + +/** + * 获取任务列表的同步动作类型 + *+ * 该方法根据本地数据和远程数据的状态,确定需要执行的同步操作类型 + *
+ * + * @param c 包含本地文件夹数据的Cursor对象 + * @return 同步动作类型,取值为SYNC_ACTION_*常量之一 + */ + 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 + 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; + } + } + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + + return SYNC_ACTION_ERROR; + } + +/** + * 获取任务列表中的子任务数量 + * + * @return 子任务数量 + */ + public int getChildTaskCount() { + return mChildren.size(); + } + +/** + * 向任务列表中添加子任务 + * + * @param task 要添加的子任务 + * @return 添加成功返回true,否则返回false + */ + 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); + } + } + return ret; + } + +/** + * 在指定位置向任务列表中添加子任务 + * + * @param task 要添加的子任务 + * @param index 要添加的位置索引 + * @return 添加成功返回true,否则返回false + */ + public boolean addChildTask(Task task, int index) { + if (index < 0 || index > mChildren.size()) { + Log.e(TAG, "add child task: invalid index"); + return false; + } + + int pos = mChildren.indexOf(task); + if (task != null && pos == -1) { + mChildren.add(index, task); + + // update the task list + Task preTask = null; + Task afterTask = null; + if (index != 0) + preTask = mChildren.get(index - 1); + if (index != mChildren.size() - 1) + afterTask = mChildren.get(index + 1); + + task.setPriorSibling(preTask); + if (afterTask != null) + afterTask.setPriorSibling(task); + } + + return true; + } + +/** + * 从任务列表中移除子任务 + * + * @param task 要移除的子任务 + * @return 移除成功返回true,否则返回false + */ + public boolean removeChildTask(Task task) { + boolean ret = false; + int index = mChildren.indexOf(task); + if (index != -1) { + 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)); + } + } + } + return ret; + } + +/** + * 移动任务列表中的子任务到指定位置 + * + * @param task 要移动的子任务 + * @param index 目标位置索引 + * @return 移动成功返回true,否则返回false + */ + public boolean moveChildTask(Task task, int index) { + + if (index < 0 || index >= mChildren.size()) { + Log.e(TAG, "move child task: invalid index"); + return false; + } + + int pos = mChildren.indexOf(task); + if (pos == -1) { + Log.e(TAG, "move child task: the task should in the list"); + return false; + } + + if (pos == index) + return true; + return (removeChildTask(task) && addChildTask(task, index)); + } + +/** + * 根据Google Task ID查找子任务 + * + * @param gid Google Task ID + * @return 找到的子任务,如果找不到返回null + */ + public Task findChildTaskByGid(String gid) { + for (int i = 0; i < mChildren.size(); i++) { + Task t = mChildren.get(i); + if (t.getGid().equals(gid)) { + return t; + } + } + 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"); + return null; + } + return mChildren.get(index); + } + +/** + * 根据Google Task ID获取子任务 + *+ * 注意:该方法与findChildTaskByGid功能相同,名称可能存在拼写错误("ChilTask"应为"ChildTask") + *
+ * + * @param gid Google Task ID + * @return 找到的子任务,如果找不到返回null + */ + public Task getChilTaskByGid(String gid) { + for (Task task : mChildren) { + if (task.getGid().equals(gid)) + return task; + } + return null; + } + +/** + * 获取任务列表中的所有子任务 + * + * @return 包含所有子任务的ArrayList + */ + public ArrayList+ * 当GTask同步操作(如创建、更新、删除任务或任务列表)执行失败时抛出此异常 + *
+ */ +public class ActionFailureException extends RuntimeException { + private static final long serialVersionUID = 4425249765923293627L; + + public ActionFailureException() { + super(); + } + + public ActionFailureException(String paramString) { + super(paramString); + } + + public ActionFailureException(String paramString, Throwable paramThrowable) { + super(paramString, paramThrowable); + } +} diff --git a/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java b/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java new file mode 100644 index 0000000..b9f564d --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.exception; + +/** + * NetworkFailureException是GTask同步过程中用于表示网络操作失败的自定义检查型异常 + *+ * 当GTask同步操作(如网络请求、数据传输)因网络问题(如网络连接中断、超时等)失败时抛出此异常 + *
+ */ +public class NetworkFailureException extends Exception { + private static final long serialVersionUID = 2107610287180234136L; + + public NetworkFailureException() { + super(); + } + + public NetworkFailureException(String paramString) { + super(paramString); + } + + public NetworkFailureException(String paramString, Throwable paramThrowable) { + super(paramString, paramThrowable); + } +} diff --git a/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java new file mode 100644 index 0000000..9e52a69 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java @@ -0,0 +1,209 @@ + +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.remote; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.os.AsyncTask; + +import net.micode.notes.R; +import net.micode.notes.ui.NotesListActivity; +import net.micode.notes.ui.NotesPreferenceActivity; + + +/** + * GTaskASyncTask是用于在后台执行GTask同步操作的异步任务类 + *+ * 该类负责: + * 1. 在后台线程执行GTask同步操作 + * 2. 显示同步进度通知 + * 3. 处理同步结果并显示相应通知 + * 4. 支持同步取消功能 + *
+ */ +public class GTaskASyncTask extends AsyncTask+ * 该类提供了以下主要功能: + * 1. Google账号登录和认证 + * 2. 创建、更新、删除任务 + * 3. 创建、更新、删除任务列表 + * 4. 移动任务(在同一任务列表内或不同任务列表之间) + * 5. 获取任务列表和任务数据 + *
+ *+ * 该类采用单例模式设计,确保应用中只有一个GTask客户端实例 + *
+ */ +public class GTaskClient { + /** + * 日志标签 + */ + private static final String TAG = GTaskClient.class.getSimpleName(); + + /** + * Google Tasks基础URL + */ + private static final String GTASK_URL = "https://mail.google.com/tasks/"; + + /** + * Google Tasks GET请求URL + */ + private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; + + /** + * Google Tasks POST请求URL + */ + private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; + + /** + * GTaskClient单例实例 + */ + private static GTaskClient mInstance = null; + + /** + * HTTP客户端实例,用于与Google Tasks服务器进行通信 + */ + private DefaultHttpClient mHttpClient; + + /** + * 当前使用的GET请求URL + */ + private String mGetUrl; + + /** + * 当前使用的POST请求URL + */ + private String mPostUrl; + + /** + * Google Tasks客户端版本号 + */ + private long mClientVersion; + + /** + * 登录状态标志 + */ + private boolean mLoggedin; + + /** + * 上次登录时间 + */ + private long mLastLoginTime; + + /** + * 操作ID,用于标识不同的同步操作 + */ + private int mActionId; + + /** + * 当前同步的Google账号 + */ + private Account mAccount; + + /** + * 更新操作数组,用于批量提交更新操作 + */ + private JSONArray mUpdateArray; + + /** + * GTaskClient构造函数(私有,用于单例模式) + */ + private GTaskClient() { + mHttpClient = null; + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + mClientVersion = -1; + mLoggedin = false; + mLastLoginTime = 0; + mActionId = 1; + mAccount = null; + mUpdateArray = null; + } + + /** + * 获取GTaskClient单例实例 + * + * @return GTaskClient单例实例 + */ + public static synchronized GTaskClient getInstance() { + if (mInstance == null) { + mInstance = new GTaskClient(); + } + return mInstance; + } + + /** + * 登录Google Tasks账号 + *+ * 如果距离上次登录时间不超过5分钟,则不需要重新登录 + * 如果账号发生变化,需要重新登录 + *
+ * + * @param activity 调用登录的Activity + * @return 登录成功返回true,失败返回false + */ + public boolean login(Activity activity) { + // we suppose that the cookie would expire after 5 minutes + // then we need to re-login + 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))) { + mLoggedin = false; + } + + if (mLoggedin) { + Log.d(TAG, "already logged in"); + return true; + } + + mLastLoginTime = System.currentTimeMillis(); + String authToken = loginGoogleAccount(activity, false); + if (authToken == null) { + Log.e(TAG, "login google account failed"); + return false; + } + + // login with custom domain if necessary + if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() + .endsWith("googlemail.com"))) { + StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); + int index = mAccount.name.indexOf('@') + 1; + String suffix = mAccount.name.substring(index); + url.append(suffix + "/"); + mGetUrl = url.toString() + "ig"; + mPostUrl = url.toString() + "r/ig"; + + if (tryToLoginGtask(activity, authToken)) { + mLoggedin = true; + } + } + + // try to login with google official url + if (!mLoggedin) { + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + if (!tryToLoginGtask(activity, authToken)) { + return false; + } + } + + mLoggedin = true; + return true; + } + + /** + * 登录Google账号,获取认证令牌 + * + * @param activity 调用登录的Activity + * @param invalidateToken 是否使当前令牌失效 + * @return 认证令牌字符串,失败返回null + */ + private String loginGoogleAccount(Activity activity, boolean invalidateToken) { + String authToken; + AccountManager accountManager = AccountManager.get(activity); + Account[] accounts = accountManager.getAccountsByType("com.google"); + + if (accounts.length == 0) { + Log.e(TAG, "there is no available google account"); + return null; + } + + String accountName = NotesPreferenceActivity.getSyncAccountName(activity); + Account account = null; + for (Account a : accounts) { + if (a.name.equals(accountName)) { + account = a; + break; + } + } + if (account != null) { + mAccount = account; + } else { + Log.e(TAG, "unable to get an account with the same name in the settings"); + return null; + } + + // get the token now + AccountManagerFuture+ * 如果登录失败,会尝试使令牌失效并重新登录 + *
+ * + * @param activity 调用登录的Activity + * @param authToken 认证令牌 + * @return 登录成功返回true,失败返回false + */ + 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"); + return false; + } + + if (!loginGtask(authToken)) { + Log.e(TAG, "login gtask failed"); + return false; + } + } + return true; + } + + /** + * 使用认证令牌登录Google Tasks + * + * @param authToken 认证令牌 + * @return 登录成功返回true,失败返回false + */ + private boolean loginGtask(String authToken) { + int timeoutConnection = 10000; + int timeoutSocket = 15000; + HttpParams httpParameters = new BasicHttpParams(); + HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); + HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); + mHttpClient = new DefaultHttpClient(httpParameters); + BasicCookieStore localBasicCookieStore = new BasicCookieStore(); + 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 + List+ * 支持gzip和deflate压缩格式 + *
+ * + * @param entity HTTP响应实体 + * @return 响应内容字符串 + * @throws IOException 如果读取响应内容失败 + */ + private String getResponseContent(HttpEntity entity) throws IOException { + String contentEncoding = null; + if (entity.getContentEncoding() != null) { + contentEncoding = entity.getContentEncoding().getValue(); + Log.d(TAG, "encoding: " + contentEncoding); + } + + InputStream input = entity.getContent(); + if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { + input = new GZIPInputStream(entity.getContent()); + } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { + Inflater inflater = new Inflater(true); + input = new InflaterInputStream(entity.getContent(), inflater); + } + + try { + InputStreamReader isr = new InputStreamReader(input); + BufferedReader br = new BufferedReader(isr); + StringBuilder sb = new StringBuilder(); + + while (true) { + String buff = br.readLine(); + if (buff == null) { + return sb.toString(); + } + sb = sb.append(buff); + } + } finally { + input.close(); + } + } + + /** + * 发送POST请求到Google Tasks服务器 + * + * @param js 请求内容的JSON对象 + * @return 响应内容的JSON对象 + * @throws NetworkFailureException 如果网络请求失败 + * @throws ActionFailureException 如果请求格式或响应解析失败 + */ + private JSONObject postRequest(JSONObject js) throws NetworkFailureException { + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + HttpPost httpPost = createHttpPost(); + try { + LinkedList+ * 如果更新数组中的操作数量超过10个,则立即提交更新 + *
+ * + * @param node 要更新的节点对象 + * @throws NetworkFailureException 如果网络请求失败 + * @throws ActionFailureException 如果更新操作添加失败 + */ + public void addUpdateNode(Node node) throws NetworkFailureException { + if (node != null) { + // too many update items may result in an error + // set max to 10 items + if (mUpdateArray != null && mUpdateArray.length() > 10) { + commitUpdate(); + } + + if (mUpdateArray == null) + mUpdateArray = new JSONArray(); + mUpdateArray.put(node.getUpdateAction(getActionId())); + } + } + + /** + * 移动任务 + *+ * 支持在同一任务列表内移动或在不同任务列表之间移动 + *
+ * + * @param task 要移动的任务 + * @param preParent 任务原来的父任务列表 + * @param curParent 任务现在的父任务列表 + * @throws NetworkFailureException 如果网络请求失败 + * @throws ActionFailureException 如果任务移动失败 + */ + public void moveTask(Task task, TaskList preParent, TaskList curParent) + throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + // action_list + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); + if (preParent == curParent && task.getPriorSibling() != null) { + // put prioring_sibing_id only if moving within the tasklist and + // it is not the first one + action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); + } + action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); + action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); + if (preParent != curParent) { + // put the dest_list only if moving between tasklists + action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); + } + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("move task: handing jsonobject failed"); + } + } + + /** + * 删除节点(任务或任务列表) + * + * @param node 要删除的节点对象 + * @throws NetworkFailureException 如果网络请求失败 + * @throws ActionFailureException 如果节点删除失败 + */ + 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); + mUpdateArray = null; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("delete node: handing jsonobject failed"); + } + } + + /** + * 获取所有任务列表 + * + * @return 包含所有任务列表的JSON数组 + * @throws NetworkFailureException 如果网络请求失败 + * @throws ActionFailureException 如果获取任务列表失败 + */ + public JSONArray getTaskLists() throws NetworkFailureException { + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + try { + HttpGet httpGet = new HttpGet(mGetUrl); + HttpResponse response = null; + response = mHttpClient.execute(httpGet); + + // get the task list + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin != -1 && end != -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); + } catch (ClientProtocolException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (IOException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task lists: handing jasonobject failed"); + } + } + + /** + * 获取指定任务列表中的所有任务 + * + * @param listGid 任务列表的Google ID + * @return 包含任务列表中所有任务的JSON数组 + * @throws NetworkFailureException 如果网络请求失败 + * @throws ActionFailureException 如果获取任务失败 + */ + public JSONArray getTaskList(String listGid) throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + 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()); + action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); + action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); + 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); + return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task list: handing jsonobject failed"); + } + } + + /** + * 获取当前同步的Google账号 + * + * @return 当前同步的Google账号 + */ + public Account getSyncAccount() { + return mAccount; + } + + /** + * 重置更新数组 + */ + public void resetUpdateArray() { + mUpdateArray = null; + } +} diff --git a/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java b/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java new file mode 100644 index 0000000..09c7b79 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java @@ -0,0 +1,944 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.remote; + +import android.app.Activity; +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.data.MetaData; +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.SqlNote; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + + +/** + * GTaskManager是GTask同步模块的核心管理类,负责协调本地笔记与Google Tasks服务器之间的同步 + *+ * 该类采用单例模式,提供以下主要功能: + * 1. 管理同步状态和进度 + * 2. 初始化远程任务列表 + * 3. 同步本地和远程内容(文件夹和笔记) + * 4. 处理同步冲突和错误 + *
+ */ +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; + + /** + * GTaskManager的单例实例 + */ + private static GTaskManager mInstance = null; + + /** + * 用于Google登录的Activity实例 + */ + private Activity mActivity; + + /** + * 应用上下文 + */ + private Context mContext; + + /** + * 内容解析器,用于访问本地数据库 + */ + private ContentResolver mContentResolver; + + /** + * 同步状态标志,表示是否正在进行同步 + */ + private boolean mSyncing; + + /** + * 取消标志,表示同步是否已被取消 + */ + private boolean mCancelled; + + /** + * 远程任务列表的HashMap,键为任务列表的GID + */ + private HashMap+ * 该服务提供了以下主要功能: + * 1. 启动GTask同步操作 + * 2. 取消正在进行的同步操作 + * 3. 通过广播通知同步状态和进度 + *
+ */ +public class GTaskSyncService extends Service { + /** + * 同步操作类型的Intent参数名称 + */ + public final static String ACTION_STRING_NAME = "sync_action_type"; + + /** + * 启动同步操作的常量 + */ + public final static int ACTION_START_SYNC = 0; + + /** + * 取消同步操作的常量 + */ + public final static int ACTION_CANCEL_SYNC = 1; + + /** + * 无效操作的常量 + */ + public final static int ACTION_INVALID = 2; + + /** + * GTask同步服务广播的Intent名称 + */ + public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; + + /** + * 广播中表示同步状态的参数名称 + */ + public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; + + /** + * 广播中表示同步进度的参数名称 + */ + public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; + + /** + * 当前正在执行的同步任务实例 + */ + private static GTaskASyncTask mSyncTask = null; + + /** + * 当前同步进度信息 + */ + private static String mSyncProgress = ""; + + /** + * 启动同步操作 + */ + private void startSync() { + if (mSyncTask == null) { + mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { + public void onComplete() { + mSyncTask = null; + sendBroadcast(""); + stopSelf(); + } + }); + sendBroadcast(""); + mSyncTask.execute(); + } + } + + /** + * 取消正在进行的同步操作 + */ + private void cancelSync() { + if (mSyncTask != null) { + mSyncTask.cancelSync(); + } + } + + @Override + public void onCreate() { + mSyncTask = null; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + Bundle bundle = intent.getExtras(); + if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { + switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { + case ACTION_START_SYNC: + startSync(); + break; + case ACTION_CANCEL_SYNC: + cancelSync(); + break; + default: + break; + } + return START_STICKY; + } + return super.onStartCommand(intent, flags, startId); + } + + @Override + public void onLowMemory() { + if (mSyncTask != null) { + mSyncTask.cancelSync(); + } + } + + @Override + public IBinder onBind(Intent intent) { + return null; + } + + /** + * 发送同步状态广播 + * @param msg 同步进度消息 + */ + public void sendBroadcast(String msg) { + mSyncProgress = msg; + Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); + intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); + intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); + sendBroadcast(intent); + } + + /** + * 启动GTask同步服务 + * @param activity 调用该方法的Activity实例 + */ + public static void startSync(Activity activity) { + GTaskManager.getInstance().setActivityContext(activity); + Intent intent = new Intent(activity, GTaskSyncService.class); + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); + activity.startService(intent); + } + + /** + * 取消GTask同步服务 + * @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 如果正在同步返回true,否则返回false + */ + public static boolean isSyncing() { + return mSyncTask != null; + } + + /** + * 获取当前同步进度信息 + * @return 当前同步进度字符串 + */ + public static String getProgressString() { + return mSyncProgress; + } +} diff --git a/src/main/java/net/micode/notes/model/Note.java b/src/main/java/net/micode/notes/model/Note.java new file mode 100644 index 0000000..44935dd --- /dev/null +++ b/src/main/java/net/micode/notes/model/Note.java @@ -0,0 +1,430 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.model; +import android.content.ContentProviderOperation; +import android.content.ContentProviderResult; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.content.OperationApplicationException; +import android.net.Uri; +import android.os.RemoteException; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.Notes.TextNote; + +import java.util.ArrayList; + + +/** + * 笔记核心数据模型类,负责笔记的创建、更新和同步操作。 + *+ * 该类是笔记应用的核心数据模型,提供了笔记的创建、更新和同步功能, + * 支持文本笔记和通话笔记两种类型,并通过ContentResolver与数据库进行交互。 + *
+ */ +public class Note { + /** + * 用于存储笔记基本属性的变更值 + */ + private ContentValues mNoteDiffValues; + + /** + * 用于存储笔记具体数据(文本或通话数据) + */ + private NoteData mNoteData; + + /** + * 日志标签 + */ + private static final String TAG = Note.class.getSimpleName(); + /** + * 创建新笔记并返回其ID + *+ * 在数据库中创建一个新的笔记记录,并返回生成的笔记ID。 + * 新笔记将包含默认的创建时间、修改时间、类型等信息。 + *
+ * + * @param context 应用上下文,用于获取ContentResolver + * @param folderId 笔记所属文件夹ID + * @return 新创建的笔记ID + */ + 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.PARENT_ID, folderId); + Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); + + long noteId = 0; + try { + noteId = Long.valueOf(uri.getPathSegments().get(1)); + } catch (NumberFormatException e) { + Log.e(TAG, "Get note id error :" + e.toString()); + noteId = 0; + } + if (noteId == -1) { + throw new IllegalStateException("Wrong note id:" + noteId); + } + return noteId; + } + + /** + * 构造方法,初始化笔记数据模型 + */ + public Note() { + mNoteDiffValues = new ContentValues(); + mNoteData = new NoteData(); + } + + /** + * 设置笔记的基本属性值 + *+ * 更新笔记的基本属性,并标记为本地修改状态,同时更新修改时间。 + *
+ * + * @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()); + } + + /** + * 设置笔记文本数据 + *+ * 更新笔记的文本内容数据,并标记为本地修改状态。 + *
+ * + * @param key 文本数据键名,对应TextNote中的字段名 + * @param value 文本数据值 + */ + public void setTextData(String key, String value) { + mNoteData.setTextData(key, value); + } + + /** + * 设置文本数据ID + *+ * 设置与当前笔记关联的文本数据记录ID。 + *
+ * + * @param id 文本数据ID + */ + public void setTextDataId(long id) { + mNoteData.setTextDataId(id); + } + + /** + * 获取文本数据ID + *+ * 获取与当前笔记关联的文本数据记录ID。 + *
+ * + * @return 文本数据ID + */ + public long getTextDataId() { + return mNoteData.mTextDataId; + } + + /** + * 设置通话数据ID + *+ * 设置与当前笔记关联的通话数据记录ID。 + *
+ * + * @param id 通话数据ID + */ + public void setCallDataId(long id) { + mNoteData.setCallDataId(id); + } + + /** + * 设置通话数据 + *+ * 更新笔记的通话内容数据,并标记为本地修改状态。 + *
+ * + * @param key 通话数据键名,对应CallNote中的字段名 + * @param value 通话数据值 + */ + public void setCallData(String key, String value) { + mNoteData.setCallData(key, value); + } + + /** + * 检查笔记是否在本地被修改 + *+ * 检查笔记的基本属性或具体数据是否在本地被修改过。 + *
+ * + * @return 如果有本地修改则返回true,否则返回false + */ + public boolean isLocalModified() { + return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); + } + + /** + * 执行笔记同步操作,将本地修改提交到数据库 + *+ * 将本地对笔记的修改同步到数据库中,包括基本属性和具体数据的更新。 + * 如果同步失败,会记录错误日志但仍尝试完成数据更新。 + *
+ * + * @param context 应用上下文,用于获取ContentResolver + * @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; + } + + /** + * 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 + */ + if (context.getContentResolver().update( + 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(); + + if (mNoteData.isLocalModified() + && (mNoteData.pushIntoContentResolver(context, noteId) == null)) { + return false; + } + + return true; + } + + /** + * 笔记数据内部类,负责管理笔记的文本和通话数据。 + *+ * 该内部类封装了笔记的具体内容数据,包括文本笔记和通话笔记, + * 并提供了数据的设置和持久化方法。 + *
+ */ + private class NoteData { + /** + * 文本数据ID + */ + private long mTextDataId; + + /** + * 文本数据内容 + */ + private ContentValues mTextDataValues; + + /** + * 通话数据ID + */ + private long mCallDataId; + + /** + * 通话数据内容 + */ + private ContentValues mCallDataValues; + + /** + * 日志标签 + */ + private static final String TAG = "NoteData"; + + /** + * 构造方法,初始化笔记数据 + */ + public NoteData() { + mTextDataValues = new ContentValues(); + mCallDataValues = new ContentValues(); + mTextDataId = 0; + mCallDataId = 0; + } + + /** + * 检查笔记数据是否在本地被修改 + *+ * 检查文本数据或通话数据是否在本地被修改过。 + *
+ * + * @return 如果有本地修改则返回true,否则返回false + */ + boolean isLocalModified() { + return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; + } + + /** + * 设置文本数据ID + *+ * 设置与当前笔记关联的文本数据记录ID。 + *
+ * + * @param id 文本数据ID + */ + void setTextDataId(long id) { + if(id <= 0) { + throw new IllegalArgumentException("Text data id should larger than 0"); + } + mTextDataId = id; + } + + /** + * 设置通话数据ID + *+ * 设置与当前笔记关联的通话数据记录ID。 + *
+ * + * @param id 通话数据ID + */ + void setCallDataId(long id) { + if (id <= 0) { + throw new IllegalArgumentException("Call data id should larger than 0"); + } + mCallDataId = id; + } + + /** + * 设置通话数据 + *+ * 更新笔记的通话内容数据,并标记为本地修改状态。 + *
+ * + * @param key 通话数据键名,对应CallNote中的字段名 + * @param value 通话数据值 + */ + void setCallData(String key, String value) { + mCallDataValues.put(key, value); + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + } + + /** + * 设置文本数据 + *+ * 更新笔记的文本内容数据,并标记为本地修改状态。 + *
+ * + * @param key 文本数据键名,对应TextNote中的字段名 + * @param value 文本数据值 + */ + void setTextData(String key, String value) { + mTextDataValues.put(key, value); + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + } + + /** + * 将笔记数据推送到ContentResolver进行持久化 + *+ * 将本地修改的文本数据或通话数据持久化到数据库中。 + * 如果数据ID为0,则执行插入操作;否则执行更新操作。 + *
+ * + * @param context 应用上下文,用于获取ContentResolver + * @param noteId 笔记ID + * @return 成功返回笔记URI,失败返回null + */ + Uri pushIntoContentResolver(Context context, long noteId) { + /** + * Check for safety + */ + if (noteId <= 0) { + throw new IllegalArgumentException("Wrong note id:" + noteId); + } + + ArrayList+ * 该类是笔记应用的业务逻辑封装类,提供了笔记的创建、加载、保存等功能, + * 负责管理笔记的UI状态和业务逻辑,是UI层与数据层之间的桥梁。 + *
+ */ +public class WorkingNote { + /** + * 内部笔记数据对象 + */ + private Note mNote; + + /** + * 笔记ID + */ + private long mNoteId; + + /** + * 笔记内容 + */ + private String mContent; + + /** + * 笔记模式(普通模式或清单模式) + */ + 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.class.getSimpleName(); + + /** + * 删除标记 + */ + private boolean mIsDeleted; + + /** + * 笔记设置变更监听器 + */ + private NoteSettingChangedListener mNoteSettingStatusListener; + + /** + * 数据查询投影,用于从ContentResolver获取笔记数据 + */ + public static final String[] DATA_PROJECTION = new String[] { + DataColumns.ID, + DataColumns.CONTENT, + DataColumns.MIME_TYPE, + DataColumns.DATA1, + DataColumns.DATA2, + DataColumns.DATA3, + DataColumns.DATA4, + }; + + /** + * 笔记查询投影,用于从ContentResolver获取笔记基本信息 + */ + public static final String[] NOTE_PROJECTION = new String[] { + NoteColumns.PARENT_ID, + NoteColumns.ALERTED_DATE, + NoteColumns.BG_COLOR_ID, + NoteColumns.WIDGET_ID, + NoteColumns.WIDGET_TYPE, + NoteColumns.MODIFIED_DATE + }; + + /** + * 数据查询结果列索引:数据ID + */ + 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; + + /** + * 笔记查询结果列索引:父文件夹ID + */ + private static final int NOTE_PARENT_ID_COLUMN = 0; + + /** + * 笔记查询结果列索引:提醒日期 + */ + private static final int NOTE_ALERTED_DATE_COLUMN = 1; + + /** + * 笔记查询结果列索引:背景颜色ID + */ + private static final int NOTE_BG_COLOR_ID_COLUMN = 2; + + /** + * 笔记查询结果列索引:小部件ID + */ + 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; + mModifiedDate = System.currentTimeMillis(); + mFolderId = folderId; + mNote = new Note(); + mNoteId = 0; + mIsDeleted = false; + mMode = 0; + mWidgetType = Notes.TYPE_WIDGET_INVALIDE; + } + + // Existing note construct + /** + * 构造现有笔记的私有构造方法 + *+ * 根据笔记ID初始化一个工作笔记对象,并从数据库加载笔记数据。 + *
+ * + * @param context 应用上下文 + * @param noteId 笔记ID + * @param folderId 笔记所属文件夹ID + */ + private WorkingNote(Context context, long noteId, long folderId) { + mContext = context; + mNoteId = noteId; + mFolderId = folderId; + mIsDeleted = false; + mNote = new Note(); + loadNote(); + } + + /** + * 从数据库加载笔记基本信息 + *+ * 从ContentResolver中查询并加载笔记的基本信息,包括文件夹ID、背景颜色、 + * 小部件信息、提醒日期和修改日期等。 + *
+ */ + private void loadNote() { + Cursor cursor = mContext.getContentResolver().query( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, + null, null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); + mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); + mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); + mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN); + mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN); + mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); + } + cursor.close(); + } else { + Log.e(TAG, "No note with id:" + mNoteId); + throw new IllegalArgumentException("Unable to find note with id " + mNoteId); + } + loadNoteData(); + } + + /** + * 从数据库加载笔记详细数据 + *+ * 从ContentResolver中查询并加载笔记的详细数据,包括文本内容和模式等。 + *
+ */ + private void loadNoteData() { + Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, + DataColumns.NOTE_ID + "=?", new String[] { + String.valueOf(mNoteId) + }, null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + do { + String type = cursor.getString(DATA_MIME_TYPE_COLUMN); + if (DataConstants.NOTE.equals(type)) { + mContent = cursor.getString(DATA_CONTENT_COLUMN); + mMode = cursor.getInt(DATA_MODE_COLUMN); + mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); + } else if (DataConstants.CALL_NOTE.equals(type)) { + mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); + } else { + Log.d(TAG, "Wrong note type with type:" + type); + } + } while (cursor.moveToNext()); + } + cursor.close(); + } else { + Log.e(TAG, "No data with id:" + mNoteId); + throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); + } + } + + /** + * 创建空笔记的静态工厂方法 + *+ * 创建一个新的空工作笔记对象,并设置默认属性值。 + *
+ * + * @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) { + WorkingNote note = new WorkingNote(context, folderId); + note.setBgColorId(defaultBgColorId); + note.setWidgetId(widgetId); + note.setWidgetType(widgetType); + return note; + } + + /** + * 加载现有笔记的静态工厂方法 + *+ * 根据笔记ID加载一个现有的工作笔记对象。 + *
+ * + * @param context 应用上下文 + * @param id 笔记ID + * @return 加载的工作笔记 + */ + public static WorkingNote load(Context context, long id) { + return new WorkingNote(context, id, 0); + } + + /** + * 保存笔记到数据库 + *+ * 将当前工作笔记保存到数据库中。如果笔记不存在,则创建新笔记; + * 如果笔记已存在,则更新现有笔记。 + * 如果笔记内容为空且已存在于数据库,则将其移动到回收站。 + *
+ * + * @return 保存成功返回true,否则返回false + */ + public synchronized boolean saveNote() { + if (isWorthSaving()) { + if (!existInDatabase()) { + if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { + Log.e(TAG, "Create new note fail with id:" + mNoteId); + return false; + } + } + + 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 + && mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onWidgetChanged(); + } + return true; + } else { + // 添加删除逻辑:如果笔记内容为空且已存在于数据库,则将其移动到回收站 + if (existInDatabase() && TextUtils.isEmpty(mContent)) { + HashSet+ * 检查当前工作笔记是否已存在于数据库中。 + *
+ * + * @return 存在返回true,否则返回false + */ + public boolean existInDatabase() { + return mNoteId > 0; + } + + /** + * 检查笔记是否值得保存 + *+ * 检查当前工作笔记是否值得保存到数据库中。如果笔记已删除、 + * 内容为空,或者存在于数据库但未修改,则不值得保存。 + *
+ * + * @return 值得保存返回true,否则返回false + */ + private boolean isWorthSaving() { + if (mIsDeleted || TextUtils.isEmpty(mContent) + || (existInDatabase() && !mNote.isLocalModified())) { + return false; + } else { + return true; + } + } + + /** + * 设置笔记设置变更监听器 + *+ * 设置笔记设置变更监听器,用于监听笔记设置的变化,如背景颜色、 + * 提醒日期、小部件等的变化。 + *
+ * + * @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; + mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); + } + if (mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onClockAlertChanged(date, set); + } + } + + /** + * 标记笔记是否删除 + *+ * 标记笔记是否已删除,并通知监听器。 + *
+ * + * @param mark 删除标记 + */ + public void markDeleted(boolean mark) { + mIsDeleted = mark; + if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onWidgetChanged(); + } + } + + /** + * 设置笔记背景颜色ID + *+ * 设置笔记的背景颜色ID,并通知监听器。 + *
+ * + * @param id 背景颜色ID + */ + public void setBgColorId(int id) { + if (id != mBgColorId) { + mBgColorId = id; + if (mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onBackgroundColorChanged(); + } + mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); + } + } + + /** + * 设置笔记的清单模式 + *+ * 设置笔记的模式(普通模式或清单模式),并通知监听器。 + *
+ * + * @param mode 清单模式 + */ + public void setCheckListMode(int mode) { + if (mMode != mode) { + if (mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); + } + mMode = mode; + mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); + } + } + + /** + * 设置小部件类型 + *+ * 设置与当前笔记关联的小部件类型。 + *
+ * + * @param type 小部件类型 + */ + public void setWidgetType(int type) { + if (type != mWidgetType) { + mWidgetType = type; + mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); + } + } + + /** + * 设置小部件ID + *+ * 设置与当前笔记关联的小部件ID。 + *
+ * + * @param id 小部件ID + */ + public void setWidgetId(int id) { + if (id != mWidgetId) { + mWidgetId = id; + mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); + } + } + + /** + * 设置笔记的基本属性值 + *+ * 直接调用内部Note对象的setNoteValue方法,用于更新笔记的基本属性。 + *
+ * + * @param key 属性键名,对应NoteColumns中的字段名 + * @param value 属性值 + */ + public void setNoteValue(String key, String value) { + mNote.setNoteValue(key, value); + } + + /** + * 设置笔记内容 + *+ * 设置笔记的文本内容,支持富文本格式。 + *
+ * + * @param text 笔记内容,支持Spannable等富文本格式 + */ + public void setWorkingText(CharSequence text) { + String textStr = text.toString(); + if (!TextUtils.equals(mContent, textStr)) { + mContent = textStr; + mNote.setTextData(DataColumns.CONTENT, mContent); + } + } + + /** + * 设置笔记内容(字符串重载) + *+ * 设置笔记的文本内容。 + *
+ * + * @param text 笔记内容 + */ + public void setWorkingText(String text) { + setWorkingText((CharSequence) text); + } + + /** + * 将笔记转换为通话笔记 + *+ * 将当前笔记转换为通话笔记,并设置通话相关信息,如电话号码和通话日期。 + *
+ * + * @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 有提醒返回true,否则返回false + */ + 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 + *+ * 根据背景颜色ID获取对应的背景颜色资源ID。 + *
+ * + * @return 背景颜色资源ID + */ + public int getBgColorResId() { + return NoteBgResources.getNoteBgResource(mBgColorId); + } + + /** + * 获取背景颜色ID + *+ * 获取当前笔记的背景颜色ID。 + *
+ * + * @return 背景颜色ID + */ + public int getBgColorId() { + return mBgColorId; + } + + /** + * 获取标题背景资源ID + *+ * 根据背景颜色ID获取对应的标题背景资源ID。 + *
+ * + * @return 标题背景资源ID + */ + public int getTitleBgResId() { + return NoteBgResources.getNoteTitleBgResource(mBgColorId); + } + + /** + * 获取清单模式 + *+ * 获取当前笔记的模式(普通模式或清单模式)。 + *
+ * + * @return 清单模式 + */ + public int getCheckListMode() { + return mMode; + } + + /** + * 获取笔记ID + *+ * 获取当前笔记的ID。 + *
+ * + * @return 笔记ID + */ + public long getNoteId() { + return mNoteId; + } + + /** + * 获取文件夹ID + *+ * 获取当前笔记所属的文件夹ID。 + *
+ * + * @return 文件夹ID + */ + public long getFolderId() { + return mFolderId; + } + + /** + * 获取小部件ID + *+ * 获取与当前笔记关联的小部件ID。 + *
+ * + * @return 小部件ID + */ + public int getWidgetId() { + return mWidgetId; + } + + /** + * 获取小部件类型 + *+ * 获取与当前笔记关联的小部件类型。 + *
+ * + * @return 小部件类型 + */ + public int getWidgetType() { + return mWidgetType; + } + + /** + * 笔记设置变更监听器,用于监听笔记设置的变化。 + *+ * 该接口定义了笔记设置变化的回调方法,如背景颜色、提醒日期、 + * 小部件等的变化回调。 + *
+ */ + public interface NoteSettingChangedListener { + /** + * 当笔记背景颜色改变时调用 + *+ * 当笔记的背景颜色发生变化时,会调用该方法。 + *
+ */ + void onBackgroundColorChanged(); + + /** + * 当笔记闹钟设置改变时调用 + *+ * 当笔记的提醒日期发生变化时,会调用该方法。 + *
+ * + * @param date 闹钟日期时间戳 + * @param set 是否设置闹钟 + */ + void onClockAlertChanged(long date, boolean set); + + /** + * 当笔记小部件改变时调用 + *+ * 当与笔记关联的小部件发生变化时,会调用该方法。 + *
+ */ + void onWidgetChanged(); + + /** + * 当笔记在清单模式和普通模式之间切换时调用 + *+ * 当笔记的模式在普通模式和清单模式之间切换时,会调用该方法。 + *
+ * + * @param oldMode 切换前的模式 + * @param newMode 切换后的新模式 + */ + void onCheckListModeChanged(int oldMode, int newMode); + } +} diff --git a/src/main/java/net/micode/notes/tool/BackupUtils.java b/src/main/java/net/micode/notes/tool/BackupUtils.java new file mode 100644 index 0000000..8f2e96e --- /dev/null +++ b/src/main/java/net/micode/notes/tool/BackupUtils.java @@ -0,0 +1,490 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.tool; + +import android.content.Context; +import android.database.Cursor; +import android.os.Environment; +import android.text.TextUtils; +import android.text.format.DateFormat; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; + + +/** + * 备份工具类,负责将笔记导出为文本文件。 + *+ * 该类采用单例模式实现,提供了将笔记内容导出为用户可读文本格式的功能, + * 支持将不同文件夹的笔记分类导出,并处理SD卡状态检查和文件生成等操作。 + *
+ */ +public class BackupUtils { + /** + * 日志标签 + */ + private static final String TAG = BackupUtils.class.getSimpleName(); + /** + * 单例实例 + */ + private static BackupUtils sInstance; + + /** + * 获取BackupUtils的单例实例 + *+ * 如果实例不存在,则创建一个新实例并返回;否则返回已存在的实例。 + *
+ * + * @param context 应用上下文 + * @return BackupUtils的单例实例 + */ + public static synchronized BackupUtils getInstance(Context context) { + if (sInstance == null) { + sInstance = new BackupUtils(context); + } + return sInstance; + } + + /** + * 备份或恢复操作的状态常量 + *+ * 这些状态常量用于表示备份或恢复操作的执行结果和状态。 + *
+ */ + /** + * SD卡未挂载状态 + */ + public static final int STATE_SD_CARD_UNMOUONTED = 0; + + /** + * 备份文件不存在状态 + */ + public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; + + /** + * 数据格式损坏状态,可能被其他程序修改 + */ + public static final int STATE_DATA_DESTROIED = 2; + + /** + * 运行时异常导致备份或恢复失败状态 + */ + public static final int STATE_SYSTEM_ERROR = 3; + + /** + * 备份或恢复成功状态 + */ + public static final int STATE_SUCCESS = 4; + + /** + * 文本导出实例,负责实际的文本导出操作 + */ + private TextExport mTextExport; + + /** + * 私有构造方法,初始化BackupUtils实例 + *+ * 创建TextExport实例用于文本导出操作。 + *
+ * + * @param context 应用上下文 + */ + private BackupUtils(Context context) { + mTextExport = new TextExport(context); + } + + /** + * 检查外部存储是否可用 + *+ * 判断SD卡是否已挂载并可读写。 + *
+ * + * @return 如果外部存储可用返回true,否则返回false + */ + private static boolean externalStorageAvailable() { + return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); + } + + /** + * 将笔记导出为文本文件 + *+ * 调用内部TextExport实例的exportToText方法执行实际导出操作。 + *
+ * + * @return 导出操作的状态码,可能的值为STATE_SD_CARD_UNMOUONTED、STATE_SYSTEM_ERROR或STATE_SUCCESS + */ + 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 + }; + + 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, + }; + + 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 Context mContext; + /** + * 导出的文件名 + */ + private String mFileName; + /** + * 导出的文件目录 + */ + private String mFileDirectory; + + /** + * 构造方法,初始化TextExport实例 + *+ * 从资源文件中加载文本格式化字符串,并初始化上下文和文件信息。 + *
+ * + * @param context 应用上下文 + */ + public TextExport(Context context) { + TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); + mContext = context; + mFileName = ""; + mFileDirectory = ""; + } + + /** + * 获取指定ID的文本格式化字符串 + *+ * 从TEXT_FORMAT数组中获取指定索引的格式化字符串。 + *
+ * + * @param id 格式化字符串的索引 + * @return 对应的格式化字符串 + */ + private String getFormat(int id) { + return TEXT_FORMAT[id]; + } + + /** + * 将指定文件夹的笔记导出为文本 + *+ * 查询并导出指定文件夹下的所有笔记,包括每个笔记的修改日期和内容。 + *
+ * + * @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 + }, 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()); + } + notesCursor.close(); + } + } + + /** + * 将指定笔记导出到打印流 + *+ * 查询并导出指定笔记的详细内容,区分文本笔记和通话笔记的不同格式。 + *
+ * + * @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 + }, null); + + if (dataCursor != null) { + if (dataCursor.moveToFirst()) { + 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), + content)); + } + } + } while (dataCursor.moveToNext()); + } + dataCursor.close(); + } + // print a line separator between note + try { + ps.write(new byte[] { + Character.LINE_SEPARATOR, Character.LETTER_NUMBER + }); + } catch (IOException e) { + Log.e(TAG, e.toString()); + } + } + + /** + * 将笔记导出为用户可读的文本格式 + *+ * 检查SD卡状态,创建输出文件,然后按文件夹分类导出所有笔记内容。 + *
+ * + * @return 导出操作的状态码,可能的值为STATE_SD_CARD_UNMOUONTED、STATE_SYSTEM_ERROR或STATE_SUCCESS + */ + public int exportToText() { + 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, + "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " + + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " + + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null); + + 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); + } else { + folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); + } + 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()); + } + folderCursor.close(); + } + + // Export notes in root's folder + Cursor noteCursor = mContext.getContentResolver().query( + Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, + NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + + "=0", null, null); + + 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()); + } + noteCursor.close(); + } + ps.close(); + + return STATE_SUCCESS; + } + + /** + * 获取用于导出文本的打印流 + *+ * 创建并返回指向导出文本文件的打印流,用于写入导出的笔记内容。 + *
+ * + * @return 指向导出文本文件的打印流,如果创建失败返回null + */ + private PrintStream getExportToTextPrintStream() { + File file = generateFileMountedOnSDcard(mContext, R.string.file_path, + R.string.file_name_txt_format); + if (file == null) { + Log.e(TAG, "create file to exported failed"); + return null; + } + mFileName = file.getName(); + mFileDirectory = mContext.getString(R.string.file_path); + PrintStream ps = null; + try { + FileOutputStream fos = new FileOutputStream(file); + ps = new PrintStream(fos); + } catch (FileNotFoundException e) { + e.printStackTrace(); + return null; + } catch (NullPointerException e) { + e.printStackTrace(); + return null; + } + return ps; + } + } + + /** + * 在SD卡上生成用于存储导入数据的文本文件 + *+ * 根据指定的文件路径和文件名格式,在SD卡上创建相应的目录和文件。 + *
+ * + * @param context 应用上下文 + * @param filePathResId 文件路径资源ID + * @param fileNameFormatResId 文件名格式资源ID + * @return 创建的文件对象,如果创建失败返回null + */ + 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), + System.currentTimeMillis()))); + File file = new File(sb.toString()); + + try { + if (!filedir.exists()) { + filedir.mkdir(); + } + if (!file.exists()) { + file.createNewFile(); + } + return file; + } catch (SecurityException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return null; + } +} + + diff --git a/src/main/java/net/micode/notes/tool/DataUtils.java b/src/main/java/net/micode/notes/tool/DataUtils.java new file mode 100644 index 0000000..6d84777 --- /dev/null +++ b/src/main/java/net/micode/notes/tool/DataUtils.java @@ -0,0 +1,453 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.tool; + +import android.content.ContentProviderOperation; +import android.content.ContentProviderResult; +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.OperationApplicationException; +import android.database.Cursor; +import android.os.RemoteException; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; + +import java.util.ArrayList; +import java.util.HashSet; + + +/** + * 数据工具类,提供笔记数据的批量操作和查询功能。 + *+ * 该类包含了笔记数据的批量删除、移动、查询等静态方法, + * 主要用于处理笔记应用中的数据操作,与ContentResolver进行交互。 + *
+ */ +public class DataUtils { + /** + * 日志标签 + */ + public static final String TAG = DataUtils.class.getSimpleName(); + /** + * 批量删除笔记 + *+ * 根据提供的笔记ID集合,批量删除对应的笔记。 + * 系统根文件夹(ID_ROOT_FOLDER)不会被删除。 + *
+ * + * @param resolver ContentResolver实例,用于与内容提供者交互 + * @param ids 要删除的笔记ID集合 + * @return 删除成功返回true,否则返回false + */ + public static boolean batchDeleteNotes(ContentResolver resolver, HashSet+ * 更新笔记的父文件夹ID和原始父文件夹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); + resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); + } + + /** + * 批量将笔记移动到指定文件夹 + *+ * 根据提供的笔记ID集合,批量更新笔记的父文件夹ID。 + *
+ * + * @param resolver ContentResolver实例,用于与内容提供者交互 + * @param ids 要移动的笔记ID集合 + * @param folderId 目标文件夹ID + * @return 移动成功返回true,否则返回false + */ + public static boolean batchMoveToFolder(ContentResolver resolver, HashSet+ * 查询并返回除系统文件夹外的所有用户文件夹数量。 + *
+ * + * @param resolver ContentResolver实例,用于与内容提供者交互 + * @return 用户文件夹数量 + */ + public static int getUserFolderCount(ContentResolver resolver) { + 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)}, + null); + + int count = 0; + if(cursor != null) { + if(cursor.moveToFirst()) { + try { + count = cursor.getInt(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "get folder count failed:" + e.toString()); + } finally { + cursor.close(); + } + } + } + return count; + } + + /** + * 检查笔记在数据库中是否可见 + *+ * 检查指定ID和类型的笔记是否存在于数据库中,且不在垃圾箱中。 + *
+ * + * @param resolver ContentResolver实例,用于与内容提供者交互 + * @param noteId 笔记ID + * @param type 笔记类型 + * @return 可见返回true,否则返回false + */ + 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)}, + null); + + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + } + cursor.close(); + } + return exist; + } + + /** + * 检查笔记是否存在于数据库中 + *+ * 根据笔记ID检查笔记是否存在于数据库中。 + *
+ * + * @param resolver ContentResolver实例,用于与内容提供者交互 + * @param noteId 笔记ID + * @return 存在返回true,否则返回false + */ + public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + null, null, null, null); + + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + } + cursor.close(); + } + return exist; + } + + /** + * 检查数据是否存在于数据库中 + *+ * 根据数据ID检查数据是否存在于数据库中。 + *
+ * + * @param resolver ContentResolver实例,用于与内容提供者交互 + * @param dataId 数据ID + * @return 存在返回true,否则返回false + */ + public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), + null, null, null, null); + + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + } + cursor.close(); + } + return exist; + } + + /** + * 检查可见文件夹名称是否存在 + *+ * 检查指定名称的文件夹是否存在于数据库中,且不在垃圾箱中。 + *
+ * + * @param resolver ContentResolver实例,用于与内容提供者交互 + * @param name 文件夹名称 + * @return 存在返回true,否则返回false + */ + public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { + return checkVisibleFolderName(resolver, name, Notes.ID_ROOT_FOLDER); + } + + /** + * 检查可见文件夹名称是否存在(重载方法,支持指定父文件夹ID) + *+ * 检查指定名称的文件夹是否存在于指定父文件夹下,且不在垃圾箱中。 + *
+ * + * @param resolver ContentResolver实例,用于与内容提供者交互 + * @param name 文件夹名称 + * @param parentId 父文件夹ID + * @return 存在返回true,否则返回false + */ + public static boolean checkVisibleFolderName(ContentResolver resolver, String name, long parentId) { + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.PARENT_ID + "=?" + + " AND " + NoteColumns.SNIPPET + "=?", + new String[] { String.valueOf(parentId), name }, null); + boolean exist = false; + if(cursor != null) { + if(cursor.getCount() > 0) { + exist = true; + } + cursor.close(); + } + return exist; + } + + /** + * 获取文件夹中笔记的小部件属性 + *+ * 查询并返回指定文件夹下所有笔记的小部件ID和类型。 + *
+ * + * @param resolver ContentResolver实例,用于与内容提供者交互 + * @param folderId 文件夹ID + * @return 小部件属性集合,如果没有则返回null + */ + public static HashSet+ * 查询并返回通话笔记中存储的电话号码。 + *
+ * + * @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 }, + CallNote.NOTE_ID + "=? AND " + CallNote.MIME_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()); + } finally { + cursor.close(); + } + } + return ""; + } + + /** + * 根据电话号码和通话日期获取笔记ID + *+ * 查询并返回匹配指定电话号码和通话日期的通话笔记ID。 + *
+ * + * @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 }, + CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" + + CallNote.PHONE_NUMBER + ",?)", + new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, + null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + try { + return cursor.getLong(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "Get call note id fails " + e.toString()); + } + } + cursor.close(); + } + return 0; + } + + /** + * 根据笔记ID获取摘要 + *+ * 查询并返回指定笔记ID的摘要内容。 + * 如果笔记不存在,将抛出IllegalArgumentException异常。 + *
+ * + * @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 }, + NoteColumns.ID + "=?", + new String [] { String.valueOf(noteId)}, + null); + + if (cursor != null) { + String snippet = ""; + if (cursor.moveToFirst()) { + snippet = cursor.getString(0); + } + cursor.close(); + return snippet; + } + throw new IllegalArgumentException("Note is not found with id: " + noteId); + } + + /** + * 格式化笔记摘要 + *+ * 对笔记摘要进行格式化处理,去除首尾空格,并只保留第一行内容。 + *
+ * + * @param snippet 原始摘要内容 + * @return 格式化后的摘要内容 + */ + public static String getFormattedSnippet(String snippet) { + if (snippet != null) { + snippet = snippet.trim(); + int index = snippet.indexOf('\n'); + if (index != -1) { + snippet = snippet.substring(0, index); + } + } + return snippet; + } +} diff --git a/src/main/java/net/micode/notes/tool/GTaskStringUtils.java b/src/main/java/net/micode/notes/tool/GTaskStringUtils.java new file mode 100644 index 0000000..e9e7aab --- /dev/null +++ b/src/main/java/net/micode/notes/tool/GTaskStringUtils.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.tool; + +/** + * GTask字符串常量工具类,定义了与GTask服务交互时使用的各种JSON字段名和文件夹名称。 + *+ * 该类包含了与Google任务服务(GTask)进行JSON数据交换时所需的所有字符串常量, + * 包括动作类型、实体类型、字段名称以及文件夹命名规则等。 + *
+ */ +public class GTaskStringUtils { + + /** 动作ID字段名 */ + 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"; + + /** 创建者ID字段名 */ + 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"; + + /** 当前列表ID字段名 */ + 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"; + + /** 删除状态字段名 */ + 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"; + + /** ID字段名 */ + 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"; + + /** 列表ID字段名 */ + 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"; + + /** 新ID字段名 */ + public final static String GTASK_JSON_NEW_ID = "new_id"; + + /** 笔记字段名 */ + public final static String GTASK_JSON_NOTES = "notes"; + + /** 父级ID字段名 */ + public final static String GTASK_JSON_PARENT_ID = "parent_id"; + + /** 前一个兄弟节点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"; + + /** MIUI笔记文件夹前缀 */ + 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"; + + /** GTask ID元数据头 */ + 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"; + +} diff --git a/src/main/java/net/micode/notes/tool/ResourceParser.java b/src/main/java/net/micode/notes/tool/ResourceParser.java new file mode 100644 index 0000000..1c3c73a --- /dev/null +++ b/src/main/java/net/micode/notes/tool/ResourceParser.java @@ -0,0 +1,296 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.tool; + +import android.content.Context; +import android.preference.PreferenceManager; + +import net.micode.notes.R; +import net.micode.notes.ui.NotesPreferenceActivity; + +/** + * 资源解析工具类,管理笔记应用中使用的各种资源配置和常量。 + *+ * 该类包含了笔记的背景颜色、字体大小等常量定义,以及管理笔记背景、 + * 列表项背景、小部件背景和文本外观等资源的内部类。 + *
+ */ +public class ResourceParser { + + /** 黄色背景ID */ + public static final int YELLOW = 0; + /** 蓝色背景ID */ + public static final int BLUE = 1; + /** 白色背景ID */ + public static final int WHITE = 2; + /** 绿色背景ID */ + public static final int GREEN = 3; + /** 红色背景ID */ + public static final int RED = 4; + + /** 默认背景颜色ID */ + public static final int BG_DEFAULT_COLOR = YELLOW; + + /** 小字体大小ID */ + public static final int TEXT_SMALL = 0; + /** 中字体大小ID */ + public static final int TEXT_MEDIUM = 1; + /** 大字体大小ID */ + public static final int TEXT_LARGE = 2; + /** 超大字体大小ID */ + public static final int TEXT_SUPER = 3; + + /** 默认字体大小ID */ + 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_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 背景颜色ID + * @return 对应的背景资源ID + */ + public static int getNoteBgResource(int id) { + return BG_EDIT_RESOURCES[id]; + } + + /** + * 获取笔记标题背景资源ID + * + * @param id 背景颜色ID + * @return 对应的标题背景资源ID + */ + public static int getNoteTitleBgResource(int id) { + return BG_EDIT_TITLE_RESOURCES[id]; + } + } + + /** + * 获取默认的笔记背景颜色ID + *+ * 根据用户设置决定返回固定默认颜色还是随机颜色。 + *
+ * + * @param context 上下文对象 + * @return 默认的背景颜色ID + */ + 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_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_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 背景颜色ID + * @return 对应的第一项背景资源ID + */ + public static int getNoteBgFirstRes(int id) { + return BG_FIRST_RESOURCES[id]; + } + + /** + * 获取列表最后一项背景资源ID + * + * @param id 背景颜色ID + * @return 对应的最后一项背景资源ID + */ + public static int getNoteBgLastRes(int id) { + return BG_LAST_RESOURCES[id]; + } + + /** + * 获取列表单独项背景资源ID + * + * @param id 背景颜色ID + * @return 对应的单独项背景资源ID + */ + public static int getNoteBgSingleRes(int id) { + return BG_SINGLE_RESOURCES[id]; + } + + /** + * 获取列表中间项背景资源ID + * + * @param id 背景颜色ID + * @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 { + /** 2x尺寸小部件背景资源数组 */ + 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, + }; + + /** + * 获取2x尺寸小部件背景资源ID + * + * @param id 背景颜色ID + * @return 对应的2x尺寸小部件背景资源ID + */ + public static int getWidget2xBgResource(int id) { + return BG_2X_RESOURCES[id]; + } + + /** 4x尺寸小部件背景资源数组 */ + 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 + }; + + /** + * 获取4x尺寸小部件背景资源ID + * + * @param id 背景颜色ID + * @return 对应的4x尺寸小部件背景资源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 + }; + + /** + * 获取文本外观资源ID + *+ * 如果ID超出资源数组范围,返回默认字体大小的资源ID。 + *
+ * + * @param id 字体大小ID + * @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} + */ + if (id >= TEXTAPPEARANCE_RESOURCES.length) { + return BG_DEFAULT_FONT_SIZE; + } + return TEXTAPPEARANCE_RESOURCES[id]; + } + + /** + * 获取文本外观资源数组的大小 + * + * @return 文本外观资源数组的大小 + */ + public static int getResourcesSize() { + return TEXTAPPEARANCE_RESOURCES.length; + } + } +} diff --git a/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java b/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java new file mode 100644 index 0000000..fd4c758 --- /dev/null +++ b/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java @@ -0,0 +1,255 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.content.DialogInterface.OnDismissListener; +import android.content.Intent; +import android.media.AudioManager; +import android.media.MediaPlayer; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Bundle; +import android.os.PowerManager; +import android.provider.Settings; +import android.view.Window; +import android.view.WindowManager; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +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; + + /** + * 活动创建时的初始化方法 + *+ * 该方法完成以下初始化工作: + * 1. 设置窗口特性,隐藏标题栏 + * 2. 配置窗口标志,确保在锁屏状态下也能显示 + * 3. 如果屏幕未开启,则添加额外标志以唤醒屏幕并保持点亮 + * 4. 从Intent中获取笔记ID和摘要信息 + * 5. 创建MediaPlayer实例用于播放提醒铃声 + * 6. 检查笔记是否存在于数据库中 + * 7. 如果笔记存在,则显示提醒对话框并播放提醒铃声 + *
+ * @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 + | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON + | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); + } + + 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; + } catch (IllegalArgumentException e) { + e.printStackTrace(); + return; + } + + mPlayer = new MediaPlayer(); + if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { + showActionDialog(); + playAlarmSound(); + } else { + finish(); + } + } + + /** + * 检查屏幕是否处于开启状态 + *+ * 该方法通过PowerManager系统服务获取当前屏幕状态 + *
+ * @return 如果屏幕处于开启状态则返回true,否则返回false + */ + private boolean isScreenOn() { + PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); + return pm.isScreenOn(); + } + + /** + * 播放提醒铃声 + *+ * 该方法完成以下工作: + * 1. 获取系统默认的闹钟铃声URI + * 2. 检查系统的静音模式设置,确定应该使用的音频流类型 + * 3. 根据静音模式设置选择合适的音频流类型 + * 4. 设置MediaPlayer的数据源为获取到的铃声URI + * 5. 准备MediaPlayer并设置为循环播放模式 + * 6. 开始播放提醒铃声 + * 7. 处理可能出现的各种异常 + *
+ */ + private void playAlarmSound() { + 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(); + } + } + + /** + * 显示提醒对话框 + *+ * 该方法创建并显示一个提醒对话框,包含以下内容: + * 1. 设置对话框标题为应用名称 + * 2. 设置对话框消息为笔记的摘要内容 + * 3. 添加确定按钮,点击后关闭对话框 + * 4. 如果屏幕处于开启状态,添加进入按钮,点击后进入笔记编辑界面 + * 5. 设置对话框关闭监听器,用于在对话框关闭时停止提醒铃声并结束活动 + *
+ */ + 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); + } + + /** + * 处理提醒对话框中的按钮点击事件 + *+ * 该方法实现了OnClickListener接口,根据点击的按钮执行不同的操作: + * 1. 如果点击的是负按钮(进入按钮),则创建Intent跳转到NoteEditActivity + * 2. 设置Intent的Action为ACTION_VIEW,并将笔记ID作为额外数据传递 + * 3. 启动NoteEditActivity让用户查看或编辑对应的笔记 + * 4. 如果点击的是其他按钮(如确定按钮),则不执行任何额外操作 + *
+ * @param dialog 触发点击事件的对话框 + * @param which 点击的按钮ID,对应DialogInterface中的按钮常量 + */ + 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); + startActivity(intent); + break; + default: + break; + } + } + + /** + * 处理提醒对话框关闭事件 + *+ * 该方法实现了OnDismissListener接口,当提醒对话框被关闭时(无论点击了哪个按钮或通过其他方式关闭), + * 会停止提醒铃声并结束当前活动 + *
+ * @param dialog 被关闭的对话框 + */ + public void onDismiss(DialogInterface dialog) { + stopAlarmSound(); + finish(); + } + + /** + * 停止提醒铃声并释放媒体播放器资源 + *+ * 该方法完成以下工作: + * 1. 检查媒体播放器是否存在 + * 2. 如果存在,则停止播放铃声 + * 3. 释放媒体播放器占用的资源 + * 4. 将媒体播放器引用置为null,防止内存泄漏 + *
+ */ + private void stopAlarmSound() { + if (mPlayer != null) { + mPlayer.stop(); + mPlayer.release(); + mPlayer = null; + } + } +} diff --git a/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java b/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java new file mode 100644 index 0000000..4de50d9 --- /dev/null +++ b/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.ContentUris; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +/** + * 闹钟初始化广播接收器 + *+ * 该广播接收器负责在系统启动时重新注册所有未触发的笔记闹钟。 + * 当系统重启后,之前设置的闹钟会丢失,需要通过该接收器重新初始化 + *
+ */ +public class AlarmInitReceiver extends BroadcastReceiver { + /** + * 闹钟数据查询的投影列数组 + *+ * 定义了从数据库查询笔记闹钟数据时需要获取的列,包括笔记ID和闹钟触发日期 + *
+ */ + private static final String [] PROJECTION = new String [] { + NoteColumns.ID, + NoteColumns.ALERTED_DATE + }; + + /** + * 查询结果中笔记ID列的索引 + */ + private static final int COLUMN_ID = 0; + + /** + * 查询结果中闹钟触发日期列的索引 + */ + private static final int COLUMN_ALERTED_DATE = 1; + + /** + * 接收广播时调用的方法 + *+ * 当系统发送广播时(通常是系统启动完成),该方法会查询所有设置了未来闹钟的笔记, + * 并使用AlarmManager重新注册这些闹钟 + *
+ * @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); + + if (c != null) { + if (c.moveToFirst()) { + do { + long alertDate = c.getLong(COLUMN_ALERTED_DATE); + 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.getSystemService(Context.ALARM_SERVICE); + alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + } while (c.moveToNext()); + } + c.close(); + } + } +} diff --git a/src/main/java/net/micode/notes/ui/AlarmReceiver.java b/src/main/java/net/micode/notes/ui/AlarmReceiver.java new file mode 100644 index 0000000..610716c --- /dev/null +++ b/src/main/java/net/micode/notes/ui/AlarmReceiver.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +/** + * 闹钟触发广播接收器 + *+ * 该广播接收器负责处理闹钟触发事件,当闹钟时间到达时,它会启动闹钟提醒活动 + *
+ */ +public class AlarmReceiver extends BroadcastReceiver { + /** + * 接收闹钟触发广播时调用的方法 + *+ * 当闹钟时间到达时,该方法会启动AlarmAlertActivity来显示闹钟提醒 + *
+ * @param context 上下文对象 + * @param intent 接收到的广播意图,包含闹钟相关的笔记信息 + */ + @Override + public void onReceive(Context context, Intent intent) { + intent.setClass(context, AlarmAlertActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + } +} diff --git a/src/main/java/net/micode/notes/ui/DateTimePicker.java b/src/main/java/net/micode/notes/ui/DateTimePicker.java new file mode 100644 index 0000000..c805b60 --- /dev/null +++ b/src/main/java/net/micode/notes/ui/DateTimePicker.java @@ -0,0 +1,646 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import java.text.DateFormatSymbols; +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; + +/** + * 日期时间选择组件 + *+ * 该类是一个自定义的日期时间选择组件,继承自FrameLayout,用于在小米便签应用中 + * 提供直观的日期时间选择界面。它支持12/24小时制切换,并通过NumberPicker组件 + * 实现日期、小时、分钟和AM/PM的选择 + *
+ */ +public class DateTimePicker extends FrameLayout { + + /** + * 默认启用状态 + */ + private static final boolean DEFAULT_ENABLE_STATE = true; + + /** + * 半天的小时数(12小时) + */ + private static final int HOURS_IN_HALF_DAY = 12; + + /** + * 全天的小时数(24小时) + */ + private static final int HOURS_IN_ALL_DAY = 24; + + /** + * 一周的天数(7天) + */ + 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; + + /** + * 24小时制下小时选择器的最大值 + */ + 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; + + /** + * 12小时制下小时选择器的最大值 + */ + 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; + + /** + * AM/PM选择器的最小值 + */ + private static final int AMPM_SPINNER_MIN_VAL = 0; + + /** + * AM/PM选择器的最大值 + */ + private static final int AMPM_SPINNER_MAX_VAL = 1; + + /** + * 日期选择器组件 + */ + private final NumberPicker mDateSpinner; + + /** + * 小时选择器组件 + */ + private final NumberPicker mHourSpinner; + + /** + * 分钟选择器组件 + */ + private final NumberPicker mMinuteSpinner; + + /** + * AM/PM选择器组件 + */ + private final NumberPicker mAmPmSpinner; + + /** + * 当前选择的日期和时间 + */ + private Calendar mDate; + + /** + * 日期选择器显示的日期值数组 + */ + private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; + + /** + * 是否为上午 + */ + private boolean mIsAm; + + /** + * 是否为24小时制视图 + */ + private boolean mIs24HourView; + + /** + * 组件是否启用 + */ + 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) { + if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, 1); + isDateChanged = true; + } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + 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 { + if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, 1); + isDateChanged = true; + } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -1); + 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)); + setCurrentDay(cal.get(Calendar.DAY_OF_MONTH)); + } + } + }; + + 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; + 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; + updateAmPmControl(); + } else { + mIsAm = true; + 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); + } else { + mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); + } + updateAmPmControl(); + onDateTimeChanged(); + } + }; + + /** + * 日期时间变化监听器接口 + *+ * 当日期时间选择器的值发生变化时,会通过此接口通知外部 + *
+ */ + public interface OnDateTimeChangedListener { + /** + * 日期时间变化时调用的方法 + * @param view 日期时间选择器实例 + * @param year 选择的年份 + * @param month 选择的月份(0-11) + * @param dayOfMonth 选择的日(1-31) + * @param hourOfDay 选择的小时(0-23) + * @param minute 选择的分钟(0-59) + */ + void onDateTimeChanged(DateTimePicker view, int year, int month, + int dayOfMonth, int hourOfDay, int minute); + } + + /** + * 构造函数,使用当前时间初始化日期时间选择器 + * @param context 上下文对象 + */ + public DateTimePicker(Context context) { + this(context, System.currentTimeMillis()); + } + + /** + * 构造函数,使用指定时间初始化日期时间选择器,根据系统设置决定是否使用24小时制 + * @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.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); + mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL); + 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; + } + + @Override + public void setEnabled(boolean enabled) { + if (mIsEnabled == enabled) { + return; + } + super.setEnabled(enabled); + mDateSpinner.setEnabled(enabled); + mMinuteSpinner.setEnabled(enabled); + mHourSpinner.setEnabled(enabled); + mAmPmSpinner.setEnabled(enabled); + mIsEnabled = enabled; + } + + @Override + public boolean isEnabled() { + return mIsEnabled; + } + + /** + * Get the current date in millis + * + * @return the current date in millis + */ + public long getCurrentDateInTimeMillis() { + return mDate.getTimeInMillis(); + } + + /** + * Set the current date + * + * @param date The current date in millis + */ + public void setCurrentDate(long date) { + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(date); + setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), + cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)); + } + + /** + * 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 + */ + public void setCurrentDate(int year, int month, + int dayOfMonth, int hourOfDay, int minute) { + setCurrentYear(year); + setCurrentMonth(month); + setCurrentDay(dayOfMonth); + setCurrentHour(hourOfDay); + setCurrentMinute(minute); + } + + /** + * Get current year + * + * @return The current year + */ + public int getCurrentYear() { + return mDate.get(Calendar.YEAR); + } + + /** + * Set current year + * + * @param year The current year + */ + public void setCurrentYear(int year) { + if (!mInitialising && year == getCurrentYear()) { + return; + } + mDate.set(Calendar.YEAR, year); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current month in the year + * + * @return The current month in the year + */ + public int getCurrentMonth() { + return mDate.get(Calendar.MONTH); + } + + /** + * Set current month in the year + * + * @param month The month in the year + */ + public void setCurrentMonth(int month) { + if (!mInitialising && month == getCurrentMonth()) { + return; + } + mDate.set(Calendar.MONTH, month); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current day of the month + * + * @return The day of the month + */ + public int getCurrentDay() { + return mDate.get(Calendar.DAY_OF_MONTH); + } + + /** + * Set current day of the month + * + * @param dayOfMonth The day of the month + */ + public void setCurrentDay(int dayOfMonth) { + if (!mInitialising && dayOfMonth == getCurrentDay()) { + return; + } + mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current hour in 24 hour mode, in the range (0~23) + * @return The current hour in 24 hour mode + */ + public int getCurrentHourOfDay() { + return mDate.get(Calendar.HOUR_OF_DAY); + } + + /** + * 获取当前小时 + *+ * 根据当前视图模式返回正确的小时值: + * - 24小时制:直接返回当前小时(0-23) + * - 12小时制:返回1-12之间的小时值 + *
+ * @return 当前小时值 + */ + private int getCurrentHour() { + if (mIs24HourView){ + return getCurrentHourOfDay(); + } else { + int hour = getCurrentHourOfDay(); + if (hour > HOURS_IN_HALF_DAY) { + return hour - HOURS_IN_HALF_DAY; + } else { + return hour == 0 ? HOURS_IN_HALF_DAY : hour; + } + } + } + + /** + * 设置当前小时(24小时制,范围0-23) + * @param hourOfDay 当前小时值(24小时制) + */ + public void setCurrentHour(int hourOfDay) { + if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { + return; + } + mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); + if (!mIs24HourView) { + if (hourOfDay >= HOURS_IN_HALF_DAY) { + mIsAm = false; + if (hourOfDay > HOURS_IN_HALF_DAY) { + hourOfDay -= HOURS_IN_HALF_DAY; + } + } else { + mIsAm = true; + if (hourOfDay == 0) { + hourOfDay = HOURS_IN_HALF_DAY; + } + } + updateAmPmControl(); + } + mHourSpinner.setValue(hourOfDay); + onDateTimeChanged(); + } + + /** + * 获取当前分钟 + * @return 当前分钟值(0-59) + */ + public int getCurrentMinute() { + return mDate.get(Calendar.MINUTE); + } + + /** + * 设置当前分钟 + * @param minute 当前分钟值(0-59) + */ + public void setCurrentMinute(int minute) { + if (!mInitialising && minute == getCurrentMinute()) { + return; + } + mMinuteSpinner.setValue(minute); + mDate.set(Calendar.MINUTE, minute); + onDateTimeChanged(); + } + + /** + * 获取当前是否为24小时制视图 + * @return true表示为24小时制视图,false表示为12小时制视图 + */ + public boolean is24HourView () { + return mIs24HourView; + } + + /** + * 设置是否使用24小时制或AM/PM模式 + * @param is24HourView true表示使用24小时制,false表示使用AM/PM模式 + */ + public void set24HourView(boolean is24HourView) { + if (mIs24HourView == is24HourView) { + return; + } + mIs24HourView = is24HourView; + mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); + int hour = getCurrentHourOfDay(); + updateHourControl(); + setCurrentHour(hour); + 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); + } + mDateSpinner.setDisplayedValues(mDateDisplayValues); + mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); + mDateSpinner.invalidate(); + } + + /** + * 更新AM/PM控件 + *+ * 该方法负责根据当前时间和视图模式更新AM/PM选择器的显示 + *
+ */ + private void updateAmPmControl() { + if (mIs24HourView) { + mAmPmSpinner.setVisibility(View.GONE); + } else { + int index = mIsAm ? Calendar.AM : Calendar.PM; + mAmPmSpinner.setValue(index); + mAmPmSpinner.setVisibility(View.VISIBLE); + } + } + + /** + * 更新小时控件 + *+ * 该方法负责根据当前视图模式更新小时选择器的最小值和最大值 + *
+ */ + private void updateHourControl() { + if (mIs24HourView) { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW); + } else { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); + } + } + + /** + * 设置日期时间变化监听器 + * @param callback 日期时间变化时的回调函数,若为null则不执行任何操作 + */ + public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { + mOnDateTimeChangedListener = callback; + } + + /** + * 日期时间变化时调用的方法 + *+ * 当日期或时间发生变化时,该方法会通知注册的监听器 + *
+ */ + private void onDateTimeChanged() { + if (mOnDateTimeChangedListener != null) { + mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), + getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); + } + } +} diff --git a/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java b/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java new file mode 100644 index 0000000..b9986ac --- /dev/null +++ b/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import java.util.Calendar; + +import net.micode.notes.R; +import net.micode.notes.ui.DateTimePicker; +import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.text.format.DateFormat; +import android.text.format.DateUtils; + +/** + * 日期时间选择对话框 + *+ * 该类是一个封装了DateTimePicker组件的对话框,用于在小米便签应用中 + * 提供一个完整的日期时间选择界面。用户可以通过该对话框选择日期和时间, + * 并在确认后将选择结果返回给调用者 + *
+ */ +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) { + 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); + mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); + setButton(context.getString(R.string.datetime_dialog_ok), this); + setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); + set24HourView(DateFormat.is24HourFormat(this.getContext())); + updateTitle(mDate.getTimeInMillis()); + } + + /** + * 设置是否使用24小时制视图 + * @param is24HourView true表示使用24小时制,false表示使用12小时制 + */ + public void set24HourView(boolean is24HourView) { + mIs24HourView = 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; + flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; + setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); + } + + /** + * 点击对话框按钮时调用的方法 + *+ * 当用户点击对话框的确定按钮时,会调用该方法,通知注册的监听器 + *
+ * @param arg0 对话框实例 + * @param arg1 点击的按钮ID + */ + @Override + public void onClick(DialogInterface arg0, int arg1) { + if (mOnDateTimeSetListener != null) { + mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); + } + } + +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/ui/DropdownMenu.java b/src/main/java/net/micode/notes/ui/DropdownMenu.java new file mode 100644 index 0000000..4e58bbb --- /dev/null +++ b/src/main/java/net/micode/notes/ui/DropdownMenu.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.PopupMenu; +import android.widget.PopupMenu.OnMenuItemClickListener; + +import net.micode.notes.R; + +/** + * 下拉菜单封装类 + *+ * 该类封装了Android的PopupMenu,提供了一个简单的接口来创建和管理下拉菜单 + *
+ */ +public class DropdownMenu { + /** + * 触发下拉菜单的按钮 + */ + private Button mButton; + + /** + * 下拉菜单实例 + */ + 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); + mPopupMenu = new PopupMenu(context, mButton); + mMenu = mPopupMenu.getMenu(); + mPopupMenu.getMenuInflater().inflate(menuId, mMenu); + mButton.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + mPopupMenu.show(); + } + }); + } + + /** + * 设置下拉菜单项点击监听器 + * @param listener 菜单项点击监听器 + */ + public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { + if (mPopupMenu != null) { + mPopupMenu.setOnMenuItemClickListener(listener); + } + } + + /** + * 查找指定ID的菜单项 + * @param id 菜单项ID + * @return 指定ID的菜单项,若不存在则返回null + */ + public MenuItem findItem(int id) { + return mMenu.findItem(id); + } + + /** + * 设置下拉菜单按钮的标题 + * @param title 按钮标题 + */ + public void setTitle(CharSequence title) { + mButton.setText(title); + } +} diff --git a/src/main/java/net/micode/notes/ui/FoldersListAdapter.java b/src/main/java/net/micode/notes/ui/FoldersListAdapter.java new file mode 100644 index 0000000..7e05bf2 --- /dev/null +++ b/src/main/java/net/micode/notes/ui/FoldersListAdapter.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +/** + * 文件夹列表适配器 + *+ * 该类继承自CursorAdapter,用于在小米便签应用中显示文件夹列表 + *
+ */ +public class FoldersListAdapter extends CursorAdapter { + /** + * 文件夹数据查询的投影列数组 + *+ * 定义了从数据库查询文件夹数据时需要获取的列,包括文件夹ID和名称 + *
+ */ + public static final String [] PROJECTION = { + NoteColumns.ID, + NoteColumns.SNIPPET + }; + + /** + * 查询结果中文件夹ID列的索引 + */ + public static final int ID_COLUMN = 0; + + /** + * 查询结果中文件夹名称列的索引 + */ + public static final int NAME_COLUMN = 1; + + /** + * 构造函数,创建文件夹列表适配器 + * @param context 上下文对象 + * @param c 包含文件夹数据的游标 + */ + public FoldersListAdapter(Context context, Cursor c) { + super(context, c); + // TODO Auto-generated constructor stub + } + + /** + * 创建新的列表项视图 + * @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); + ((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); + } + + /** + * 文件夹列表项视图 + *+ * 该内部类用于显示单个文件夹列表项 + *
+ */ + private class FolderListItem extends LinearLayout { + /** + * 文件夹名称文本视图 + */ + 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); + } + } + +} diff --git a/src/main/java/net/micode/notes/ui/NoteEditActivity.java b/src/main/java/net/micode/notes/ui/NoteEditActivity.java new file mode 100644 index 0000000..c80949f --- /dev/null +++ b/src/main/java/net/micode/notes/ui/NoteEditActivity.java @@ -0,0 +1,1445 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlarmManager; +import android.app.AlertDialog; +import android.app.PendingIntent; +import android.app.SearchManager; +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Paint; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Html; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.format.DateUtils; +import android.text.style.BackgroundColorSpan; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.ImageButton; +import android.widget.ImageView; +import android.database.Cursor; +import android.content.ContentResolver; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.TextNote; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.model.WorkingNote.NoteSettingChangedListener; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.tool.ResourceParser.TextAppearanceResources; +import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener; +import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; +import net.micode.notes.ui.TemplateSelectActivity; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +/** + * 笔记编辑活动类,负责处理笔记的创建、编辑和保存操作。 + *+ * 该类实现了笔记编辑界面的所有功能,包括文本编辑、背景颜色设置、字体大小调整、 + * 提醒设置、分享等功能,同时支持普通文本模式和清单模式的切换。 + *
+ */ +public class NoteEditActivity extends Activity implements OnClickListener, + NoteSettingChangedListener, OnTextViewChangeListener { + /** + * 头部视图持有者类,用于缓存头部视图的控件引用 + */ + private class HeadViewHolder { + public TextView tvModified; + + public ImageView ivAlertIcon; + + public TextView tvAlertDate; + + public ImageButton ibSetBgColor; + } + + /** 背景颜色选择按钮映射表,将按钮ID映射到颜色ID */ + private static final Map+ * 先尝试清除设置状态,如果成功则不执行返回操作,否则保存笔记并执行返回 + *
+ */ + @Override + public void onBackPressed() { + if(clearSettingState()) { + return; + } + + saveNote(); + super.onBackPressed(); + } + + /** + * 清除设置状态,隐藏所有设置选择器 + * + * @return 如果有设置选择器被隐藏,则返回true;否则返回false + */ + private boolean clearSettingState() { + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } else if (mNoteTextColorSelector.getVisibility() == View.VISIBLE) { + mNoteTextColorSelector.setVisibility(View.GONE); + return true; + } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return false; + } + + /** + * 背景颜色改变时调用的回调方法 + *+ * 显示当前选中的背景颜色,并更新头部面板和编辑面板的背景资源 + *
+ */ + public void onBackgroundColorChanged() { + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.VISIBLE); + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + } + + /** + * 准备选项菜单,在菜单显示前调用 + *+ * 根据笔记类型和当前状态动态配置菜单项,包括加载不同的菜单资源、 + * 设置菜单标题和控制菜单项的可见性 + *
+ * + * @param menu 要准备的菜单对象 + * @return 是否成功准备菜单 + */ + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + if (isFinishing()) { + return true; + } + clearSettingState(); + menu.clear(); + if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { + getMenuInflater().inflate(R.menu.call_note_edit, menu); + } else { + getMenuInflater().inflate(R.menu.note_edit, menu); + } + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); + } else { + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); + } + if (mWorkingNote.hasClockAlert()) { + menu.findItem(R.id.menu_alert).setVisible(false); + } else { + menu.findItem(R.id.menu_delete_remind).setVisible(false); + } + return true; + } + + /** + * 处理菜单选项选择事件 + *+ * 该方法处理各种菜单选项的点击事件,包括创建新笔记、删除笔记、设置字体大小、 + * 切换列表模式、分享笔记、发送到桌面、设置提醒等功能 + *
+ * @param item 被选择的菜单项 + * @return 总是返回true,表示事件已被处理 + */ + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_new_note: + createNewNote(); + break; + case R.id.menu_delete: + AlertDialog.Builder builder = new AlertDialog.Builder(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_note)); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteCurrentNote(); + finish(); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case R.id.menu_font_size: + mFontSizeSelector.setVisibility(View.VISIBLE); + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); + break; + case R.id.menu_list_mode: + mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ? + TextNote.MODE_CHECK_LIST : 0); + break; + case R.id.menu_share: + getWorkingText(); + sendTo(this, mWorkingNote.getContent()); + break; + case R.id.menu_send_to_desktop: + sendToDesktop(); + break; + case R.id.menu_alert: + setReminder(); + break; + case R.id.menu_delete_remind: + mWorkingNote.setAlertDate(0, false); + break; + case R.id.menu_lock: + showPasswordDialogForLock(); + break; + case R.id.menu_unlock: + showPasswordDialogForUnlock(); + break; + case R.id.menu_note_template: + openTemplateSelector(); + break; + default: + break; + } + return true; + } + + /** + * 设置笔记的提醒时间 + *+ * 该方法显示一个日期时间选择对话框,让用户选择提醒时间, + * 并将选择的时间设置到当前编辑的笔记中 + *
+ */ + private void setReminder() { + DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); + d.setOnDateTimeSetListener(new OnDateTimeSetListener() { + public void OnDateTimeSet(AlertDialog dialog, long date) { + mWorkingNote.setAlertDate(date , true); + } + }); + d.show(); + } + + /** + * 分享笔记到支持{@link Intent#ACTION_SEND}动作和{@text/plain}类型的应用 + *+ * 该方法创建一个分享意图,将笔记内容发送给其他支持文本分享的应用程序 + *
+ * @param context 上下文对象 + * @param info 要分享的笔记内容 + */ + private void sendTo(Context context, String info) { + Intent intent = new Intent(Intent.ACTION_SEND); + intent.putExtra(Intent.EXTRA_TEXT, info); + intent.setType("text/plain"); + context.startActivity(intent); + } + + /** + * 显示密码输入对话框用于锁定笔记 + *+ * 该方法用于显示一个密码输入对话框,让用户输入密码来锁定当前编辑的笔记 + *
+ */ + private void showPasswordDialogForLock() { + final EditText passwordEditText = new EditText(this); + passwordEditText.setHint(R.string.hint_enter_password); + passwordEditText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); + + new AlertDialog.Builder(this) + .setTitle(R.string.dialog_enter_password) + .setView(passwordEditText) + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + String password = passwordEditText.getText().toString(); + if (!TextUtils.isEmpty(password)) { + lockCurrentNote(password); + } + } + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); + } + + /** + * 显示密码输入对话框用于解锁笔记 + *+ * 该方法用于显示一个密码输入对话框,让用户输入密码来解锁当前编辑的笔记 + *
+ */ + private void showPasswordDialogForUnlock() { + final EditText passwordEditText = new EditText(this); + passwordEditText.setHint(R.string.hint_enter_password); + passwordEditText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); + + new AlertDialog.Builder(this) + .setTitle(R.string.dialog_enter_password) + .setView(passwordEditText) + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + String password = passwordEditText.getText().toString(); + if (!TextUtils.isEmpty(password)) { + unlockCurrentNote(password); + } + } + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); + } + + /** + * 锁定当前笔记 + *+ * 该方法用于锁定当前编辑的笔记,更新其锁定状态、密码和锁定类型 + *
+ * @param password 用于锁定的密码 + */ + private void lockCurrentNote(String password) { + // 设置锁定状态为1(已锁定) + mWorkingNote.setNoteValue(NoteColumns.IS_LOCKED, "1"); + // 设置加密后的密码 + mWorkingNote.setNoteValue(NoteColumns.LOCK_PASSWORD, encryptPassword(password)); + // 设置锁定类型为笔记类型 + mWorkingNote.setNoteValue(NoteColumns.LOCK_TYPE, String.valueOf(Notes.LOCK_TYPE_NOTE)); + // 保存笔记 + saveNote(); + // 显示提示信息 + Toast.makeText(this, getString(R.string.message_note_locked), Toast.LENGTH_SHORT).show(); + } + + /** + * 解锁当前笔记 + *+ * 该方法用于解锁当前编辑的笔记,更新其锁定状态和密码 + *
+ * @param password 用于解锁的密码 + */ + private void unlockCurrentNote(String password) { + // 使用ContentResolver直接查询数据库获取加密密码 + String[] projection = {NoteColumns.LOCK_PASSWORD}; + String selection = NoteColumns.ID + "=?"; + String[] selectionArgs = {String.valueOf(mWorkingNote.getNoteId())}; + + Cursor cursor = getContentResolver().query(Notes.CONTENT_NOTE_URI, projection, selection, selectionArgs, null); + String encryptedPassword = null; + + if (cursor != null && cursor.moveToFirst()) { + encryptedPassword = cursor.getString(0); + cursor.close(); + } + + // 验证密码是否正确 + if (encryptedPassword != null && encryptedPassword.equals(encryptPassword(password))) { + // 密码正确,设置锁定状态为0(未锁定) + mWorkingNote.setNoteValue(NoteColumns.IS_LOCKED, "0"); + // 清空密码 + mWorkingNote.setNoteValue(NoteColumns.LOCK_PASSWORD, ""); + // 保存笔记 + saveNote(); + // 显示提示信息 + Toast.makeText(this, getString(R.string.message_note_unlocked), Toast.LENGTH_SHORT).show(); + } else { + // 密码错误,显示错误信息 + Toast.makeText(this, getString(R.string.error_wrong_password), Toast.LENGTH_SHORT).show(); + } + } + + /** + * 加密密码 + *+ * 该方法使用Base64和ANDROID_ID对密码进行加密 + *
+ * @param password 原始密码 + * @return 加密后的密码 + */ + private String encryptPassword(String password) { + try { + // 获取设备的ANDROID_ID作为加密密钥 + String androidId = android.provider.Settings.Secure.getString(getContentResolver(), + android.provider.Settings.Secure.ANDROID_ID); + // 使用简单的加密算法:将密码与ANDROID_ID拼接后进行Base64编码 + String combined = password + androidId; + return android.util.Base64.encodeToString(combined.getBytes(), android.util.Base64.DEFAULT); + } catch (Exception e) { + Log.e(TAG, "Password encryption failed", e); + return password; // 加密失败时返回原始密码 + } + } + + /** + * 创建新笔记 + *+ * 该方法先保存当前编辑的笔记,然后结束当前活动并启动一个新的NoteEditActivity + * 来创建新笔记,确保笔记保存在同一文件夹中 + *
+ */ + private void createNewNote() { + // Firstly, save current editing notes + saveNote(); + + // For safety, start a new NoteEditActivity + finish(); + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); + startActivity(intent); + } + + /** + * 删除当前编辑的笔记 + *+ * 该方法根据笔记是否存在于数据库中进行处理: + * 1. 如果笔记存在,将其ID添加到待删除列表 + * 2. 如果不是同步模式,直接删除笔记 + * 3. 如果是同步模式,将笔记移动到垃圾桶 + *
+ */ + private void deleteCurrentNote() { + if (mWorkingNote.existInDatabase()) { + HashSet+ * 该方法通过检查同步账户名称是否存在来判断是否启用了同步模式 + *
+ * @return 如果启用了同步模式返回true,否则返回false + */ + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + /** + * 处理时钟提醒的变化 + *+ * 该方法用于设置或取消笔记的时钟提醒, + * 如果笔记未保存,会先保存笔记,然后根据参数设置或取消闹钟 + *
+ * @param date 提醒时间的时间戳 + * @param set 如果为true则设置提醒,为false则取消提醒 + */ + public void onClockAlertChanged(long date, boolean set) { + // 用户可能会为未保存的笔记设置时钟,所以在设置提醒时钟之前,我们应该先保存笔记 + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + if (mWorkingNote.getNoteId() > 0) { + Intent intent = new Intent(this, AlarmReceiver.class); + intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId())); + PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); + AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE)); + showAlertHeader(); + if(!set) { + alarmManager.cancel(pendingIntent); + } else { + alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); + } + } else { + /** + * There is the condition that user has input nothing (the note is + * not worthy saving), we have no note id, remind the user that he + * should input something + */ + Log.e(TAG, "Clock alert setting error"); + showToast(R.string.error_note_empty_for_clock); + } + } + + /** + * 更新小部件 + *+ * 该方法调用updateWidget()方法来更新桌面小部件的内容 + *
+ */ + public void onWidgetChanged() { + updateWidget(); + } + + /** + * 处理编辑文本的删除操作 + *+ * 该方法处理用户在编辑文本时按下删除键的操作,特别是在列表模式下: + * 1. 检查是否只有一个编辑文本项,如果是则直接返回 + * 2. 将索引大于当前删除项的所有编辑文本项的索引减1 + * 3. 从列表中移除指定索引的视图 + * 4. 将被删除的文本追加到前一个或第一个编辑文本项中 + * 5. 设置焦点并将光标移动到追加文本的开始位置 + *
+ * @param index 要删除的编辑文本项的索引 + * @param text 被删除的文本内容 + */ + public void onEditTextDelete(int index, String text) { + int childCount = mEditTextList.getChildCount(); + if (childCount == 1) { + return; + } + + for (int i = index + 1; i < childCount; i++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i - 1); + } + + mEditTextList.removeViewAt(index); + NoteEditText edit = null; + if(index == 0) { + edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById( + R.id.et_edit_text); + } else { + edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById( + R.id.et_edit_text); + } + int length = edit.length(); + edit.append(text); + edit.requestFocus(); + edit.setSelection(length); + } + + /** + * 处理编辑文本的回车操作 + *+ * 该方法处理用户在编辑文本时按下回车键的操作,在指定索引位置插入新的编辑文本项 + *
+ * @param index 插入新编辑文本项的索引位置 + * @param text 新编辑文本项的内容 + */ + public void onEditTextEnter(int index, String text) { + // 不应该发生的情况,用于调试检查 + if(index > mEditTextList.getChildCount()) { + Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); + } + + View view = getListItem(text, index); + mEditTextList.addView(view, index); + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.requestFocus(); + edit.setSelection(0); + for (int i = index + 1; i < mEditTextList.getChildCount(); i++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i); + } + } + + /** + * 切换到列表模式 + *+ * 该方法将笔记从普通文本模式切换到列表模式, + * 将文本内容按行分割并创建对应的列表项,最后添加一个空的列表项用于继续输入 + *
+ * @param text 当前笔记的文本内容 + */ + private void switchToListMode(String text) { + mEditTextList.removeAllViews(); + String[] items = text.split("\n"); + int index = 0; + for (String item : items) { + if(!TextUtils.isEmpty(item)) { + mEditTextList.addView(getListItem(item, index)); + index++; + } + } + mEditTextList.addView(getListItem("", index)); + mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); + + mNoteEditor.setVisibility(View.GONE); + mEditTextList.setVisibility(View.VISIBLE); + } + + /** + * 获取带有高亮查询结果的文本 + *+ * 该方法在完整文本中查找用户查询的内容,并为匹配项添加背景高亮效果 + *
+ * @param fullText 完整的文本内容,支持CharSequence类型 + * @param userQuery 用户查询的内容 + * @return 带有高亮查询结果的Spannable对象 + */ + private Spannable getHighlightQueryResult(CharSequence fullText, String userQuery) { + SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); + if (!TextUtils.isEmpty(userQuery)) { + mPattern = Pattern.compile(userQuery); + Matcher m = mPattern.matcher(fullText); + int start = 0; + while (m.find(start)) { + spannable.setSpan( + new BackgroundColorSpan(this.getResources().getColor( + R.color.user_query_highlight)), m.start(), m.end(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + start = m.end(); + } + } + return spannable; + } + + /** + * 获取列表模式下的列表项视图 + *+ * 该方法创建并配置列表模式下的列表项视图,包括: + * 1. 加载列表项布局 + * 2. 设置编辑文本的字体大小 + * 3. 配置复选框的选中状态变化监听器 + * 4. 根据项目文本的标签设置初始选中状态和文本样式 + * 5. 设置文本变化监听器和索引 + * 6. 应用查询高亮效果 + *
+ * @param item 列表项的文本内容 + * @param index 列表项的索引 + * @return 配置好的列表项视图 + */ + private View getListItem(String item, int index) { + View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); + final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); + cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + } else { + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); + } + } + }); + + if (item.startsWith(TAG_CHECKED)) { + cb.setChecked(true); + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + item = item.substring(TAG_CHECKED.length(), item.length()).trim(); + } else if (item.startsWith(TAG_UNCHECKED)) { + cb.setChecked(false); + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); + item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); + } + + edit.setOnTextViewChangeListener(this); + edit.setIndex(index); + edit.setText(getHighlightQueryResult(item, mUserQuery)); + return view; + } + + /** + * 处理文本变化事件 + *+ * 该方法在列表模式下处理编辑文本的内容变化事件, + * 根据文本是否为空来控制对应列表项中复选框的显示或隐藏 + *
+ * @param index 编辑文本项的索引 + * @param hasText 编辑文本是否包含内容 + */ + public void onTextChange(int index, boolean hasText) { + if (index >= mEditTextList.getChildCount()) { + Log.e(TAG, "Wrong index, should not happen"); + return; + } + if(hasText) { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE); + } else { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE); + } + } + + /** + * 处理检查列表模式的变化 + *+ * 该方法在笔记的普通文本模式和检查列表模式之间切换时被调用, + * 根据新的模式执行相应的视图切换和数据处理操作 + *
+ * @param oldMode 旧的模式 + * @param newMode 新的模式 + */ + public void onCheckListModeChanged(int oldMode, int newMode) { + if (newMode == TextNote.MODE_CHECK_LIST) { + switchToListMode(mNoteEditor.getText().toString()); + } else { + if (!getWorkingText()) { + mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ", + "")); + } + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); + mEditTextList.setVisibility(View.GONE); + mNoteEditor.setVisibility(View.VISIBLE); + } + } + + /** + * 获取当前工作笔记的文本内容 + *+ * 该方法根据当前笔记的模式(普通文本或检查列表)获取相应的文本内容: + * 1. 如果是检查列表模式,遍历所有列表项,收集文本内容并添加相应的标签(已完成或未完成) + * 2. 如果是普通文本模式,直接获取编辑框的文本内容 + *
+ * @return 是否包含已完成的列表项 + */ + private boolean getWorkingText() { + boolean hasChecked = false; + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < mEditTextList.getChildCount(); i++) { + View view = mEditTextList.getChildAt(i); + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + if (!TextUtils.isEmpty(edit.getText())) { + if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) { + sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n"); + hasChecked = true; + } else { + sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n"); + } + } + } + mWorkingNote.setWorkingText(sb.toString()); + } else { + // 保留富文本格式,将 Spanned 转换为 HTML 字符串保存 + mWorkingNote.setWorkingText(Html.toHtml(mNoteEditor.getText())); + } + return hasChecked; + } + + /** + * 保存当前工作笔记 + *+ * 该方法首先获取当前工作笔记的最新文本内容,然后调用mWorkingNote的saveNote方法将其保存到数据库中。 + * 如果保存成功,会设置返回结果为RESULT_OK,用于标识创建/编辑状态,以便在返回列表视图时正确定位。 + *
+ * @return 保存是否成功 + */ + private boolean saveNote() { + getWorkingText(); + boolean saved = mWorkingNote.saveNote(); + if (saved) { + /** + * There are two modes from List view to edit view, open one note, + * create/edit a node. Opening node requires to the original + * position in the list when back from edit view, while creating a + * new node requires to the top of the list. This code + * {@link #RESULT_OK} is used to identify the create/edit state + */ + setResult(RESULT_OK); + } + return saved; + } + + /** + * 将当前编辑的笔记发送到桌面创建快捷方式 + *+ * 该方法执行以下操作: + * 1. 在发送前确保当前编辑的笔记已保存在数据库中,如果是新笔记则先保存 + * 2. 创建一个快捷方式Intent,包含打开该笔记的相关信息 + * 3. 设置快捷方式的名称、图标等属性 + * 4. 发送广播来创建桌面快捷方式 + * 5. 如果笔记为空或保存失败,显示错误提示 + *
+ */ + private void sendToDesktop() { + // 在发送到桌面之前,确保当前编辑的笔记已存在于数据库中。对于新笔记,首先保存它 + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + + if (mWorkingNote.getNoteId() > 0) { + Intent sender = new Intent(); + Intent shortcutIntent = new Intent(this, NoteEditActivity.class); + shortcutIntent.setAction(Intent.ACTION_VIEW); + shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); + sender.putExtra(Intent.EXTRA_SHORTCUT_NAME, + makeShortcutIconTitle(mWorkingNote.getContent())); + sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, + Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app)); + sender.putExtra("duplicate", true); + sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); + showToast(R.string.info_note_enter_desktop); + sendBroadcast(sender); + } else { + /** + * There is the condition that user has input nothing (the note is + * not worthy saving), we have no note id, remind the user that he + * should input something + */ + Log.e(TAG, "Send to desktop error"); + showToast(R.string.error_note_empty_for_send_to_desktop); + } + } + + /** + * 生成快捷方式图标的标题 + *+ * 该方法将笔记内容转换为适合作为快捷方式标题的格式: + * 1. 移除检查列表模式下的状态标签(已完成和未完成标签) + * 2. 如果内容长度超过最大限制,则截断为指定长度 + *
+ * @param content 笔记的原始内容 + * @return 处理后的快捷方式标题 + */ + private String makeShortcutIconTitle(String content) { + content = content.replace(TAG_CHECKED, ""); + content = content.replace(TAG_UNCHECKED, ""); + return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0, + SHORTCUT_ICON_TITLE_MAX_LEN) : content; + } + + /** + * 显示短时长的Toast提示信息 + *+ * 该方法是showToast(int resId, int duration)的便捷重载版本, + * 默认使用Toast.LENGTH_SHORT作为显示时长 + *
+ * @param resId 提示信息的字符串资源ID + */ + private void showToast(int resId) { + showToast(resId, Toast.LENGTH_SHORT); + } + + /** + * 打开模板选择页面 + *+ * 该方法启动TemplateSelectActivity,让用户选择便签模板 + *
+ */ + private void openTemplateSelector() { + // 获取当前笔记内容 + getWorkingText(); + String currentContent = mWorkingNote.getContent(); + + Intent intent = new Intent(this, TemplateSelectActivity.class); + intent.putExtra(TemplateSelectActivity.EXTRA_CURRENT_NOTE_CONTENT, currentContent); + startActivityForResult(intent, REQUEST_CODE_TEMPLATE); + } + + /** + * 处理从模板选择页面返回的结果 + *+ * 该方法在从TemplateSelectActivity返回时被调用, + * 如果用户选择了模板,则更新当前笔记的内容 + *
+ * @param requestCode 请求码 + * @param resultCode 结果码 + * @param data 返回的Intent数据 + */ + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == REQUEST_CODE_TEMPLATE && resultCode == RESULT_OK) { + if (data != null) { + String templateContent = data.getStringExtra(TemplateSelectActivity.EXTRA_TEMPLATE_CONTENT); + if (!TextUtils.isEmpty(templateContent)) { + // 保存模板内容到WorkingNote,防止onResume时被覆盖 + mWorkingNote.setWorkingText(templateContent); + + // 更新笔记内容 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + switchToListMode(templateContent); + } else { + mNoteEditor.setText(Html.fromHtml(templateContent)); + mNoteEditor.setSelection(mNoteEditor.getText().length()); + } + Toast.makeText(this, R.string.notealert_enter, Toast.LENGTH_SHORT).show(); + } + } + } + } + + /** + * 显示Toast提示信息 + *+ * 该方法使用Android系统的Toast机制显示指定的提示信息 + *
+ * @param resId 提示信息的字符串资源ID + * @param duration 显示时长,可以是Toast.LENGTH_SHORT或Toast.LENGTH_LONG + */ + private void showToast(int resId, int duration) { + Toast.makeText(this, resId, duration).show(); + } +} diff --git a/src/main/java/net/micode/notes/ui/NoteEditText.java b/src/main/java/net/micode/notes/ui/NoteEditText.java new file mode 100644 index 0000000..5a6842e --- /dev/null +++ b/src/main/java/net/micode/notes/ui/NoteEditText.java @@ -0,0 +1,429 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.graphics.Rect; +import android.text.Layout; +import android.text.Selection; +import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.TextUtils; +import android.text.style.StyleSpan; +import android.text.style.URLSpan; +import android.text.style.UnderlineSpan; +import android.text.style.ForegroundColorSpan; +import android.graphics.Typeface; +import android.util.AttributeSet; +import android.util.Log; +import android.view.ContextMenu; +import android.view.KeyEvent; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.widget.EditText; + +import net.micode.notes.R; + +import java.util.HashMap; +import java.util.Map; + +/** + * 自定义笔记编辑文本框 + *+ * 该类继承自EditText,用于小米便签应用中的笔记编辑,支持链接识别、键盘事件处理 + * 和文本视图变化监听等功能 + *
+ */ +public class NoteEditText extends EditText { + /** + * 日志标签 + */ + private static final String TAG = "NoteEditText"; + + /** + * 当前编辑框的索引 + */ + private int mIndex; + + /** + * 删除操作前的选择起始位置 + */ + private int mSelectionStartBeforeDelete; + + /** + * 电话链接协议 + */ + private static final String SCHEME_TEL = "tel:" ; + + /** + * HTTP链接协议 + */ + private static final String SCHEME_HTTP = "http:" ; + + /** + * 邮件链接协议 + */ + private static final String SCHEME_EMAIL = "mailto:" ; + + /** + * 链接协议与资源ID的映射表 + */ + private static final Map+ * 由{@link NoteEditActivity}调用,用于处理编辑框的删除或添加 + *
+ */ + public interface OnTextViewChangeListener { + /** + * 当按下{@link KeyEvent#KEYCODE_DEL}且文本为空时,删除当前编辑框 + */ + void onEditTextDelete(int index, String text); + + /** + * 当按下{@link KeyEvent#KEYCODE_ENTER}时,在当前编辑框后添加新的编辑框 + */ + void onEditTextEnter(int index, String text); + + /** + * 当文本变化时,隐藏或显示项目选项 + */ + void onTextChange(int index, boolean hasText); + } + + /** + * 文本视图变化监听器实例 + */ + private OnTextViewChangeListener mOnTextViewChangeListener; + + /** + * 构造函数,创建笔记编辑文本框 + * @param context 上下文对象 + */ + public NoteEditText(Context context) { + super(context, null); + mIndex = 0; + } + + /** + * 设置编辑框索引 + * @param index 编辑框索引 + */ + public void setIndex(int index) { + mIndex = index; + } + + /** + * 设置文本视图变化监听器 + * @param listener 文本视图变化监听器 + */ + public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { + mOnTextViewChangeListener = listener; + } + + /** + * 构造函数,创建笔记编辑文本框 + * @param context 上下文对象 + * @param attrs 属性集合 + */ + public NoteEditText(Context context, AttributeSet attrs) { + super(context, attrs, android.R.attr.editTextStyle); + } + + /** + * 构造函数,创建笔记编辑文本框 + * @param context 上下文对象 + * @param attrs 属性集合 + * @param defStyle 默认样式 + */ + public NoteEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + // TODO Auto-generated constructor stub + } + + /** + * 处理触摸事件 + *+ * 当用户点击编辑框时,将光标定位到点击位置 + *
+ * @param event 触摸事件 + * @return 事件是否被处理 + */ + @Override + public boolean onTouchEvent(MotionEvent event) { + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + + int x = (int) event.getX(); + int y = (int) event.getY(); + x -= getTotalPaddingLeft(); + y -= getTotalPaddingTop(); + x += getScrollX(); + y += getScrollY(); + + Layout layout = getLayout(); + int line = layout.getLineForVertical(y); + int off = layout.getOffsetForHorizontal(line, x); + Selection.setSelection(getText(), off); + break; + } + + return super.onTouchEvent(event); + } + + /** + * 处理按键按下事件 + *+ * 监听回车键和删除键的按下事件 + *
+ * @param keyCode 按键代码 + * @param event 按键事件 + * @return 事件是否被处理 + */ + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + switch (keyCode) { + case KeyEvent.KEYCODE_ENTER: + if (mOnTextViewChangeListener != null) { + return false; + } + break; + case KeyEvent.KEYCODE_DEL: + mSelectionStartBeforeDelete = getSelectionStart(); + break; + default: + break; + } + return super.onKeyDown(keyCode, event); + } + + /** + * 处理按键释放事件 + *+ * 监听删除键和回车键的释放事件,实现编辑框的删除和添加功能 + *
+ * @param keyCode 按键代码 + * @param event 按键事件 + * @return 事件是否被处理 + */ + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) { + switch(keyCode) { + case KeyEvent.KEYCODE_DEL: + if (mOnTextViewChangeListener != null) { + if (0 == mSelectionStartBeforeDelete && mIndex != 0) { + mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); + return true; + } + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + case KeyEvent.KEYCODE_ENTER: + if (mOnTextViewChangeListener != null) { + int selectionStart = getSelectionStart(); + String text = getText().subSequence(selectionStart, length()).toString(); + setText(getText().subSequence(0, selectionStart)); + mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + default: + break; + } + return super.onKeyUp(keyCode, event); + } + + /** + * 处理焦点变化事件 + *+ * 当编辑框失去焦点且文本为空时,通知监听器隐藏项目选项 + * 当编辑框获得焦点或文本不为空时,通知监听器显示项目选项 + *
+ * @param focused 是否获得焦点 + * @param direction 焦点变化方向 + * @param previouslyFocusedRect 之前焦点所在的矩形区域 + */ + @Override + protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { + if (mOnTextViewChangeListener != null) { + if (!focused && TextUtils.isEmpty(getText())) { + mOnTextViewChangeListener.onTextChange(mIndex, false); + } else { + mOnTextViewChangeListener.onTextChange(mIndex, true); + } + } + super.onFocusChanged(focused, direction, previouslyFocusedRect); + } + + /** + * 创建上下文菜单 + *+ * 当选中的文本包含链接时,创建相应的链接操作菜单 + *
+ * @param menu 上下文菜单 + */ + @Override + protected void onCreateContextMenu(ContextMenu menu) { + if (getText() instanceof Spanned) { + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd(); + + int min = Math.min(selStart, selEnd); + int max = Math.max(selStart, selEnd); + + final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); + if (urls.length == 1) { + int defaultResId = 0; + for(String schema: sSchemaActionResMap.keySet()) { + if(urls[0].getURL().indexOf(schema) >= 0) { + defaultResId = sSchemaActionResMap.get(schema); + break; + } + } + + if (defaultResId == 0) { + defaultResId = R.string.note_link_other; + } + + menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( + new OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) { + // goto a new intent + urls[0].onClick(NoteEditText.this); + return true; + } + }); + } + } + super.onCreateContextMenu(menu); + } + + /** + * 应用粗体格式到选中文本 + */ + public void applyBold() { + applyStyle(Typeface.BOLD); + } + + /** + * 应用斜体格式到选中文本 + */ + public void applyItalic() { + applyStyle(Typeface.ITALIC); + } + + /** + * 应用下划线格式到选中文本 + */ + public void applyUnderline() { + SpannableStringBuilder ssb = new SpannableStringBuilder(getText()); + int start = getSelectionStart(); + int end = getSelectionEnd(); + + if (start != end) { + // 检查是否已存在下划线样式 + UnderlineSpan[] existingUnderlines = ssb.getSpans(start, end, UnderlineSpan.class); + if (existingUnderlines.length > 0) { + // 移除下划线 + for (UnderlineSpan span : existingUnderlines) { + ssb.removeSpan(span); + } + } else { + // 添加下划线 + ssb.setSpan(new UnderlineSpan(), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); + } + setText(ssb); + setSelection(start, end); + } + } + + /** + * 应用指定颜色到选中文本 + * @param color 要应用的颜色值 + */ + public void applyTextColor(int color) { + SpannableStringBuilder ssb = new SpannableStringBuilder(getText()); + int start = getSelectionStart(); + int end = getSelectionEnd(); + + if (start != end) { + // 移除已有的文字颜色 + ForegroundColorSpan[] existingSpans = ssb.getSpans(start, end, ForegroundColorSpan.class); + for (ForegroundColorSpan span : existingSpans) { + ssb.removeSpan(span); + } + + // 添加新的文字颜色 + ssb.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); + + setText(ssb); + setSelection(start, end); + } + } + + /** + * 应用字体样式到选中文本 + */ + private void applyStyle(int style) { + SpannableStringBuilder ssb = new SpannableStringBuilder(getText()); + int start = getSelectionStart(); + int end = getSelectionEnd(); + + if (start != end) { + // 获取当前选中文本的所有样式 + StyleSpan[] existingSpans = ssb.getSpans(start, end, StyleSpan.class); + + // 计算当前选中文本的总样式 + int currentStyle = Typeface.NORMAL; + if (existingSpans.length > 0) { + // 如果有样式,取第一个样式(假设所有样式一致) + currentStyle = existingSpans[0].getStyle(); + } + + // 计算新的字体样式 + int newStyle; + if ((currentStyle & style) != 0) { + // 移除该样式 + newStyle = currentStyle & ~style; + } else { + // 添加该样式 + newStyle = currentStyle | style; + } + + // 移除旧的样式 + for (StyleSpan span : existingSpans) { + ssb.removeSpan(span); + } + + // 添加新的样式 + ssb.setSpan(new StyleSpan(newStyle), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); + setText(ssb); + setSelection(start, end); + } + } +} diff --git a/src/main/java/net/micode/notes/ui/NoteItemData.java b/src/main/java/net/micode/notes/ui/NoteItemData.java new file mode 100644 index 0000000..2dcdedf --- /dev/null +++ b/src/main/java/net/micode/notes/ui/NoteItemData.java @@ -0,0 +1,600 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.text.TextUtils; + +import net.micode.notes.data.Contact; +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, + NoteColumns.PINNED, + NoteColumns.IS_LOCKED, + NoteColumns.LOCK_PASSWORD, + NoteColumns.LOCK_TYPE, + NoteColumns.DELETED_DATE, + }; + + /** + * 查询结果中笔记ID列的索引 + */ + private static final int ID_COLUMN = 0; + + /** + * 查询结果中提醒日期列的索引 + */ + private static final int ALERTED_DATE_COLUMN = 1; + + /** + * 查询结果中背景颜色ID列的索引 + */ + 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; + + /** + * 查询结果中父文件夹ID列的索引 + */ + private static final int PARENT_ID_COLUMN = 7; + + /** + * 查询结果中笔记摘要列的索引 + */ + private static final int SNIPPET_COLUMN = 8; + + /** + * 查询结果中笔记类型列的索引 + */ + private static final int TYPE_COLUMN = 9; + + /** + * 查询结果中小组件ID列的索引 + */ + private static final int WIDGET_ID_COLUMN = 10; + + /** + * 查询结果中小组件类型列的索引 + */ + private static final int WIDGET_TYPE_COLUMN = 11; + + /** + * 查询结果中置顶状态列的索引 + */ + private static final int PINNED_COLUMN = 12; + + /** + * 查询结果中锁定状态列的索引 + */ + private static final int IS_LOCKED_COLUMN = 13; + + /** + * 查询结果中锁定密码列的索引 + */ + private static final int LOCK_PASSWORD_COLUMN = 14; + + /** + * 查询结果中锁定类型列的索引 + */ + private static final int LOCK_TYPE_COLUMN = 15; + + /** + * 查询结果中删除日期列的索引 + */ + private static final int DELETED_DATE_COLUMN = 16; + + /** + * 笔记ID + */ + private long mId; + + /** + * 置顶状态 + */ + private boolean mPinned; + + /** + * 锁定状态 + */ + private boolean mIsLocked; + + /** + * 锁定密码 + */ + private String mLockPassword; + + /** + * 锁定类型 + */ + private int mLockType; + + /** + * 提醒日期 + */ + private long mAlertDate; + + /** + * 背景颜色ID + */ + private int mBgColorId; + + /** + * 创建日期 + */ + private long mCreatedDate; + + /** + * 是否有附件 + */ + private boolean mHasAttachment; + + /** + * 修改日期 + */ + private long mModifiedDate; + + /** + * 删除日期 + */ + private long mDeletedDate; + + /** + * 笔记数量(用于文件夹) + */ + private int mNotesCount; + + /** + * 父文件夹ID + */ + private long mParentId; + + /** + * 笔记摘要 + */ + private String mSnippet; + + /** + * 笔记类型 + */ + private int mType; + + /** + * 小组件ID + */ + 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; + + /** + * 构造函数,从游标中初始化笔记列表项数据 + * @param context 上下文对象 + * @param cursor 包含笔记数据的游标 + */ + public NoteItemData(Context context, Cursor cursor) { + mId = cursor.getLong(ID_COLUMN); + mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); + mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); + mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); + mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; + mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); + mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); + mParentId = cursor.getLong(PARENT_ID_COLUMN); + mSnippet = cursor.getString(SNIPPET_COLUMN); + // 先替换标签,保留HTML格式以便在列表中显示富文本 + 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); + mPinned = (cursor.getInt(PINNED_COLUMN) > 0) ? true : false; + mIsLocked = (cursor.getInt(IS_LOCKED_COLUMN) > 0) ? true : false; + mLockPassword = cursor.getString(LOCK_PASSWORD_COLUMN); + mLockType = cursor.getInt(LOCK_TYPE_COLUMN); + mDeletedDate = cursor.getLong(DELETED_DATE_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; + } + } + } + + if (mName == null) { + mName = ""; + } + checkPostion(cursor); + } + + /** + * 检查当前项在列表中的位置 + *+ * 该方法用于判断当前项是否为第一项、最后一项、唯一一项,以及是否为文件夹后的笔记 + *
+ * @param cursor 包含笔记数据的游标 + */ + private void checkPostion(Cursor cursor) { + mIsLastItem = cursor.isLast() ? true : false; + mIsFirstItem = cursor.isFirst() ? true : false; + mIsOnlyOneItem = (cursor.getCount() == 1); + 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; + } else { + mIsOneNoteFollowingFolder = true; + } + } + if (!cursor.moveToNext()) { + throw new IllegalStateException("cursor move to previous but can't move back"); + } + } + } + } + + /** + * 判断是否为文件夹后的唯一笔记 + * @return 是否为文件夹后的唯一笔记 + */ + public boolean isOneFollowingFolder() { + return mIsOneNoteFollowingFolder; + } + + /** + * 判断是否为文件夹后的多个笔记 + * @return 是否为文件夹后的多个笔记 + */ + public boolean isMultiFollowingFolder() { + return mIsMultiNotesFollowingFolder; + } + + /** + * 判断是否为最后一项 + * @return 是否为最后一项 + */ + public boolean isLast() { + return mIsLastItem; + } + + /** + * 获取通话记录联系人名称 + * @return 通话记录联系人名称 + */ + public String getCallName() { + return mName; + } + + /** + * 判断是否为第一项 + * @return 是否为第一项 + */ + public boolean isFirst() { + return mIsFirstItem; + } + + /** + * 判断是否为唯一一项 + * @return 是否为唯一一项 + */ + 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 是否有附件 + */ + 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; + } + + /** + * 获取文件夹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 是否有提醒 + */ + public boolean hasAlert() { + return (mAlertDate > 0); + } + + /** + * 判断是否为通话记录 + * @return 是否为通话记录 + */ + public boolean isCallRecord() { + return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); + } + + /** + * 获取置顶状态 + * @return 置顶状态,true表示已置顶,false表示未置顶 + */ + public boolean isPinned() { + return mPinned; + } + + /** + * 设置置顶状态 + * @param pinned 置顶状态,true表示置顶,false表示取消置顶 + */ + public void setPinned(boolean pinned) { + mPinned = pinned; + } + + /** + * 获取锁定状态 + * @return 锁定状态,true表示已锁定,false表示未锁定 + */ + public boolean isLocked() { + return mIsLocked; + } + + /** + * 设置锁定状态 + * @param locked 锁定状态,true表示锁定,false表示解锁 + */ + public void setLocked(boolean locked) { + mIsLocked = locked; + } + + /** + * 获取锁定密码 + * @return 锁定密码 + */ + public String getLockPassword() { + return mLockPassword; + } + + /** + * 设置锁定密码 + * @param password 锁定密码 + */ + public void setLockPassword(String password) { + mLockPassword = password; + } + + /** + * 获取锁定类型 + * @return 锁定类型,0表示笔记,1表示文件夹 + */ + public int getLockType() { + return mLockType; + } + + /** + * 设置锁定类型 + * @param type 锁定类型,0表示笔记,1表示文件夹 + */ + public void setLockType(int type) { + mLockType = type; + } + + /** + * 获取删除日期 + * @return 删除日期,以毫秒为单位 + */ + public long getDeletedDate() { + return mDeletedDate; + } + + /** + * 判断是否为已删除项 + * @return 是否已删除,true表示已删除,false表示未删除 + */ + public boolean isDeleted() { + return (mDeletedDate > 0); + } + + /** + * 获取笔记类型(静态方法) + * @param cursor 包含笔记数据的游标 + * @return 笔记类型 + */ + public static int getNoteType(Cursor cursor) { + return cursor.getInt(TYPE_COLUMN); + } +} diff --git a/src/main/java/net/micode/notes/ui/NotesListActivity.java b/src/main/java/net/micode/notes/ui/NotesListActivity.java new file mode 100644 index 0000000..ae6ab3f --- /dev/null +++ b/src/main/java/net/micode/notes/ui/NotesListActivity.java @@ -0,0 +1,1890 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.appwidget.AppWidgetManager; +import android.content.AsyncQueryHandler; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.os.AsyncTask; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.util.Log; +import android.view.ActionMode; +import android.view.ContextMenu; +import android.view.ContextMenu.ContextMenuInfo; +import android.view.Display; +import android.view.HapticFeedbackConstants; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.View.OnCreateContextMenuListener; +import android.view.View.OnTouchListener; +import android.view.inputmethod.InputMethodManager; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.AdapterView.OnItemLongClickListener; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ListView; +import android.widget.PopupMenu; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.remote.GTaskSyncService; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.tool.BackupUtils; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.HashSet; + +/** + * 笔记列表活动类 + *+ * 该类是应用的主界面,负责显示笔记列表,处理笔记的创建、编辑、删除等操作, + * 支持文件夹管理、笔记同步、导入导出等功能,并提供了多选模式、上下文菜单等交互方式 + *
+ */ +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; + + /** 文件夹删除菜单ID */ + private static final int MENU_FOLDER_DELETE = 0; + + /** 文件夹查看菜单ID */ + private static final int MENU_FOLDER_VIEW = 1; + + /** 文件夹重命名菜单ID */ + private static final int MENU_FOLDER_CHANGE_NAME = 2; + + /** 偏好设置:是否添加了介绍笔记 */ + private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; + + /** + * 列表编辑状态枚举 + *+ * 定义了笔记列表的三种状态: + * 1. NOTE_LIST:根目录下的笔记列表 + * 2. SUB_FOLDER:子文件夹中的笔记列表 + * 3. CALL_RECORD_FOLDER:通话记录文件夹 + *
+ */ + private enum ListEditState { + NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER + } + + /** + * 显示密码输入对话框 + *+ * 该方法用于显示一个密码输入对话框,让用户输入密码来锁定选中的笔记或文件夹 + *
+ */ + private void showPasswordDialog() { + final EditText passwordEditText = new EditText(this); + passwordEditText.setHint(R.string.hint_enter_password); + passwordEditText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); + + new AlertDialog.Builder(this) + .setTitle(R.string.dialog_enter_password) + .setView(passwordEditText) + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + String password = passwordEditText.getText().toString(); + if (!TextUtils.isEmpty(password)) { + toggleLockedStatus(password); + } + } + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); + } + + /** + * 切换锁定状态 + *+ * 该方法用于切换选中笔记或文件夹的锁定状态,使用异步任务处理数据库操作 + *
+ * @param password 用于锁定的密码 + */ + private void toggleLockedStatus(final String password) { + final HashSet+ * 该方法使用Base64和ANDROID_ID对密码进行加密 + *
+ * @param password 原始密码 + * @return 加密后的密码 + */ + private String encryptPassword(String password) { + try { + // 获取设备的ANDROID_ID作为加密密钥 + String androidId = android.provider.Settings.Secure.getString(getContentResolver(), + android.provider.Settings.Secure.ANDROID_ID); + // 使用简单的加密算法:将密码与ANDROID_ID拼接后进行Base64编码 + String combined = password + androidId; + return android.util.Base64.encodeToString(combined.getBytes(), android.util.Base64.DEFAULT); + } catch (Exception e) { + Log.e(TAG, "Password encryption failed", e); + return password; // 加密失败时返回原始密码 + } + }; + + /** 当前列表编辑状态 */ + 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; + + /** 当前文件夹ID */ + private long mCurrentFolderId; + + /** 内容解析器 */ + private ContentResolver mContentResolver; + + /** 模式回调 */ + private ModeCallback mModeCallBack; + + /** 是否分发触摸事件 */ + private boolean mDispatch; + + /** 原始Y坐标 */ + private int mOriginY; + + /** 分发Y坐标 */ + private int mDispatchY; + + /** 日志标签 */ + private static final String TAG = "NotesListActivity"; + + /** 笔记列表视图滚动速率 */ + 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)" + " OR (" + + NoteColumns.ID + "=" + Notes.ID_TRASH_FOLER + ")"; // 添加回收站文件夹到根目录列表 + + /** 打开笔记请求码 */ + private final static int REQUEST_CODE_OPEN_NODE = 102; + /** 新建笔记请求码 */ + private final static int REQUEST_CODE_NEW_NODE = 103; + + /** + * 活动创建时调用 + *+ * 该方法完成以下工作: + * 1. 设置布局文件 + * 2. 初始化资源 + * 3. 如果是首次使用,添加介绍笔记 + *
+ * @param savedInstanceState 保存的实例状态 + */ + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.note_list); + + // 上移底部系统栏,解决写便签按钮与底部系统栏之间的多余间距 + View decorView = getWindow().getDecorView(); + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { + // Android 11+ 使用新的WindowInsetsController API + android.view.WindowInsetsController insetsController = decorView.getWindowInsetsController(); + if (insetsController != null) { + // 隐藏底部导航栏 + insetsController.hide(android.view.WindowInsets.Type.navigationBars()); + // 设置系统栏行为,允许滑动显示 + insetsController.setSystemBarsBehavior( + android.view.WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE); + } + } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { + // Android 4.1-10 使用旧的系统UI可见性API + int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; + decorView.setSystemUiVisibility(uiOptions); + } + + // 添加系统UI可见性变化监听器,确保系统栏保持上移状态 + decorView.setOnSystemUiVisibilityChangeListener( + new View.OnSystemUiVisibilityChangeListener() { + @Override + public void onSystemUiVisibilityChange(int visibility) { + // 当系统UI可见性变化时,重新设置系统UI可见性 + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { + // Android 11+ 使用新API + android.view.WindowInsetsController insetsController = decorView.getWindowInsetsController(); + if (insetsController != null) { + insetsController.hide(android.view.WindowInsets.Type.navigationBars()); + } + } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { + // Android 4.1-10 使用旧API + if ((visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { + int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; + decorView.setSystemUiVisibility(uiOptions); + } + } + } + } + ); + + initResources(); + + /** + * Insert an introduction when user firstly use this application + */ + setAppInfoFromRawRes(); + + // 注册Android 13+的返回键回调 + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) { + getOnBackInvokedDispatcher().registerOnBackInvokedCallback( + android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT, + new android.window.OnBackInvokedCallback() { + @Override + public void onBackInvoked() { + handleBackPress(); + } + } + ); + } + } + + /** + * 处理活动返回结果 + *+ * 该方法在其他活动返回结果时调用,主要用于处理笔记编辑活动返回的结果 + *
+ * @param requestCode 请求码 + * @param resultCode 结果码 + * @param data 返回的数据 + */ + @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); + } 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); + if (in != null) { + InputStreamReader isr = new InputStreamReader(in); + BufferedReader br = new BufferedReader(isr); + char [] buf = new char[1024]; + int len = 0; + while ((len = br.read(buf)) > 0) { + sb.append(buf, 0, len); + } + } else { + Log.e(TAG, "Read introduction file error"); + return; + } + } catch (IOException e) { + e.printStackTrace(); + return; + } finally { + 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); + note.setWorkingText(sb.toString()); + if (note.saveNote()) { + sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); + } else { + Log.e(TAG, "Save introduction note error"); + return; + } + } + } + + /** + * 活动开始时调用 + *+ * 该方法在活动开始时调用,主要用于启动异步笔记列表查询 + *
+ */ + @Override + protected void onStart() { + super.onStart(); + startAsyncNotesListQuery(); + // 启动回收站自动清理任务 + net.micode.notes.worker.TrashCleanupWorker.doCleanup(this); + } + + /** + * 初始化资源 + *+ * 该方法完成以下工作: + * 1. 初始化内容解析器和后台查询处理器 + * 2. 设置当前文件夹ID为根文件夹ID + * 3. 初始化笔记列表视图,添加页脚,设置点击和长按监听器 + * 4. 初始化笔记列表适配器并设置给列表视图 + * 5. 初始化新建笔记按钮,设置点击和触摸监听器 + * 6. 初始化触摸事件相关变量 + * 7. 初始化标题栏和状态 + * 8. 初始化模式回调 + *
+ */ + private void initResources() { + mContentResolver = this.getContentResolver(); + mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); + 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); + mNotesListView.setAdapter(mNotesListAdapter); + mAddNewNote = (Button) findViewById(R.id.btn_new_note); + mAddNewNote.setOnClickListener(this); + mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); + mDispatch = false; + mDispatchY = 0; + mOriginY = 0; + mTitleBar = (TextView) findViewById(R.id.tv_title_bar); + mState = ListEditState.NOTE_LIST; + mModeCallBack = new ModeCallback(); + } + + /** + * 多选模式回调类 + *+ * 该类实现了ListView.MultiChoiceModeListener和OnMenuItemClickListener接口, + * 用于处理多选模式下的操作,包括创建模式、更新菜单、处理菜单点击事件等 + *
+ */ + private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { + /** 下拉菜单 */ + private DropdownMenu mDropDownMenu; + /** 动作模式 */ + private ActionMode mActionMode; + /** 移动菜单 */ + private MenuItem mMoveMenu; + + /** + * 创建动作模式 + *+ * 该方法完成以下工作: + * 1. 加载菜单资源 + * 2. 设置删除菜单的点击监听器 + * 3. 根据当前文件夹ID和用户文件夹数量设置移动菜单或恢复菜单的可见性 + * 4. 保存动作模式实例 + * 5. 设置列表适配器为选择模式 + * 6. 禁用列表的长按功能 + * 7. 隐藏新建笔记按钮 + * 8. 设置自定义视图 + * 9. 创建下拉菜单 + * 10. 设置下拉菜单的点击监听器 + *
+ * @param mode 动作模式 + * @param menu 菜单 + * @return 是否创建成功,返回true表示成功 + */ + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + getMenuInflater().inflate(R.menu.note_list_options, menu); + menu.findItem(R.id.delete).setOnMenuItemClickListener(this); + + if (mCurrentFolderId == Notes.ID_TRASH_FOLER) { + // 在回收站内部,显示恢复按钮 + MenuItem restoreMenu = menu.findItem(R.id.restore); + if (restoreMenu != null) { + restoreMenu.setVisible(true); + restoreMenu.setOnMenuItemClickListener(this); + } + // 隐藏移动按钮 + MenuItem moveMenu = menu.findItem(R.id.move); + if (moveMenu != null) { + moveMenu.setVisible(false); + } + } else { + // 在回收站外部,显示移动按钮 + mMoveMenu = menu.findItem(R.id.move); + if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER + || DataUtils.getUserFolderCount(mContentResolver) == 0) { + mMoveMenu.setVisible(false); + } else { + mMoveMenu.setVisible(true); + mMoveMenu.setOnMenuItemClickListener(this); + } + // 隐藏恢复按钮 + MenuItem restoreMenu = menu.findItem(R.id.restore); + if (restoreMenu != null) { + restoreMenu.setVisible(false); + } + } + + // 添加置顶菜单初始化 + MenuItem pinMenu = menu.findItem(R.id.pin); + if (pinMenu != null) { + pinMenu.setOnMenuItemClickListener(this); + } + // 添加锁定菜单初始化 + MenuItem lockMenu = menu.findItem(R.id.lock); + if (lockMenu != null) { + lockMenu.setOnMenuItemClickListener(this); + } + mActionMode = mode; + mNotesListAdapter.setChoiceMode(true); + 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(){ + public boolean onMenuItemClick(MenuItem item) { + mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); + updateMenu(); + return true; + } + + }); + return true; + } + + /** + * 更新菜单 + *+ * 该方法完成以下工作: + * 1. 获取选中的笔记数量 + * 2. 更新下拉菜单的标题,显示选中数量 + * 3. 更新全选/取消全选菜单项的状态和标题 + *
+ */ + 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); + if (item != null) { + if (mNotesListAdapter.isAllSelected()) { + item.setChecked(true); + item.setTitle(R.string.menu_deselect_all); + } else { + item.setChecked(false); + item.setTitle(R.string.menu_select_all); + } + } + } + + /** + * 准备动作模式 + *+ * 该方法未实现具体功能,返回false + *
+ * @param mode 动作模式 + * @param menu 菜单 + * @return 是否准备成功,返回false + */ + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + // TODO Auto-generated method stub + return false; + } + + /** + * 处理动作模式菜单项点击事件 + *+ * 该方法未实现具体功能,返回false + *
+ * @param mode 动作模式 + * @param item 菜单项 + * @return 是否处理成功,返回false + */ + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + // TODO Auto-generated method stub + return false; + } + + /** + * 销毁动作模式 + *+ * 该方法完成以下工作: + * 1. 设置列表适配器为非选择模式 + * 2. 启用列表的长按功能 + * 3. 显示新建笔记按钮 + *
+ * @param mode 动作模式 + */ + public void onDestroyActionMode(ActionMode mode) { + mNotesListAdapter.setChoiceMode(false); + mNotesListView.setLongClickable(true); + mAddNewNote.setVisibility(View.VISIBLE); + } + + /** + * 结束动作模式 + *+ * 该方法调用动作模式的finish方法来结束多选模式 + *
+ */ + public void finishActionMode() { + mActionMode.finish(); + } + + /** + * 列表项选中状态变化时调用 + *+ * 该方法完成以下工作: + * 1. 设置列表项的选中状态 + * 2. 更新菜单 + *
+ * @param mode 动作模式 + * @param position 列表项位置 + * @param id 列表项ID + * @param checked 是否选中 + */ + public void onItemCheckedStateChanged(ActionMode mode, int position, long id, + boolean checked) { + mNotesListAdapter.setCheckedItem(position, checked); + updateMenu(); + } + + /** + * 处理菜单项点击事件 + *+ * 该方法完成以下工作: + * 1. 检查是否有选中的笔记,如果没有则显示提示 + * 2. 根据菜单项ID处理不同的操作: + * - 删除:显示删除确认对话框,点击确定后调用batchDelete方法 + * - 移动:调用startQueryDestinationFolders方法查询目标文件夹 + * - 恢复:调用batchRestore方法恢复选中的项目 + *
+ * @param item 菜单项 + * @return 是否处理成功,返回true表示成功 + */ + public boolean onMenuItemClick(MenuItem item) { + if (mNotesListAdapter.getSelectedCount() == 0) { + Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), + Toast.LENGTH_SHORT).show(); + return true; + } + + switch (item.getItemId()) { + case R.id.delete: + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + + if (mCurrentFolderId == Notes.ID_TRASH_FOLER) { + // 在回收站内部,提示永久删除 + 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_permanently, + mNotesListAdapter.getSelectedCount())); + } else { + // 在回收站外部,提示移动到回收站 + 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())); + } + + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + batchDelete(); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case R.id.move: + startQueryDestinationFolders(); + break; + case R.id.restore: + // 恢复选中的项目 + batchRestore(); + break; + case R.id.pin: + togglePinnedStatus(); + break; + case R.id.lock: + showPasswordDialog(); + break; + default: + return false; + } + return true; + } + } + + /** + * 新建笔记按钮触摸监听器 + *+ * 该类实现了OnTouchListener接口,用于处理新建笔记按钮的触摸事件, + * 特别是处理按钮透明部分的触摸事件,将其分发给下方的列表视图 + *
+ */ + private class NewNoteOnTouchListener implements OnTouchListener { + + /** + * 处理触摸事件 + *+ * 该方法完成以下工作: + * 1. 处理ACTION_DOWN事件: + * - 获取屏幕高度和新建笔记按钮高度 + * - 计算触摸事件的Y坐标 + * - 如果当前状态是SUB_FOLDER,减去标题栏高度 + * - 检查触摸点是否在按钮的透明部分(根据公式y=-0.12x+94判断) + * - 如果是,将触摸事件分发给下方的列表视图 + * 2. 处理ACTION_MOVE事件: + * - 如果已经开始分发事件,更新事件坐标并继续分发给列表视图 + * 3. 处理其他事件: + * - 如果已经开始分发事件,结束分发并将事件分发给列表视图 + *
+ * @param v 被触摸的视图 + * @param event 触摸事件 + * @return 是否消费了该事件,返回true表示已消费 + */ + public boolean onTouch(View v, MotionEvent event) { + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: { + Display display = getWindowManager().getDefaultDisplay(); + int screenHeight = display.getHeight(); + 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. + */ + if (event.getY() < (event.getX() * (-0.12) + 94)) { + View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 + - mNotesListView.getFooterViewsCount()); + if (view != null && view.getBottom() > start + && (view.getTop() < (start + 94))) { + mOriginY = (int) event.getY(); + mDispatchY = eventY; + event.setLocation(event.getX(), mDispatchY); + mDispatch = true; + return mNotesListView.dispatchTouchEvent(event); + } + } + break; + } + case MotionEvent.ACTION_MOVE: { + if (mDispatch) { + mDispatchY += (int) event.getY() - mOriginY; + event.setLocation(event.getX(), mDispatchY); + return mNotesListView.dispatchTouchEvent(event); + } + break; + } + default: { + if (mDispatch) { + event.setLocation(event.getX(), mDispatchY); + mDispatch = false; + return mNotesListView.dispatchTouchEvent(event); + } + break; + } + } + return false; + } + + }; + + /** + * 启动异步笔记列表查询 + *+ * 该方法根据当前文件夹ID选择合适的查询条件,然后启动异步查询,查询结果将通过BackgroundQueryHandler返回 + *
+ */ + 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) + }, NoteColumns.PINNED + " DESC," + NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); + } + + /** + * 后台查询处理器类 + *+ * 该类继承自AsyncQueryHandler,用于处理异步查询操作, + * 主要处理两种查询: + * 1. 文件夹笔记列表查询 + * 2. 文件夹列表查询 + *
+ */ + private final class BackgroundQueryHandler extends AsyncQueryHandler { + /** + * 构造函数 + * @param contentResolver 内容解析器 + */ + public BackgroundQueryHandler(ContentResolver contentResolver) { + super(contentResolver); + } + + /** + * 查询完成时调用 + *+ * 该方法根据查询令牌处理查询结果: + * 1. 如果是文件夹笔记列表查询,将结果游标设置给列表适配器 + * 2. 如果是文件夹列表查询,显示文件夹列表菜单 + *
+ * @param token 查询令牌,用于标识查询类型 + * @param cookie 查询时传递的附加数据,此处未使用 + * @param cursor 查询结果游标 + */ + @Override + protected void onQueryComplete(int token, Object cookie, Cursor cursor) { + switch (token) { + case FOLDER_NOTE_LIST_QUERY_TOKEN: + mNotesListAdapter.changeCursor(cursor); + break; + case FOLDER_LIST_QUERY_TOKEN: + if (cursor != null && cursor.getCount() > 0) { + showFolderListMenu(cursor); + } else { + Log.e(TAG, "Query folder failed"); + } + break; + default: + return; + } + } + } + + private void showFolderListMenu(Cursor cursor) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(R.string.menu_title_select_folder); + final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); + builder.setAdapter(adapter, new DialogInterface.OnClickListener() { + + public void onClick(DialogInterface dialog, int which) { + DataUtils.batchMoveToFolder(mContentResolver, + mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); + Toast.makeText( + NotesListActivity.this, + getString(R.string.format_move_notes_to_folder, + mNotesListAdapter.getSelectedCount(), + adapter.getFolderName(NotesListActivity.this, which)), + Toast.LENGTH_SHORT).show(); + mModeCallBack.finishActionMode(); + } + }); + builder.show(); + } + + /** + * 创建新笔记 + *+ * 该方法通过启动NoteEditActivity来创建新笔记,并传递当前文件夹ID作为额外参数 + *
+ */ + private void createNewNote() { + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); + this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); + } + + /** + * 批量删除笔记 + *+ * 该方法在异步任务中完成以下工作: + * 1. 获取选中的部件属性 + * 2. 如果当前在回收站内部,直接永久删除选中的笔记 + * 3. 如果当前不在回收站内部,将选中的笔记移动到回收站 + * 4. 更新相关部件 + * 5. 结束多选模式 + *
+ */ + private void batchDelete() { + new AsyncTask+ * 该方法在异步任务中完成以下工作: + * 1. 获取选中的项目ID + * 2. 对于每个项目,查询其原始父文件夹ID + * 3. 将项目移动回原始父文件夹(如果原始父文件夹不存在或也在回收站中,则移动到根文件夹) + * 4. 更新相关部件 + * 5. 结束动作模式 + *
+ */ + private void batchRestore() { + new AsyncTask+ * 该方法完成以下工作: + * 1. 检查文件夹ID是否为根文件夹ID,如果是则返回错误 + * 2. 获取文件夹的部件属性 + * 3. 如果文件夹在回收站外部,将其移动到回收站 + * 4. 如果文件夹在回收站内部,直接永久删除 + * 5. 更新相关部件 + *
+ * @param folderId 要删除的文件夹ID + */ + private void deleteFolder(long folderId) { + if (folderId == Notes.ID_ROOT_FOLDER) { + Log.e(TAG, "Wrong folder id, should not happen " + folderId); + return; + } + + HashSet+ * 该方法通过启动NoteEditActivity来打开指定的笔记,传递笔记ID作为额外参数 + *
+ * @param data 要打开的笔记数据项 + */ + private void openNode(final NoteItemData data) { + // 检查笔记是否被锁定 + if (data.isLocked()) { + final EditText passwordEditText = new EditText(this); + passwordEditText.setHint(R.string.hint_enter_password); + passwordEditText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); + + new AlertDialog.Builder(this) + .setTitle(R.string.dialog_enter_password) + .setView(passwordEditText) + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + String password = passwordEditText.getText().toString(); + if (!TextUtils.isEmpty(password)) { + verifyPasswordAndOpenNote(data.getId(), password); + } + } + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); + } else { + // 未锁定,直接打开笔记 + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, data.getId()); + startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); + } + } + + /** + * 验证密码并打开笔记 + *+ * 该方法完成以下工作: + * 1. 查询笔记的加密密码 + * 2. 验证密码是否正确 + * 3. 如果正确,打开笔记;否则显示错误信息 + *
+ * @param noteId 笔记ID + * @param password 用户输入的密码 + */ + private void verifyPasswordAndOpenNote(final long noteId, String password) { + // 查询笔记的加密密码 + String[] projection = {NoteColumns.LOCK_PASSWORD}; + String selection = NoteColumns.ID + "=?"; + String[] selectionArgs = {String.valueOf(noteId)}; + + Cursor cursor = getContentResolver().query(Notes.CONTENT_NOTE_URI, projection, selection, selectionArgs, null); + String encryptedPassword = null; + + if (cursor != null && cursor.moveToFirst()) { + encryptedPassword = cursor.getString(0); + cursor.close(); + } + + // 验证密码是否正确 + if (encryptedPassword != null && encryptedPassword.equals(encryptPassword(password))) { + // 密码正确,打开笔记 + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, noteId); + startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); + } else { + // 密码错误,显示错误信息 + Toast.makeText(this, getString(R.string.error_wrong_password), Toast.LENGTH_SHORT).show(); + } + } + + /** + * 打开文件夹 + *+ * 该方法完成以下工作: + * 1. 设置当前文件夹ID + * 2. 启动异步笔记列表查询 + * 3. 根据文件夹类型设置列表状态: + * - 如果是通话记录文件夹,设置为CALL_RECORD_FOLDER状态并隐藏新建笔记按钮 + * - 否则设置为SUB_FOLDER状态 + * 4. 设置标题栏文本和可见性 + *
+ * @param data 要打开的文件夹数据项 + */ + private void openFolder(NoteItemData data) { + mCurrentFolderId = data.getId(); + 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 { + mTitleBar.setText(data.getSnippet()); + } + mTitleBar.setVisibility(View.VISIBLE); + } + + /** + * 处理点击事件 + *+ * 该方法处理视图的点击事件,目前只处理新建笔记按钮的点击事件 + *
+ * @param v 被点击的视图 + */ + public void onClick(View v) { + switch (v.getId()) { + case R.id.btn_new_note: + createNewNote(); + break; + default: + break; + } + } + + /** + * 显示软键盘 + *+ * 该方法通过InputMethodManager显示软键盘 + *
+ */ + private void showSoftInput() { + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + if (inputMethodManager != null) { + inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); + } + } + + /** + * 隐藏软键盘 + *+ * 该方法通过InputMethodManager隐藏软键盘 + *
+ * @param view 用于获取窗口令牌的视图 + */ + private void hideSoftInput(View view) { + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); + } + + /** + * 显示创建或修改文件夹对话框 + *+ * 该方法完成以下工作: + * 1. 创建对话框构建器 + * 2. 加载布局文件 + * 3. 显示软键盘 + * 4. 根据create参数设置对话框标题和编辑框内容: + * - 如果是修改文件夹,设置标题为"修改文件夹名称",并显示当前文件夹名称 + * - 如果是创建文件夹,设置标题为"创建文件夹",并清空编辑框 + * 5. 设置对话框按钮和点击事件 + * 6. 显示对话框 + * 7. 为确定按钮设置点击事件,处理文件夹的创建或修改 + * 8. 为编辑框添加文本变化监听器,当文本为空时禁用确定按钮 + *
+ * @param create 是否是创建文件夹,true表示创建,false表示修改 + */ + 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); + final EditText etName = (EditText) view.findViewById(R.id.et_foler_name); + showSoftInput(); + if (!create) { + if (mFocusNoteDataItem != null) { + etName.setText(mFocusNoteDataItem.getSnippet()); + builder.setTitle(getString(R.string.menu_folder_change_name)); + } else { + Log.e(TAG, "The long click data item is null"); + return; + } + } else { + etName.setText(""); + builder.setTitle(this.getString(R.string.menu_create_folder)); + } + + builder.setPositiveButton(android.R.string.ok, null); + builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + hideSoftInput(etName); + } + }); + + final Dialog dialog = builder.setView(view).show(); + final Button positive = (Button)dialog.findViewById(android.R.id.button1); + positive.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + hideSoftInput(etName); + String name = etName.getText().toString(); + if (DataUtils.checkVisibleFolderName(mContentResolver, name, mCurrentFolderId)) { + Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), + Toast.LENGTH_LONG).show(); + etName.setSelection(0, etName.length()); + return; + } + 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()) + }); + } + } else if (!TextUtils.isEmpty(name)) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.SNIPPET, name); + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + values.put(NoteColumns.PARENT_ID, mCurrentFolderId); + mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); + } + dialog.dismiss(); + } + }); + + 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 onTextChanged(CharSequence s, int start, int before, int count) { + if (TextUtils.isEmpty(etName.getText())) { + positive.setEnabled(false); + } else { + positive.setEnabled(true); + } + } + + public void afterTextChanged(Editable s) { + // TODO Auto-generated method stub + + } + }); + } + + /** + * 处理返回按钮点击事件 + *+ * 该方法根据当前状态处理返回按钮点击事件: + * 1. 如果在子文件夹中,返回根文件夹 + * 2. 如果在通话记录文件夹中,返回根文件夹并显示新建笔记按钮 + * 3. 如果在根文件夹中,调用默认的返回处理 + *
+ */ + private void handleBackPress() { + switch (mState) { + case SUB_FOLDER: + // 查询当前文件夹的父文件夹ID + Cursor cursor = mContentResolver.query(Notes.CONTENT_NOTE_URI, + new String[]{NoteColumns.PARENT_ID, NoteColumns.SNIPPET}, + NoteColumns.ID + "=?", + new String[]{String.valueOf(mCurrentFolderId)}, + null); + + if (cursor != null && cursor.moveToFirst()) { + long parentId = cursor.getLong(0); + String parentName = cursor.getString(1); + cursor.close(); + + if (parentId == Notes.ID_ROOT_FOLDER) { + // 如果父文件夹是根文件夹,返回根目录 + mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mState = ListEditState.NOTE_LIST; + mTitleBar.setVisibility(View.GONE); + } else { + // 否则返回上一级文件夹 + mCurrentFolderId = parentId; + mState = ListEditState.SUB_FOLDER; + mTitleBar.setText(parentName); + mTitleBar.setVisibility(View.VISIBLE); + } + startAsyncNotesListQuery(); + } + break; + case CALL_RECORD_FOLDER: + mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mState = ListEditState.NOTE_LIST; + mAddNewNote.setVisibility(View.VISIBLE); + mTitleBar.setVisibility(View.GONE); + startAsyncNotesListQuery(); + break; + case NOTE_LIST: + super.onBackPressed(); + break; + default: + break; + } + } + + @Override + public void onBackPressed() { + handleBackPress(); + } + + /** + * 更新部件 + *+ * 该方法完成以下工作: + * 1. 创建广播意图 + * 2. 根据部件类型设置广播接收者: + * - 如果是2x2部件,设置接收者为NoteWidgetProvider_2x + * - 如果是4x4部件,设置接收者为NoteWidgetProvider_4x + * - 否则记录错误并返回 + * 3. 添加部件ID到意图中 + * 4. 发送广播 + * 5. 设置结果 + *
+ * @param appWidgetId 部件ID + * @param appWidgetType 部件类型 + */ + 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) { + intent.setClass(this, NoteWidgetProvider_4x.class); + } else { + Log.e(TAG, "Unspported widget type"); + return; + } + + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { + 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) { + menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); + menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); + menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); + menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name); + } + } + }; + + @Override + public void onContextMenuClosed(Menu menu) { + if (mNotesListView != null) { + mNotesListView.setOnCreateContextMenuListener(null); + } + super.onContextMenuClosed(menu); + } + + @Override + public boolean onContextItemSelected(MenuItem item) { + if (mFocusNoteDataItem == null) { + Log.e(TAG, "The long click data item is null"); + return false; + } + switch (item.getItemId()) { + case MENU_FOLDER_VIEW: + 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); + builder.setMessage(getString(R.string.alert_message_delete_folder)); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteFolder(mFocusNoteDataItem.getId()); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case MENU_FOLDER_CHANGE_NAME: + showCreateOrModifyFolderDialog(false); + break; + default: + break; + } + + return true; + } + + @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 + menu.findItem(R.id.menu_sync).setTitle( + GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); + } else if (mState == ListEditState.SUB_FOLDER) { + getMenuInflater().inflate(R.menu.sub_folder, menu); + } else if (mState == ListEditState.CALL_RECORD_FOLDER) { + getMenuInflater().inflate(R.menu.call_record_folder, menu); + } else { + Log.e(TAG, "Wrong state:" + mState); + } + return true; + } + + /** + * 处理选项菜单点击事件 + *+ * 该方法处理以下菜单项的点击事件: + * 1. 新建文件夹:显示创建文件夹对话框 + * 2. 导出文本:调用exportNoteToText方法导出笔记 + * 3. 同步: + * - 如果在同步模式下,根据当前标题判断是开始同步还是取消同步 + * - 否则跳转到设置页面 + * 4. 设置:跳转到设置页面 + * 5. 新建笔记:调用createNewNote方法创建新笔记 + * 6. 搜索:调用onSearchRequested方法启动搜索 + *
+ * @param item 被点击的菜单项 + * @return 是否处理了该事件,返回true表示已处理 + */ + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_new_folder: { + showCreateOrModifyFolderDialog(true); + break; + } + case R.id.menu_export_text: { + exportNoteToText(); + break; + } + case R.id.menu_sync: { + if (isSyncMode()) { + if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { + GTaskSyncService.startSync(this); + } else { + GTaskSyncService.cancelSync(this); + } + } else { + startPreferenceActivity(); + } + break; + } + case R.id.menu_setting: { + startPreferenceActivity(); + break; + } + case R.id.menu_new_note: { + createNewNote(); + break; + } + case R.id.menu_search: + onSearchRequested(); + break; + default: + break; + } + return true; + } + + /** + * 处理搜索请求 + *+ * 该方法启动搜索活动 + *
+ * @return 是否处理了搜索请求,返回true表示已处理 + */ + @Override + public boolean onSearchRequested() { + startSearch(null, false, null /* appData */, false); + return true; + } + + /** + * 导出笔记到文本文件 + *+ * 该方法在异步任务中完成以下工作: + * 1. 获取BackupUtils实例 + * 2. 在后台调用exportToText方法导出笔记 + * 3. 根据导出结果显示不同的对话框: + * - 如果SD卡未挂载,显示失败对话框 + * - 如果导出成功,显示成功对话框并显示导出文件的位置 + * - 如果系统错误,显示失败对话框 + *
+ */ + private void exportNoteToText() { + final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); + new AsyncTask+ * 该方法通过获取同步账户名来检查是否处于同步模式,如果同步账户名不为空则处于同步模式 + *
+ * @return 是否处于同步模式,true表示处于同步模式,false表示不处于同步模式 + */ + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + /** + * 启动偏好设置活动 + *+ * 该方法完成以下工作: + * 1. 获取当前活动或父活动 + * 2. 创建意图,跳转到NotesPreferenceActivity + * 3. 启动活动 + *
+ */ + private void startPreferenceActivity() { + Activity from = getParent() != null ? getParent() : this; + Intent intent = new Intent(from, NotesPreferenceActivity.class); + from.startActivityIfNeeded(intent, -1); + } + + /** + * 列表项点击监听器类 + *+ * 该类实现了OnItemClickListener接口,用于处理列表项的点击事件, + * 根据当前状态和点击的列表项类型执行不同的操作 + *
+ */ + private class OnListItemClickListener implements OnItemClickListener { + + /** + * 处理列表项点击事件 + *+ * 该方法完成以下工作: + * 1. 检查被点击的视图是否是NotesListItem + * 2. 获取被点击的笔记数据项 + * 3. 如果在选择模式下: + * - 如果是笔记类型,切换选中状态 + * - 返回 + * 4. 根据当前状态和笔记类型执行不同的操作: + * - NOTE_LIST状态: + * - 如果是文件夹或系统类型,调用openFolder方法打开文件夹 + * - 如果是笔记类型,调用openNode方法打开笔记 + * - SUB_FOLDER或CALL_RECORD_FOLDER状态: + * - 如果是笔记类型,调用openNode方法打开笔记 + *
+ * @param parent 父视图 + * @param view 被点击的视图 + * @param position 被点击的位置 + * @param id 被点击的ID + */ + 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.getId() != Notes.ID_ROOT_FOLDER) { + position = position - mNotesListView.getHeaderViewsCount(); + mModeCallBack.onItemCheckedStateChanged(null, position, id, + !mNotesListAdapter.isSelectedItem(position)); + } + return; + } + + switch (mState) { + case NOTE_LIST: + if (item.getType() == Notes.TYPE_FOLDER + || item.getType() == Notes.TYPE_SYSTEM) { + openFolder(item); + } else if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); + } else { + Log.e(TAG, "Wrong note type in NOTE_LIST"); + } + break; + case SUB_FOLDER: + if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); + } else if (item.getType() == Notes.TYPE_FOLDER) { + openFolder(item); + } else { + Log.e(TAG, "Wrong note type in SUB_FOLDER"); + } + break; + case CALL_RECORD_FOLDER: + if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); + } else { + Log.e(TAG, "Wrong note type in CALL_RECORD_FOLDER"); + } + break; + default: + break; + } + } + } + + } + + /** + * 启动查询目标文件夹 + *+ * 该方法完成以下工作: + * 1. 构建查询条件: + * - 基本条件:类型为文件夹,父ID不等于回收站ID,ID不等于当前文件夹ID + * - 如果当前状态不是NOTE_LIST,添加根文件夹ID到条件中 + * 2. 启动异步查询,查询结果将通过BackgroundQueryHandler返回 + *
+ */ + 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 + ")"; + + mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, + null, + Notes.CONTENT_NOTE_URI, + FoldersListAdapter.PROJECTION, + selection, + new String[] { + String.valueOf(Notes.TYPE_FOLDER), + String.valueOf(Notes.ID_TRASH_FOLER), + String.valueOf(mCurrentFolderId) + }, + NoteColumns.MODIFIED_DATE + " DESC"); + } + + /** + * 处理列表项长按事件 + *+ * 该方法完成以下工作: + * 1. 检查被长按的视图是否是NotesListItem + * 2. 获取被长按的笔记数据项 + * 3. 根据笔记类型处理长按事件: + * - 如果是笔记类型且不在选择模式下,启动多选模式并选中当前项 + * - 如果是文件夹类型,设置上下文菜单监听器 + * 4. 返回false表示事件未被完全处理 + *
+ * @param parent 父视图 + * @param view 被长按的视图 + * @param position 被长按的位置 + * @param id 被长按的ID + * @return 是否处理了该事件,返回false表示事件未被完全处理 + */ + 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); + } else { + Log.e(TAG, "startActionMode fails"); + } + } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { + mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); + } + } + return false; + } +} diff --git a/src/main/java/net/micode/notes/ui/NotesListAdapter.java b/src/main/java/net/micode/notes/ui/NotesListAdapter.java new file mode 100644 index 0000000..5b1a583 --- /dev/null +++ b/src/main/java/net/micode/notes/ui/NotesListAdapter.java @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.util.Log; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; + +import net.micode.notes.data.Notes; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; + + +/** + * 笔记列表适配器类 + *+ * 该类是CursorAdapter的子类,用于将数据库中的笔记数据绑定到列表视图上, + * 支持普通浏览模式和选择模式,能够管理选中的项目,并提供了各种方法来处理 + * 列表项的选择状态、获取选中项目ID等功能。 + *
+ */ +public class NotesListAdapter extends CursorAdapter { + /** 日志标签 */ + private static final String TAG = "NotesListAdapter"; + /** 上下文对象 */ + private Context mContext; + /** 保存选中项目的位置和状态 */ + private HashMap+ * 该类用于存储桌面组件的相关属性,包括组件ID和组件类型 + *
+ */ + public static class AppWidgetAttribute { + /** 桌面组件ID */ + public int widgetId; + /** 桌面组件类型 */ + public int widgetType; + }; + + /** + * 构造函数 + *+ * 初始化NotesListAdapter,创建选中项目的映射表,并设置初始上下文和笔记数量 + *
+ * @param context 上下文对象 + */ + public NotesListAdapter(Context context) { + super(context, null); + mSelectedIndex = new HashMap+ * 该方法在需要为新的数据项创建视图时调用,返回一个新的NotesListItem实例 + *
+ * @param context 上下文对象 + * @param cursor 数据游标 + * @param parent 父视图组 + * @return 新创建的列表项视图 + */ + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new NotesListItem(context); + } + + /** + * 将数据绑定到列表项视图 + *+ * 该方法在需要将数据绑定到现有视图时调用,将游标中的数据转换为NoteItemData对象, + * 并调用NotesListItem的bind方法将数据绑定到视图上 + *
+ * @param view 要绑定数据的视图 + * @param context 上下文对象 + * @param cursor 数据游标 + */ + @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())); + } + } + + /** + * 设置指定位置的项是否被选中 + *+ * 该方法用于在选择模式下设置指定位置的项的选中状态,并通知数据集变化 + *
+ * @param position 项的位置 + * @param checked 是否被选中 + */ + public void setCheckedItem(final int position, final boolean checked) { + mSelectedIndex.put(position, checked); + notifyDataSetChanged(); + } + + /** + * 检查是否处于选择模式 + * @return 是否处于选择模式 + */ + public boolean isInChoiceMode() { + return mChoiceMode; + } + + /** + * 设置是否进入选择模式 + *+ * 该方法用于切换选择模式,进入选择模式时会清除之前的选中状态 + *
+ * @param mode 是否进入选择模式 + */ + public void setChoiceMode(boolean mode) { + mSelectedIndex.clear(); + mChoiceMode = mode; + } + + /** + * 全选或取消全选 + *+ * 该方法用于在选择模式下全选或取消全选所有普通笔记项 + * 在回收站内部时,也会选择文件夹类型的项 + *
+ * @param checked 是否全选 + */ + public void selectAll(boolean checked) { + Cursor cursor = getCursor(); + for (int i = 0; i < getCount(); i++) { + if (cursor.moveToPosition(i)) { + // 获取当前项的类型 + int noteType = NoteItemData.getNoteType(cursor); + // 获取当前项的父文件夹ID + cursor.moveToPosition(i); + long parentId = cursor.getLong(8); // PARENT_ID列的索引是8 + + // 在回收站内部时,选择所有类型的项(除了根文件夹) + if (parentId == Notes.ID_TRASH_FOLER || noteType == Notes.TYPE_NOTE) { + setCheckedItem(i, checked); + } + } + } + } + + /** + * 获取所有选中项的ID + *+ * 该方法用于获取选择模式下所有选中项的ID集合,排除根文件夹ID + *
+ * @return 选中项的ID集合 + */ + public HashSet+ * 该方法用于获取选择模式下所有选中的桌面组件的属性集合 + *
+ * @return 选中的桌面组件属性集合,若获取失败则返回null + */ + public HashSet+ * 该方法在数据内容发生变化时被调用,会重新计算笔记数量 + *
+ */ + @Override + protected void onContentChanged() { + super.onContentChanged(); + calcNotesCount(); + } + + /** + * 更换数据游标 + *+ * 该方法在更换数据游标时被调用,会重新计算笔记数量 + *
+ * @param cursor 新的数据游标 + */ + @Override + public void changeCursor(Cursor cursor) { + super.changeCursor(cursor); + calcNotesCount(); + } + + /** + * 计算笔记数量 + *+ * 该方法用于统计当前数据集中的普通笔记数量,并更新mNotesCount成员变量 + *
+ */ + private void calcNotesCount() { + mNotesCount = 0; + Cursor cursor = getCursor(); + if (cursor != null && !cursor.isClosed()) { + // 使用 try-finally 块确保 cursor 位置正确恢复 + int originalPosition = cursor.getPosition(); + try { + if (cursor.moveToFirst()) { + do { + try { + if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { + mNotesCount++; + } + } catch (Exception e) { + // 捕获可能的异常,避免崩溃 + Log.e(TAG, "Error calculating note count: " + e.getMessage()); + break; + } + } while (cursor.moveToNext()); + } + } finally { + // 恢复 cursor 到原始位置 + if (!cursor.isClosed()) { + cursor.moveToPosition(originalPosition); + } + } + } + } +} diff --git a/src/main/java/net/micode/notes/ui/NotesListItem.java b/src/main/java/net/micode/notes/ui/NotesListItem.java new file mode 100644 index 0000000..069771a --- /dev/null +++ b/src/main/java/net/micode/notes/ui/NotesListItem.java @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.text.Html; +import android.text.format.DateUtils; +import android.view.View; +import android.widget.CheckBox; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser.NoteItemBgResources; + + +/** + * 笔记列表项视图类 + *+ * 该类用于显示笔记列表中的单个条目,包含笔记的标题、时间、提醒图标等UI元素, + * 并能根据不同的笔记类型(普通笔记、文件夹、通话记录)和状态(选择模式、是否有提醒) + * 进行动态展示和样式调整 + *
+ */ +public class NotesListItem extends LinearLayout { + /** 提醒图标,用于显示笔记是否设置了提醒 */ + private ImageView mAlert; + /** 笔记标题文本视图 */ + private TextView mTitle; + /** 笔记时间文本视图 */ + private TextView mTime; + /** 通话记录名称文本视图 */ + private TextView mCallName; + /** 列表项数据对象,存储笔记的相关信息 */ + private NoteItemData mItemData; + /** 选择框,用于选择模式下选择笔记 */ + private CheckBox mCheckBox; + + /** + * 构造函数 + *+ * 初始化NotesListItem视图,加载布局文件并获取各个UI组件的引用 + *
+ * @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); + mCallName = (TextView) findViewById(R.id.tv_name); + mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); + } + + /** + * 将笔记数据绑定到列表项视图 + *+ * 该方法根据笔记数据的类型和状态,动态调整列表项的UI显示,包括: + * 1. 根据选择模式和笔记类型决定是否显示复选框 + * 2. 根据笔记类型(通话记录文件夹、普通通话记录、普通笔记、文件夹)设置不同的UI样式 + * 3. 设置标题、时间、提醒图标等内容 + * 4. 调用setBackground方法设置背景样式 + *
+ * @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); + } else { + mCheckBox.setVisibility(View.GONE); + } + + mItemData = data; + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { + mCallName.setVisibility(View.GONE); + mAlert.setVisibility(View.VISIBLE); + mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); + 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.getId() == Notes.ID_TRASH_FOLER) { + mCallName.setVisibility(View.GONE); + mAlert.setVisibility(View.VISIBLE); + mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); + mTitle.setText("回收站" + + context.getString(R.string.format_folder_files_count, data.getNotesCount())); + mAlert.setImageResource(R.drawable.delete); + } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { + mCallName.setVisibility(View.VISIBLE); + mCallName.setText(data.getCallName()); + mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); + mTitle.setText(Html.fromHtml(DataUtils.getFormattedSnippet(data.getSnippet()))); + if (data.hasAlert()) { + mAlert.setImageResource(R.drawable.clock); + mAlert.setVisibility(View.VISIBLE); + } else { + mAlert.setVisibility(View.GONE); + } + } 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())); + mAlert.setVisibility(View.GONE); + } else { + mTitle.setText(Html.fromHtml(DataUtils.getFormattedSnippet(data.getSnippet()))); + if (data.hasAlert()) { + mAlert.setImageResource(R.drawable.clock); + mAlert.setVisibility(View.VISIBLE); + } else { + mAlert.setVisibility(View.GONE); + } + } + } + // 根据笔记是否在回收站中显示不同的时间 + if (data.getParentId() == Notes.ID_TRASH_FOLER || data.isDeleted()) { + // 回收站中的项显示删除时间 + mTime.setText(context.getString(R.string.deleted_time_format, + DateUtils.getRelativeTimeSpanString(data.getDeletedDate()))); + } else { + // 普通项显示修改时间 + mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); + } + + setBackground(data); + } + + /** + * 设置列表项的背景样式 + *+ * 该方法根据笔记数据的类型和状态,选择并设置合适的背景资源: + * 1. 对于普通笔记,根据其在列表中的位置(单个、第一个、最后一个、中间)选择不同的背景 + * 2. 对于文件夹或其他类型,使用默认的文件夹背景 + *
+ * @param data 笔记列表项数据,包含背景颜色ID、类型和位置信息 + */ + 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; + } +} diff --git a/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java b/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java new file mode 100644 index 0000000..5cca48d --- /dev/null +++ b/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java @@ -0,0 +1,554 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.app.ActionBar; +import android.app.AlertDialog; +import android.content.BroadcastReceiver; +import android.content.ContentValues; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.Preference; +import android.preference.Preference.OnPreferenceClickListener; +import android.preference.PreferenceActivity; +import android.preference.PreferenceCategory; +import android.text.TextUtils; +import android.text.format.DateFormat; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.remote.GTaskSyncService; + + +/** + * 笔记偏好设置活动类 + *+ * 该类用于处理笔记应用的设置,包括同步账户管理、背景颜色设置等功能, + * 提供了UI界面让用户进行偏好设置,并与GTaskSyncService进行交互实现同步功能 + *
+ */ +public class NotesPreferenceActivity extends PreferenceActivity { + /** 偏好设置文件名 */ + public static final String PREFERENCE_NAME = "notes_preferences"; + + /** 同步账户名的偏好键 */ + public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; + + /** 最后同步时间的偏好键 */ + public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; + + /** 背景颜色随机出现的偏好键 */ + public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; + + /** 同步账户的偏好键 */ + private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; + + /** 权限过滤器键 */ + private static final String AUTHORITIES_FILTER_KEY = "authorities"; + + /** 账户偏好设置分类 */ + private PreferenceCategory mAccountCategory; + + /** GTask同步服务广播接收器 */ + private GTaskReceiver mReceiver; + + /** 原始账户列表 */ + private Account[] mOriAccounts; + + /** 是否添加了新账户 */ + private boolean mHasAddedAccount; + + /** + * 活动创建时调用 + *+ * 该方法完成以下工作: + * 1. 设置导航栏显示应用图标 + * 2. 加载偏好设置资源 + * 3. 初始化账户偏好设置分类 + * 4. 注册GTask同步服务广播接收器 + * 5. 为列表视图添加头部 + *
+ * @param icicle 保存的实例状态 + */ + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + /* using the app icon for navigation */ + getActionBar().setDisplayHomeAsUpEnabled(true); + + addPreferencesFromResource(R.xml.preferences); + mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); + mReceiver = new GTaskReceiver(); + IntentFilter filter = new IntentFilter(); + filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); + registerReceiver(mReceiver, filter, Context.RECEIVER_EXPORTED); + + mOriAccounts = null; + View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); + getListView().addHeaderView(header, null, true); + } + + /** + * 活动恢复时调用 + *+ * 该方法完成以下工作: + * 1. 如果添加了新账户,自动设置同步账户 + * 2. 刷新UI界面 + *
+ */ + @Override + protected void onResume() { + super.onResume(); + + // need to set sync account automatically if user has added a new + // account + if (mHasAddedAccount) { + Account[] accounts = getGoogleAccounts(); + if (mOriAccounts != null && accounts.length > mOriAccounts.length) { + for (Account accountNew : accounts) { + boolean found = false; + for (Account accountOld : mOriAccounts) { + if (TextUtils.equals(accountOld.name, accountNew.name)) { + found = true; + break; + } + } + if (!found) { + setSyncAccount(accountNew.name); + break; + } + } + } + } + + refreshUI(); + } + + /** + * 活动销毁时调用 + *+ * 该方法完成以下工作: + * 1. 注销GTask同步服务广播接收器 + *
+ */ + @Override + protected void onDestroy() { + if (mReceiver != null) { + unregisterReceiver(mReceiver); + } + super.onDestroy(); + } + + /** + * 加载账户偏好设置 + *+ * 该方法完成以下工作: + * 1. 清空账户偏好设置分类中的所有偏好项 + * 2. 创建新的账户偏好项 + * 3. 设置账户偏好项的标题、摘要和点击监听器 + * 4. 根据当前同步状态和账户设置情况,决定点击时显示的对话框 + * 5. 将账户偏好项添加到分类中 + *
+ */ + private void loadAccountPreference() { + mAccountCategory.removeAll(); + + Preference accountPref = new Preference(this); + final String defaultAccount = getSyncAccountName(this); + accountPref.setTitle(getString(R.string.preferences_account_title)); + accountPref.setSummary(getString(R.string.preferences_account_summary)); + accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { + if (!GTaskSyncService.isSyncing()) { + if (TextUtils.isEmpty(defaultAccount)) { + // the first time to set account + showSelectAccountAlertDialog(); + } else { + // if the account has already been set, we need to promp + // user about the risk + showChangeAccountConfirmAlertDialog(); + } + } else { + Toast.makeText(NotesPreferenceActivity.this, + R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) + .show(); + } + return true; + } + }); + + mAccountCategory.addPreference(accountPref); + } + + /** + * 加载同步按钮和状态 + *+ * 该方法完成以下工作: + * 1. 获取同步按钮和最后同步时间视图 + * 2. 根据同步状态设置按钮文本和点击事件 + * 3. 根据是否有同步账户设置按钮可用性 + * 4. 设置最后同步时间或同步进度 + *
+ */ + private void loadSyncButton() { + Button syncButton = (Button) findViewById(R.id.preference_sync_button); + TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); + + // set button state + if (GTaskSyncService.isSyncing()) { + syncButton.setText(getString(R.string.preferences_button_sync_cancel)); + syncButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + GTaskSyncService.cancelSync(NotesPreferenceActivity.this); + } + }); + } else { + syncButton.setText(getString(R.string.preferences_button_sync_immediately)); + syncButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + GTaskSyncService.startSync(NotesPreferenceActivity.this); + } + }); + } + syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); + + // set last sync time + if (GTaskSyncService.isSyncing()) { + lastSyncTimeView.setText(GTaskSyncService.getProgressString()); + lastSyncTimeView.setVisibility(View.VISIBLE); + } else { + long lastSyncTime = getLastSyncTime(this); + if (lastSyncTime != 0) { + lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, + DateFormat.format(getString(R.string.preferences_last_sync_time_format), + lastSyncTime))); + lastSyncTimeView.setVisibility(View.VISIBLE); + } else { + lastSyncTimeView.setVisibility(View.GONE); + } + } + } + + /** + * 刷新UI界面 + *+ * 该方法调用loadAccountPreference和loadSyncButton方法来刷新UI界面 + *
+ */ + private void refreshUI() { + loadAccountPreference(); + loadSyncButton(); + } + + /** + * 显示选择账户对话框 + *+ * 该方法完成以下工作: + * 1. 创建对话框构建器并设置自定义标题 + * 2. 获取Google账户列表 + * 3. 如果有账户,显示单选列表供用户选择 + * 4. 添加添加新账户的选项 + * 5. 处理用户选择事件 + *
+ */ + private void showSelectAccountAlertDialog() { + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); + + View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); + TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); + titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); + TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); + subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); + + dialogBuilder.setCustomTitle(titleView); + dialogBuilder.setPositiveButton(null, null); + + Account[] accounts = getGoogleAccounts(); + String defAccount = getSyncAccountName(this); + + mOriAccounts = accounts; + mHasAddedAccount = false; + + if (accounts.length > 0) { + CharSequence[] items = new CharSequence[accounts.length]; + final CharSequence[] itemMapping = items; + int checkedItem = -1; + int index = 0; + for (Account account : accounts) { + if (TextUtils.equals(account.name, defAccount)) { + checkedItem = index; + } + items[index++] = account.name; + } + dialogBuilder.setSingleChoiceItems(items, checkedItem, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + setSyncAccount(itemMapping[which].toString()); + dialog.dismiss(); + refreshUI(); + } + }); + } + + View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); + dialogBuilder.setView(addAccountView); + + final AlertDialog dialog = dialogBuilder.show(); + addAccountView.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + mHasAddedAccount = true; + Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); + intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { + "gmail-ls" + }); + startActivityForResult(intent, -1); + dialog.dismiss(); + } + }); + } + + /** + * 显示更改账户确认对话框 + *+ * 该方法完成以下工作: + * 1. 创建对话框构建器并设置自定义标题 + * 2. 添加选项:更改账户、移除账户、取消 + * 3. 处理用户选择事件 + *
+ */ + private void showChangeAccountConfirmAlertDialog() { + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); + + View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); + TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); + titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, + getSyncAccountName(this))); + TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); + subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); + dialogBuilder.setCustomTitle(titleView); + + CharSequence[] menuItemArray = new CharSequence[] { + getString(R.string.preferences_menu_change_account), + getString(R.string.preferences_menu_remove_account), + getString(R.string.preferences_menu_cancel) + }; + dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + if (which == 0) { + showSelectAccountAlertDialog(); + } else if (which == 1) { + removeSyncAccount(); + refreshUI(); + } + } + }); + dialogBuilder.show(); + } + + /** + * 获取Google账户列表 + *+ * 该方法通过AccountManager获取设备上的所有Google账户 + *
+ * @return Google账户数组 + */ + private Account[] getGoogleAccounts() { + AccountManager accountManager = AccountManager.get(this); + return accountManager.getAccountsByType("com.google"); + } + + /** + * 设置同步账户 + *+ * 该方法完成以下工作: + * 1. 更新同步账户偏好设置 + * 2. 清除最后同步时间 + * 3. 清除本地GTask相关信息 + * 4. 显示成功提示 + *
+ * @param account 要设置的同步账户名 + */ + private void setSyncAccount(String account) { + if (!getSyncAccountName(this).equals(account)) { + SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = settings.edit(); + if (account != null) { + editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); + } else { + editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); + } + editor.commit(); + + // clean up last sync time + setLastSyncTime(this, 0); + + // clean up local gtask related info + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); + values.put(NoteColumns.SYNC_ID, 0); + getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); + } + }).start(); + + Toast.makeText(NotesPreferenceActivity.this, + getString(R.string.preferences_toast_success_set_accout, account), + Toast.LENGTH_SHORT).show(); + } + } + + /** + * 移除同步账户 + *+ * 该方法完成以下工作: + * 1. 移除同步账户偏好设置 + * 2. 移除最后同步时间偏好设置 + * 3. 清除本地GTask相关信息 + *
+ */ + private void removeSyncAccount() { + SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = settings.edit(); + if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { + editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); + } + if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { + editor.remove(PREFERENCE_LAST_SYNC_TIME); + } + editor.commit(); + + // clean up local gtask related info + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); + values.put(NoteColumns.SYNC_ID, 0); + getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); + } + }).start(); + } + + /** + * 获取同步账户名 + *+ * 该方法从偏好设置中获取同步账户名 + *
+ * @param context 上下文对象 + * @return 同步账户名,如果未设置则返回空字符串 + */ + public static String getSyncAccountName(Context context) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); + return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); + } + + /** + * 设置最后同步时间 + *+ * 该方法将最后同步时间保存到偏好设置中 + *
+ * @param context 上下文对象 + * @param time 最后同步时间(毫秒) + */ + public static void setLastSyncTime(Context context, long time) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); + SharedPreferences.Editor editor = settings.edit(); + editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); + editor.commit(); + } + + /** + * 获取最后同步时间 + *+ * 该方法从偏好设置中获取最后同步时间 + *
+ * @param context 上下文对象 + * @return 最后同步时间(毫秒),如果未设置则返回0 + */ + public static long getLastSyncTime(Context context) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); + return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); + } + + /** + * GTask同步服务广播接收器 + *+ * 该类用于接收GTaskSyncService发送的广播,更新UI界面和同步状态 + *
+ */ + private class GTaskReceiver extends BroadcastReceiver { + + /** + * 接收广播时调用 + *+ * 该方法完成以下工作: + * 1. 刷新UI界面 + * 2. 如果正在同步,更新同步状态文本 + *
+ * @param context 上下文对象 + * @param intent 广播意图,包含同步状态和进度信息 + */ + @Override + public void onReceive(Context context, Intent intent) { + refreshUI(); + if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { + TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); + syncStatus.setText(intent + .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); + } + + } + } + + /** + * 处理选项菜单点击事件 + *+ * 该方法处理选项菜单的点击事件,目前只处理了返回按钮的点击事件 + *
+ * @param item 被点击的菜单项 + * @return 是否处理了该事件 + */ + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + Intent intent = new Intent(this, NotesListActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(intent); + return true; + default: + return false; + } + } +} diff --git a/src/main/java/net/micode/notes/ui/TemplateSelectActivity.java b/src/main/java/net/micode/notes/ui/TemplateSelectActivity.java new file mode 100644 index 0000000..46999d5 --- /dev/null +++ b/src/main/java/net/micode/notes/ui/TemplateSelectActivity.java @@ -0,0 +1,207 @@ +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import net.micode.notes.R; +import net.micode.notes.model.NoteTemplate; +import net.micode.notes.model.TemplateManager; + +import java.util.List; + +/** + * 模板选择Activity,用于展示和选择笔记模板 + */ +public class TemplateSelectActivity extends Activity { + public static final String EXTRA_TEMPLATE_CONTENT = "template_content"; + public static final String EXTRA_CURRENT_NOTE_CONTENT = "current_note_content"; + + private RecyclerView mRecyclerView; + private TemplateAdapter mAdapter; + private List+ * 该抽象类为所有笔记小组件提供核心功能,包括小组件数据管理、UI更新、点击事件处理 + * 和小组件删除管理。它支持不同的小组件类型和布局,通过抽象方法让子类实现特定的 + * 布局和资源配置 + *
+ */ +public abstract class NoteWidgetProvider extends AppWidgetProvider { + /** + * 小组件数据查询的投影列数组 + *+ * 定义了从数据库查询笔记数据时需要获取的列,包括笔记ID、背景颜色ID和摘要内容 + *
+ */ + public static final String [] PROJECTION = new String [] { + NoteColumns.ID, + NoteColumns.BG_COLOR_ID, + NoteColumns.SNIPPET + }; + + /** + * 查询结果中ID列的索引 + */ + public static final int COLUMN_ID = 0; + + /** + * 查询结果中背景颜色ID列的索引 + */ + 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); + for (int i = 0; i < appWidgetIds.length; i++) { + context.getContentResolver().update(Notes.CONTENT_NOTE_URI, + values, + NoteColumns.WIDGET_ID + "=?", + new String[] { String.valueOf(appWidgetIds[i])}); + } + } + + /** + * 查询与特定小组件ID关联的笔记信息 + *+ * 该方法从数据库中查询与给定小组件ID关联的笔记数据,并排除已删除到回收站的笔记 + *
+ * @param context 上下文对象 + * @param widgetId 要查询的小组件ID + * @return 返回包含笔记信息的Cursor对象,使用PROJECTION中定义的列 + */ + private Cursor getNoteWidgetInfo(Context context, int widgetId) { + return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, + PROJECTION, + NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", + new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, + null); + } + + /** + * 更新小组件的UI和数据 + *+ * 该方法是update方法的公共保护接口,默认使用非隐私模式更新小组件 + *
+ * @param context 上下文对象 + * @param appWidgetManager 小组件管理器 + * @param appWidgetIds 要更新的小组件ID数组 + */ + protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + update(context, appWidgetManager, appWidgetIds, false); + } + + /** + * 更新小组件的UI和数据(私有实现) + *+ * 该方法负责实际更新小组件的内容,支持隐私模式和正常模式: + * 1. 查询与小组件关联的笔记信息 + * 2. 根据查询结果设置小组件显示的文本和背景 + * 3. 创建点击小组件时的PendingIntent + * 4. 在隐私模式下显示特定提示文本并跳转到笔记列表 + * 5. 在正常模式下显示笔记内容并支持查看或创建笔记 + *
+ * @param context 上下文对象 + * @param appWidgetManager 小组件管理器 + * @param appWidgetIds 要更新的小组件ID数组 + * @param privacyMode 是否处于隐私模式 + */ + private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, + boolean privacyMode) { + for (int i = 0; i < appWidgetIds.length; i++) { + if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { + 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) { + Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]); + c.close(); + return; + } + 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); + } else { + snippet = context.getResources().getString(R.string.widget_havenot_content); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + } + + if (c != null) { + c.close(); + } + + 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; + if (privacyMode) { + 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); + } + + rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); + appWidgetManager.updateAppWidget(appWidgetIds[i], rv); + } + } + } + + /** + * 根据背景颜色ID获取对应的背景资源ID + *+ * 该方法由子类实现,用于将数据库中的背景颜色ID转换为实际的资源ID + *
+ * @param bgId 数据库中的背景颜色ID + * @return 对应的背景资源ID + */ + protected abstract int getBgResourceId(int bgId); + + /** + * 获取小组件的布局ID + *+ * 该方法由子类实现,返回特定小组件类型的布局资源ID + *
+ * @return 小组件布局资源ID + */ + protected abstract int getLayoutId(); + + /** + * 获取小组件类型 + *+ * 该方法由子类实现,返回特定小组件的类型标识 + *
+ * @return 小组件类型标识 + */ + protected abstract int getWidgetType(); +} diff --git a/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java b/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java new file mode 100644 index 0000000..02bd7f1 --- /dev/null +++ b/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.ResourceParser; + + +/** + * 2x尺寸的笔记小组件实现类 + *+ * 该类继承自NoteWidgetProvider抽象类,实现了2x尺寸笔记小组件的具体功能 + * 包括布局设置、背景资源获取和小组件类型定义 + *
+ */ +public class NoteWidgetProvider_2x extends NoteWidgetProvider { + /** + * 更新小组件的UI和数据 + *+ * 该方法重写了AppWidgetProvider的onUpdate方法,调用父类的update方法来更新2x尺寸小组件 + *
+ * @param context 上下文对象 + * @param appWidgetManager 小组件管理器 + * @param appWidgetIds 要更新的小组件ID数组 + */ + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + } + + /** + * 获取2x尺寸小组件的布局ID + *+ * 返回2x尺寸小组件的布局资源ID + *
+ * @return 2x小组件布局资源ID + */ + @Override + protected int getLayoutId() { + return R.layout.widget_2x; + } + + /** + * 根据背景颜色ID获取2x小组件对应的背景资源ID + *+ * 通过ResourceParser获取2x尺寸小组件的背景资源ID + *
+ * @param bgId 数据库中的背景颜色ID + * @return 2x小组件对应的背景资源ID + */ + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); + } + + /** + * 获取2x小组件类型 + *+ * 返回2x尺寸小组件的类型标识 + *
+ * @return 2x小组件类型标识 + */ + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_2X; + } +} diff --git a/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java b/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java new file mode 100644 index 0000000..6e4a984 --- /dev/null +++ b/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.ResourceParser; + + +/** + * 4x尺寸的笔记小组件实现类 + *+ * 该类继承自NoteWidgetProvider抽象类,实现了4x尺寸笔记小组件的具体功能 + * 包括布局设置、背景资源获取和小组件类型定义 + *
+ */ +public class NoteWidgetProvider_4x extends NoteWidgetProvider { + /** + * 更新小组件的UI和数据 + *+ * 该方法重写了AppWidgetProvider的onUpdate方法,调用父类的update方法来更新4x尺寸小组件 + *
+ * @param context 上下文对象 + * @param appWidgetManager 小组件管理器 + * @param appWidgetIds 要更新的小组件ID数组 + */ + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + } + + /** + * 获取4x尺寸小组件的布局ID + *+ * 返回4x尺寸小组件的布局资源ID + *
+ * @return 4x小组件布局资源ID + */ + @Override + protected int getLayoutId() { + return R.layout.widget_4x; + } + + /** + * 根据背景颜色ID获取4x小组件对应的背景资源ID + *+ * 通过ResourceParser获取4x尺寸小组件的背景资源ID + *
+ * @param bgId 数据库中的背景颜色ID + * @return 4x小组件对应的背景资源ID + */ + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); + } + + /** + * 获取4x小组件类型 + *+ * 返回4x尺寸小组件的类型标识 + *
+ * @return 4x小组件类型标识 + */ + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_4X; + } +} diff --git a/src/main/java/net/micode/notes/worker/TrashCleanupWorker.java b/src/main/java/net/micode/notes/worker/TrashCleanupWorker.java new file mode 100644 index 0000000..5efd14f --- /dev/null +++ b/src/main/java/net/micode/notes/worker/TrashCleanupWorker.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.worker; + +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import android.util.Log; + +import net.micode.notes.model.RecentlyDeletedManager; + +/** + * 回收站自动清理工作器,负责定期清理超过保留期限的已删除项 + * 提供静态方法doCleanup()用于手动触发清理,可在应用启动时调用 + */ +public class TrashCleanupWorker { + // 日志标签 + private static final String TAG = "TrashCleanupWorker"; + // 上次清理时间的偏好设置键 + private static final String PREF_LAST_CLEANUP_TIME = "last_trash_cleanup_time"; + // 回收站保留天数的偏好设置键 + private static final String PREF_TRASH_RETENTION_DAYS = "pref_key_trash_retention_days"; + + /** + * 执行清理任务 + * @param context 上下文对象 + */ + public static void doCleanup(Context context) { + try { + // 获取偏好设置 + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + long lastCleanupTime = prefs.getLong(PREF_LAST_CLEANUP_TIME, 0); + long currentTime = System.currentTimeMillis(); + + // 检查是否需要清理:如果距离上次清理时间超过24小时 + if (currentTime - lastCleanupTime < RecentlyDeletedManager.CLEANUP_INTERVAL) { + Log.d(TAG, "Skip cleanup, last cleanup was within the interval"); + return; + } + + // 获取用户设置的保留天数 + int retentionDays = RecentlyDeletedManager.DEFAULT_RETENTION_DAYS; + try { + String retentionDaysStr = prefs.getString(PREF_TRASH_RETENTION_DAYS, String.valueOf(RecentlyDeletedManager.DEFAULT_RETENTION_DAYS)); + retentionDays = Integer.parseInt(retentionDaysStr); + } catch (NumberFormatException e) { + Log.e(TAG, "Invalid retention days setting, using default value", e); + retentionDays = RecentlyDeletedManager.DEFAULT_RETENTION_DAYS; + } + + // 执行清理 + RecentlyDeletedManager manager = RecentlyDeletedManager.getInstance(context); + int deletedCount = manager.cleanupOldItems(retentionDays); + + if (deletedCount > 0) { + Log.i(TAG, "Cleaned up " + deletedCount + " old items from trash"); + } else { + Log.d(TAG, "No old items to cleanup"); + } + + // 更新上次清理时间 + prefs.edit().putLong(PREF_LAST_CLEANUP_TIME, currentTime).apply(); + } catch (Exception e) { + Log.e(TAG, "Failed to perform trash cleanup", e); + } + } +} \ No newline at end of file diff --git a/src/main/res/color/primary_text_dark.xml b/src/main/res/color/primary_text_dark.xml new file mode 100644 index 0000000..7c85459 --- /dev/null +++ b/src/main/res/color/primary_text_dark.xml @@ -0,0 +1,22 @@ + + + + +