diff --git a/.idea/.gitignore b/.idea/.gitignore
deleted file mode 100644
index 26d3352..0000000
--- a/.idea/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-# Default ignored files
-/shelf/
-/workspace.xml
diff --git a/.idea/.name b/.idea/.name
deleted file mode 100644
index 7efc0ae..0000000
--- a/.idea/.name
+++ /dev/null
@@ -1 +0,0 @@
-Notes-master
\ No newline at end of file
diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml
deleted file mode 100644
index 4a53bee..0000000
--- a/.idea/AndroidProjectSystem.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
- * 应用的主入口,负责初始化主界面并处理窗口边距。 - * 支持边到边显示模式,自动适配系统栏的边距。 - *
- */ -public class MainActivity extends AppCompatActivity { - - /** - * 创建活动 - *- * 初始化活动界面,启用边到边显示模式,并设置窗口边距监听器。 - *
- * - * @param savedInstanceState 保存的实例状态,用于恢复活动状态 - */ - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - // 启用边到边显示模式 - EdgeToEdge.enable(this); - setContentView(R.layout.activity_main); - // 设置窗口边距监听器,自动适配系统栏 - ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { - // 获取系统栏边距 - Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); - // 设置视图内边距以适配系统栏 - v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); - return insets; - }); - } -} \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/data/Contact.java b/app/src/main/java/net/micode/notes/data/Contact.java deleted file mode 100644 index da3a693..0000000 --- a/app/src/main/java/net/micode/notes/data/Contact.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 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.Context; -import android.database.Cursor; -import android.provider.ContactsContract.CommonDataKinds.Phone; -import android.provider.ContactsContract.Data; -import android.telephony.PhoneNumberUtils; -import android.util.Log; - -import java.util.HashMap; - -/** - * 联系人信息查询工具类 - *- * 提供根据电话号码查询联系人姓名的功能,使用缓存机制提高查询效率。 - * 通过Android系统的ContactsContract Provider查询联系人信息。 - *
- *- * 主要功能: - *
- * 使用场景: - * 当笔记中包含电话号码时,使用此类查询对应的联系人姓名并显示。 - *
- * - * @see ContactsContract - * @see PhoneNumberUtils - */ -public class Contact { - /** - * 联系人信息缓存 - *- * 使用HashMap存储已查询的电话号码和对应的联系人姓名, - * 避免重复查询系统联系人数据库,提高性能。 - *
- * Key: 电话号码 - * Value: 联系人姓名 - */ - private static HashMap- * 使用PHONE_NUMBERS_EQUAL函数进行号码匹配,支持国际号码格式。 - * 只查询电话号码类型的数据(Phone.CONTENT_ITEM_TYPE)。 - * 使用min_match='+'进行最小匹配,提高查询效率。 - *
- */ - private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER - + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" - + " AND " + Data.RAW_CONTACT_ID + " IN " - + "(SELECT raw_contact_id " - + " FROM phone_lookup" - + " WHERE min_match = '+')"; - - /** - * 根据电话号码获取联系人姓名 - *- * 首先检查缓存中是否已存在该号码对应的联系人姓名, - * 如果存在则直接返回,否则查询系统联系人数据库。 - * 查询结果会被缓存以提高后续查询效率。 - *
- * - * @param context 应用上下文,用于访问ContentResolver - * @param phoneNumber 要查询的电话号码 - * @return 联系人姓名,如果未找到则返回null - */ - public static String getContact(Context context, String phoneNumber) { - // 初始化缓存 - if(sContactCache == null) { - sContactCache = new HashMap- * 定义了笔记应用中使用的所有常量、接口和内部类,包括: - *
- * 该类主要用于定义数据库表结构和Content Provider的契约, - * 提供统一的常量访问接口,方便应用各模块使用。 - *
- */ -public class Notes { - /** - * Content Provider的Authority - */ - 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; - - /** - * 以下ID是系统文件夹的标识符 - * {@link Notes#ID_ROOT_FOLDER } 是默认文件夹 - * {@link Notes#ID_TEMPARAY_FOLDER } 用于不属于任何文件夹的笔记 - * {@link Notes#ID_CALL_RECORD_FOLDER} 用于存储通话记录 - */ - public static final int ID_ROOT_FOLDER = 0; - /** - * 临时文件夹ID,用于不属于任何文件夹的笔记 - */ - public static final int ID_TEMPARAY_FOLDER = -1; - /** - * 通话记录文件夹ID,用于存储通话记录 - */ - public static final int ID_CALL_RECORD_FOLDER = -2; - /** - * 回收站文件夹ID,用于存储已删除的笔记 - */ - public static final int ID_TRASH_FOLER = -3; - - /** - * Intent Extra键:提醒日期 - */ - public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; - /** - * Intent Extra键:背景颜色ID - */ - public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; - /** - * Intent Extra键:Widget ID - */ - public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; - /** - * Intent Extra键:Widget类型 - */ - public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; - /** - * Intent Extra键:文件夹ID - */ - public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; - /** - * Intent Extra键:通话日期 - */ - public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; - - /** - * 无效的Widget类型 - */ - public static final int TYPE_WIDGET_INVALIDE = -1; - /** - * 2x2 Widget类型 - */ - public static final int TYPE_WIDGET_2X = 0; - /** - * 4x4 Widget类型 - */ - public static final int TYPE_WIDGET_4X = 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 to query all notes and folders - */ - public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); - - /** - * Uri to query data - */ - public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); - - public interface NoteColumns { - /** - * The unique ID for a row - *Type: INTEGER (long)
- */ - public static final String ID = "_id"; - - /** - * The parent's id for note or folder - *Type: INTEGER (long)
- */ - public static final String PARENT_ID = "parent_id"; - - /** - * Created data for note or folder - *Type: INTEGER (long)
- */ - public static final String CREATED_DATE = "created_date"; - - /** - * Latest modified date - *Type: INTEGER (long)
- */ - public static final String MODIFIED_DATE = "modified_date"; - - - /** - * Alert date - *Type: INTEGER (long)
- */ - public static final String ALERTED_DATE = "alert_date"; - - /** - * Folder's name or text content of note - *Type: TEXT
- */ - public static final String SNIPPET = "snippet"; - - /** - * Note's widget id - *Type: INTEGER (long)
- */ - public static final String WIDGET_ID = "widget_id"; - - /** - * Note's widget type - *Type: INTEGER (long)
- */ - public static final String WIDGET_TYPE = "widget_type"; - - /** - * Note's background color's id - *Type: INTEGER (long)
- */ - public static final String BG_COLOR_ID = "bg_color_id"; - - /** - * For text note, it doesn't has attachment, for multi-media - * note, it has at least one attachment - *Type: INTEGER
- */ - public static final String HAS_ATTACHMENT = "has_attachment"; - - /** - * Folder's count of notes - *Type: INTEGER (long)
- */ - public static final String NOTES_COUNT = "notes_count"; - - /** - * The file type: folder or note - *Type: INTEGER
- */ - public static final String TYPE = "type"; - - /** - * The last sync id - *Type: INTEGER (long)
- */ - public static final String SYNC_ID = "sync_id"; - - /** - * Sign to indicate local modified or not - *Type: INTEGER
- */ - public static final String LOCAL_MODIFIED = "local_modified"; - - /** - * Original parent id before moving into temporary folder - *Type : INTEGER
- */ - public static final String ORIGIN_PARENT_ID = "origin_parent_id"; - - /** - * The gtask id - *Type : TEXT
- */ - public static final String GTASK_ID = "gtask_id"; - - /** - * The version code - *Type : INTEGER (long)
- */ - public static final String VERSION = "version"; - } - - public interface DataColumns { - /** - * The unique ID for a row - *Type: INTEGER (long)
- */ - public static final String ID = "_id"; - - /** - * The MIME type of the item represented by this row. - *Type: Text
- */ - public static final String MIME_TYPE = "mime_type"; - - /** - * The reference id to note that this data belongs to - *Type: INTEGER (long)
- */ - public static final String NOTE_ID = "note_id"; - - /** - * Created data for note or folder - *Type: INTEGER (long)
- */ - public static final String CREATED_DATE = "created_date"; - - /** - * Latest modified date - *Type: INTEGER (long)
- */ - public static final String MODIFIED_DATE = "modified_date"; - - /** - * Data's content - *Type: TEXT
- */ - public static final String CONTENT = "content"; - - - /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * integer data type - *Type: INTEGER
- */ - public static final String DATA1 = "data1"; - - /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * integer data type - *Type: INTEGER
- */ - public static final String DATA2 = "data2"; - - /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * TEXT data type - *Type: TEXT
- */ - public static final String DATA3 = "data3"; - - /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * TEXT data type - *Type: TEXT
- */ - public static final String DATA4 = "data4"; - - /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * TEXT data type - *Type: TEXT
- */ - public static final String DATA5 = "data5"; - } - - public static final class TextNote implements DataColumns { - /** - * Mode to indicate the text in check list mode or not - *Type: Integer 1:check list mode 0: normal mode
- */ - public static final String MODE = DATA1; - - public static final int MODE_CHECK_LIST = 1; - - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; - - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; - - public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); - } - - public static final class CallNote implements DataColumns { - /** - * Call date for this record - *Type: INTEGER (long)
- */ - public static final String CALL_DATE = DATA1; - - /** - * Phone number for this record - *Type: TEXT
- */ - public static final String PHONE_NUMBER = DATA3; - - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; - - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; - - public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); - } -} diff --git a/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java b/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java deleted file mode 100644 index 558caf7..0000000 --- a/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java +++ /dev/null @@ -1,598 +0,0 @@ -/* - * 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; - - -/** - * 笔记数据库帮助类 - *- * 继承自SQLiteOpenHelper,负责笔记应用SQLite数据库的创建、升级和管理。 - * 管理两个主要数据表:note表(存储笔记和文件夹信息)和data表(存储笔记的详细内容)。 - * 使用数据库触发器自动维护笔记计数、内容同步等关联关系。 - *
- *- * 主要功能: - *
- * 数据库版本历史: - *
- * 当前数据库版本为4,用于跟踪数据库结构变更。 - * 当数据库版本变更时,onUpgrade方法会被调用以执行升级逻辑。 - *
- */ - private static final int DB_VERSION = 4; - - /** - * 数据库表名常量接口 - */ - public interface TABLE { - /** - * 笔记表名 - *- * 存储笔记和文件夹的基本信息,包括ID、父文件夹ID、创建时间、修改时间、 - * 背景颜色、提醒时间、附件状态、笔记数量、摘要、类型、Widget信息、 - * 同步ID、本地修改状态、原始父文件夹ID、GTASK ID、版本等字段。 - *
- */ - public static final String NOTE = "note"; - - /** - * 数据表名 - *- * 存储笔记的详细内容,支持多种MIME类型(文本、图片、附件等)。 - * 每条数据记录关联到一条笔记,包含MIME类型、内容、以及5个通用数据字段。 - *
- */ - public static final String DATA = "data"; - } - - /** - * 日志标签 - */ - private static final String TAG = "NotesDatabaseHelper"; - - /** - * 数据库帮助类单例实例 - *- * 使用单例模式确保全局只有一个数据库帮助类实例, - * 避免多个实例同时操作数据库导致的数据不一致问题。 - *
- */ - private static NotesDatabaseHelper mInstance; - - /** - * 创建笔记表的SQL语句 - *- * 创建note表,包含以下字段: - *
- * 创建data表,包含以下字段: - *
- * 在data表的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 + ");"; - - /** - * Increase folder's note count when move note to the folder - */ - private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = - "CREATE TRIGGER increase_folder_count_on_update "+ - " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + - " END"; - - /** - * Decrease folder's note count when move note from folder - */ - 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"; - - /** - * Increase folder's note count when insert new note to the folder - */ - private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = - "CREATE TRIGGER increase_folder_count_on_insert " + - " AFTER INSERT ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + - " END"; - - /** - * Decrease folder's note count when delete note from the folder - */ - 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"; - - /** - * Update note's content when insert data with type {@link DataConstants#NOTE} - */ - 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"; - - /** - * Update note's content when data with {@link DataConstants#NOTE} type has changed - */ - 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"; - - /** - * Update note's content when data with {@link DataConstants#NOTE} type has deleted - */ - 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"; - - /** - * Delete datas belong to note which has been deleted - */ - private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = - "CREATE TRIGGER delete_data_on_delete " + - " AFTER DELETE ON " + TABLE.NOTE + - " BEGIN" + - " DELETE FROM " + TABLE.DATA + - " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + - " END"; - - /** - * Delete notes belong to folder which has been deleted - */ - 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"; - - /** - * Move notes belong to folder which has been moved to trash folder - */ - private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = - "CREATE TRIGGER folder_move_notes_on_trash " + - " 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); - } - - /** - * 创建笔记表 - *- * 执行创建note表的SQL语句,创建相关触发器,并初始化系统文件夹。 - *
- * - * @param db SQLiteDatabase实例 - */ - public void createNoteTable(SQLiteDatabase db) { - db.execSQL(CREATE_NOTE_TABLE_SQL); - reCreateNoteTableTriggers(db); - createSystemFolder(db); - Log.d(TAG, "note table has been created"); - } - - /** - * 重新创建笔记表触发器 - *- * 先删除所有已存在的note表相关触发器,然后重新创建所有触发器。 - * 用于在数据库升级时更新触发器逻辑。 - *
- * - * @param db SQLiteDatabase实例 - */ - private void reCreateNoteTableTriggers(SQLiteDatabase db) { - // 删除所有已存在的触发器 - db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); - db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); - 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(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); - } - - /** - * 创建系统文件夹 - *- * 在note表中创建四个系统文件夹: - *
- * 执行创建data表的SQL语句,创建相关触发器,并创建索引。 - *
- * - * @param db SQLiteDatabase实例 - */ - 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"); - } - - /** - * 重新创建数据表触发器 - *- * 先删除所有已存在的data表相关触发器,然后重新创建所有触发器。 - * 用于在数据库升级时更新触发器逻辑。 - *
- * - * @param db SQLiteDatabase实例 - */ - private void reCreateDataTableTriggers(SQLiteDatabase db) { - // 删除所有已存在的触发器 - db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); - db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); - 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 NotesDatabaseHelper单例实例 - */ - static synchronized NotesDatabaseHelper getInstance(Context context) { - if (mInstance == null) { - mInstance = new NotesDatabaseHelper(context); - } - return mInstance; - } - - /** - * 创建数据库 - *- * 当数据库文件不存在时调用,创建note表和data表。 - *
- * - * @param db SQLiteDatabase实例 - */ - @Override - public void onCreate(SQLiteDatabase db) { - createNoteTable(db); - createDataTable(db); - } - - /** - * 升级数据库 - *- * 当数据库版本号增加时调用,执行从旧版本到新版本的升级逻辑。 - * 支持增量升级,从当前版本逐步升级到目标版本。 - *
- * - * @param db SQLiteDatabase实例 - * @param oldVersion 当前数据库版本号 - * @param newVersion 目标数据库版本号 - * @throws IllegalStateException 如果升级失败 - */ - @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - boolean reCreateTriggers = false; - boolean skipV2 = false; - - // 从V1升级到V2(包括V2到V3) - if (oldVersion == 1) { - upgradeToV2(db); - skipV2 = true; // this upgrade including the upgrade from v2 to v3 - oldVersion++; - } - - // 从V2升级到V3 - if (oldVersion == 2 && !skipV2) { - upgradeToV3(db); - reCreateTriggers = true; - oldVersion++; - } - - // 从V3升级到V4 - if (oldVersion == 3) { - upgradeToV4(db); - oldVersion++; - } - - // 如果需要,重新创建触发器 - if (reCreateTriggers) { - reCreateNoteTableTriggers(db); - reCreateDataTableTriggers(db); - } - - // 检查升级是否成功 - if (oldVersion != newVersion) { - throw new IllegalStateException("Upgrade notes database to version " + newVersion - + "fails"); - } - } - - /** - * 升级数据库到V2版本 - *- * 删除旧表并重新创建note表和data表。 - *
- * - * @param db SQLiteDatabase实例 - */ - 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); - } - - /** - * 升级数据库到V3版本 - *- * 添加GTASK_ID列到note表,并创建回收站系统文件夹。 - *
- * - * @param db SQLiteDatabase实例 - */ - private void upgradeToV3(SQLiteDatabase db) { - // drop unused triggers - // 删除未使用的触发器 - db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); - db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); - db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); - // add a column for gtask id - // 添加GTASK_ID列 - db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID - + " TEXT NOT NULL DEFAULT ''"); - // add a trash system folder - // 添加回收站系统文件夹 - ContentValues values = new ContentValues(); - values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); - values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); - db.insert(TABLE.NOTE, null, values); - } - - /** - * 升级数据库到V4版本 - *- * 添加VERSION列到note表,用于跟踪笔记版本。 - *
- * - * @param db SQLiteDatabase实例 - */ - private void upgradeToV4(SQLiteDatabase db) { - db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION - + " INTEGER NOT NULL DEFAULT 0"); - } -} diff --git a/app/src/main/java/net/micode/notes/data/NotesProvider.java b/app/src/main/java/net/micode/notes/data/NotesProvider.java deleted file mode 100644 index aa2cf34..0000000 --- a/app/src/main/java/net/micode/notes/data/NotesProvider.java +++ /dev/null @@ -1,517 +0,0 @@ -/* - * 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; - - -/** - * 笔记Content Provider - *- * 继承自ContentProvider,提供对笔记数据的增删改查(CRUD)操作。 - * 管理note表和data表的数据访问,支持URI匹配、数据查询、插入、更新和删除操作。 - * 同时提供搜索建议功能,支持全局搜索笔记内容。 - *
- *- * 主要功能: - *
- * 支持的URI模式: - *
- * 用于匹配不同的URI模式,将请求路由到对应的处理逻辑。 - * 支持笔记、数据、搜索等多种URI模式。 - *
- */ - private static final UriMatcher mMatcher; - - /** - * 数据库帮助类实例 - *- * 用于获取可读和可写的SQLiteDatabase实例。 - *
- */ - private NotesDatabaseHelper mHelper; - - /** - * 日志标签 - */ - private static final String TAG = "NotesProvider"; - - /** - * 笔记URI匹配码 - */ - private static final int URI_NOTE = 1; - /** - * 笔记项URI匹配码 - */ - private static final int URI_NOTE_ITEM = 2; - /** - * 数据URI匹配码 - */ - private static final int URI_DATA = 3; - /** - * 数据项URI匹配码 - */ - private static final int URI_DATA_ITEM = 4; - - /** - * 搜索URI匹配码 - */ - private static final int URI_SEARCH = 5; - /** - * 搜索建议URI匹配码 - */ - private static final int URI_SEARCH_SUGGEST = 6; - - /** - * URI匹配器初始化块 - *- * 初始化UriMatcher,注册所有支持的URI模式。 - *
- */ - static { - mMatcher = new UriMatcher(UriMatcher.NO_MATCH); - mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); - mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); - mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); - mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); - 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); - } - - /** - * 搜索结果投影 - *- * 定义搜索建议返回的列,包括笔记ID、文本内容、图标、Intent动作等。 - * 使用TRIM和REPLACE函数去除换行符和空白字符,以便更好地显示搜索结果。 - *
- *- * x'0A'代表SQLite中的换行符'\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语句 - *- * 搜索note表中SNIPPET字段包含指定关键词的笔记。 - * 排除回收站中的笔记(PARENT_ID不等于ID_TRASH_FOLER)。 - * 只搜索普通笔记(TYPE等于TYPE_NOTE)。 - *
- */ - 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; - - /** - * 创建Content Provider - *- * 初始化数据库帮助类实例。 - *
- * - * @return true表示创建成功 - */ - @Override - public boolean onCreate() { - mHelper = NotesDatabaseHelper.getInstance(getContext()); - return true; - } - - /** - * 查询数据 - *- * 根据URI模式查询对应的数据表,支持笔记、数据、搜索等多种查询模式。 - * 对于搜索模式,使用LIKE模糊匹配查询笔记摘要。 - *
- * - * @param uri 查询的URI - * @param projection 要查询的列数组 - * @param selection 查询条件 - * @param selectionArgs 查询条件参数 - * @param sortOrder 排序方式 - * @return 查询结果的Cursor对象 - * @throws IllegalArgumentException 如果URI模式不支持或搜索时指定了不允许的参数 - */ - @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, - String sortOrder) { - Cursor c = null; - SQLiteDatabase db = mHelper.getReadableDatabase(); - String id = null; - switch (mMatcher.match(uri)) { - case URI_NOTE: - // 查询所有笔记 - c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, - sortOrder); - break; - case URI_NOTE_ITEM: - // 查询指定ID的笔记 - id = uri.getPathSegments().get(1); - c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id - + parseSelection(selection), selectionArgs, null, null, sortOrder); - break; - case URI_DATA: - // 查询所有数据 - c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, - sortOrder); - break; - case URI_DATA_ITEM: - // 查询指定ID的数据 - id = uri.getPathSegments().get(1); - c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id - + parseSelection(selection), selectionArgs, null, null, sortOrder); - break; - case URI_SEARCH: - case URI_SEARCH_SUGGEST: - // 搜索笔记或搜索建议 - if (sortOrder != null || projection != null) { - throw new IllegalArgumentException( - "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); - } - - String searchString = null; - if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { - // 从URI路径中获取搜索关键词 - if (uri.getPathSegments().size() > 1) { - searchString = uri.getPathSegments().get(1); - } - } else { - // 从查询参数中获取搜索关键词 - searchString = uri.getQueryParameter("pattern"); - } - - // 搜索关键词为空时返回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); - } - // 设置通知URI,当数据变更时通知观察者 - if (c != null) { - c.setNotificationUri(getContext().getContentResolver(), uri); - } - return c; - } - - /** - * 插入数据 - *- * 根据URI模式向对应的数据表插入数据,支持笔记和数据的插入。 - * 插入成功后通知相关URI的观察者。 - *
- * - * @param uri 插入数据的URI - * @param values 要插入的数据值 - * @return 插入数据的URI(包含新增记录的ID) - * @throws IllegalArgumentException 如果URI模式不支持 - */ - @Override - public Uri insert(Uri uri, ContentValues values) { - SQLiteDatabase db = mHelper.getWritableDatabase(); - long dataId = 0, noteId = 0, insertedId = 0; - switch (mMatcher.match(uri)) { - case URI_NOTE: - // 插入笔记 - insertedId = noteId = db.insert(TABLE.NOTE, null, values); - break; - case URI_DATA: - // 插入数据 - if (values.containsKey(DataColumns.NOTE_ID)) { - 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); - } - // Notify the note uri - // 通知笔记URI的观察者 - if (noteId > 0) { - getContext().getContentResolver().notifyChange( - ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); - } - - // Notify the data uri - // 通知数据URI的观察者 - if (dataId > 0) { - getContext().getContentResolver().notifyChange( - ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); - } - - return ContentUris.withAppendedId(uri, insertedId); - } - - /** - * 删除数据 - *- * 根据URI模式删除对应的数据表中的数据,支持笔记和数据的删除。 - * 删除笔记时,不允许删除系统文件夹(ID小于等于0)。 - * 删除成功后通知相关URI的观察者。 - *
- * - * @param uri 删除数据的URI - * @param selection 删除条件 - * @param selectionArgs 删除条件参数 - * @return 删除的记录数 - * @throws IllegalArgumentException 如果URI模式不支持 - */ - @Override - public int delete(Uri uri, String selection, String[] selectionArgs) { - int count = 0; - String id = null; - SQLiteDatabase db = mHelper.getWritableDatabase(); - boolean deleteData = false; - switch (mMatcher.match(uri)) { - case URI_NOTE: - // 删除笔记(排除系统文件夹) - selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; - count = db.delete(TABLE.NOTE, selection, selectionArgs); - break; - case URI_NOTE_ITEM: - // 删除指定ID的笔记 - id = uri.getPathSegments().get(1); - /** - * ID that smaller than 0 is system folder which is not allowed to - * trash - * 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的数据 - 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); - } - getContext().getContentResolver().notifyChange(uri, null); - } - return count; - } - - /** - * 更新数据 - *- * 根据URI模式更新对应的数据表中的数据,支持笔记和数据的更新。 - * 更新笔记时自动递增笔记的版本号。 - * 更新成功后通知相关URI的观察者。 - *
- * - * @param uri 更新数据的URI - * @param values 要更新的数据值 - * @param selection 更新条件 - * @param selectionArgs 更新条件参数 - * @return 更新的记录数 - * @throws IllegalArgumentException 如果URI模式不支持 - */ - @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; - switch (mMatcher.match(uri)) { - case URI_NOTE: - // 更新笔记(递增版本号) - increaseNoteVersion(-1, selection, selectionArgs); - count = db.update(TABLE.NOTE, values, selection, selectionArgs); - break; - case URI_NOTE_ITEM: - // 更新指定ID的笔记(递增版本号) - id = uri.getPathSegments().get(1); - increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); - count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id - + parseSelection(selection), selectionArgs); - break; - case URI_DATA: - // 更新数据 - count = db.update(TABLE.DATA, values, selection, selectionArgs); - updateData = true; - break; - case URI_DATA_ITEM: - // 更新指定ID的数据 - id = uri.getPathSegments().get(1); - count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id - + parseSelection(selection), selectionArgs); - updateData = true; - break; - default: - throw new IllegalArgumentException("Unknown URI " + uri); - } - - // 更新成功后通知观察者 - if (count > 0) { - if (updateData) { - // 更新数据时通知笔记URI - getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); - } - getContext().getContentResolver().notifyChange(uri, null); - } - return count; - } - - /** - * 解析查询条件 - *- * 将查询条件与ID条件组合,用于构建完整的SQL WHERE子句。 - *
- * - * @param selection 原始查询条件 - * @return 组合后的查询条件字符串 - */ - private String parseSelection(String selection) { - return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); - } - - /** - * 递增笔记版本号 - *- * 更新指定笔记的VERSION字段,使其值加1。 - * 用于跟踪笔记的修改历史,支持同步功能。 - *
- * - * @param id 笔记ID,如果小于等于0则使用selection条件 - * @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); - } - - mHelper.getWritableDatabase().execSQL(sql.toString()); - } - - /** - * 获取数据MIME类型 - *- * 返回指定URI对应的数据MIME类型。 - *
- * - * @param uri 数据URI - * @return MIME类型字符串 - */ - @Override - public String getType(Uri uri) { - // TODO Auto-generated method stub - return null; - } -} diff --git a/app/src/main/java/net/micode/notes/gtask/data/MetaData.java b/app/src/main/java/net/micode/notes/gtask/data/MetaData.java deleted file mode 100644 index 28f6294..0000000 --- a/app/src/main/java/net/micode/notes/gtask/data/MetaData.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * 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; - - -/** - * Google Tasks 元数据类 - *- * 继承自 Task,用于存储和管理 Google Tasks 同步的元数据信息。 - * 元数据以特殊任务的形式存储在 Google Tasks 中,用于关联本地笔记和远程任务的对应关系。 - * 该类不应通过本地 JSON 或数据库游标进行操作,仅用于远程同步场景。 - *
- */ -public class MetaData extends Task { - /** - * 日志标签 - */ - private final static String TAG = MetaData.class.getSimpleName(); - - /** - * 关联的 Google Tasks ID - */ - private String mRelatedGid = null; - - /** - * 设置元数据信息 - *- * 将 Google Tasks ID 添加到元信息 JSON 对象中,并设置任务名称为元数据专用名称。 - * 元信息以 JSON 字符串形式存储在任务的 notes 字段中。 - *
- * - * @param gid 关联的 Google Tasks ID - * @param metaInfo 元信息 JSON 对象 - */ - public void setMeta(String gid, JSONObject metaInfo) { - try { - // 将关联的 GID 添加到元信息中 - metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); - } catch (JSONException e) { - Log.e(TAG, "failed to put related gid"); - } - // 将元信息转换为字符串并设置为任务备注 - setNotes(metaInfo.toString()); - // 设置为元数据专用名称 - setName(GTaskStringUtils.META_NOTE_NAME); - } - - /** - * 获取关联的 Google Tasks ID - * - * @return 关联的 Google Tasks ID,如果未设置则返回 null - */ - public String getRelatedGid() { - return mRelatedGid; - } - - /** - * 判断是否值得保存 - *- * 只有当 notes 字段不为空时才值得保存,因为元数据信息存储在 notes 中。 - *
- * - * @return 如果 notes 不为 null 返回 true,否则返回 false - */ - @Override - public boolean isWorthSaving() { - return getNotes() != null; - } - - /** - * 根据远程 JSON 设置内容 - *- * 从远程服务器返回的 JSON 对象中解析元数据信息,提取关联的 Google Tasks ID。 - *
- * - * @param js 远程服务器返回的 JSON 对象 - */ - @Override - public void setContentByRemoteJSON(JSONObject js) { - super.setContentByRemoteJSON(js); - if (getNotes() != null) { - try { - // 从 notes 字段中解析元信息 JSON - JSONObject metaInfo = new JSONObject(getNotes().trim()); - // 提取关联的 GID - mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); - } catch (JSONException e) { - Log.w(TAG, "failed to get related gid"); - mRelatedGid = null; - } - } - } - - /** - * 根据本地 JSON 设置内容 - *- * 此方法不应被调用,因为元数据不通过本地 JSON 进行操作。 - *
- * - * @param js 本地 JSON 对象 - * @throws IllegalAccessError 总是抛出此异常,表示不应调用此方法 - */ - @Override - public void setContentByLocalJSON(JSONObject js) { - // this function should not be called - throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); - } - - /** - * 从内容生成本地 JSON 对象 - *- * 此方法不应被调用,因为元数据不通过本地 JSON 进行操作。 - *
- * - * @return 无返回值,总是抛出异常 - * @throws IllegalAccessError 总是抛出此异常,表示不应调用此方法 - */ - @Override - public JSONObject getLocalJSONFromContent() { - throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); - } - - /** - * 根据数据库游标获取同步动作 - *- * 此方法不应被调用,因为元数据不通过数据库游标进行操作。 - *
- * - * @param c 数据库游标 - * @return 无返回值,总是抛出异常 - * @throws IllegalAccessError 总是抛出此异常,表示不应调用此方法 - */ - @Override - public int getSyncAction(Cursor c) { - throw new IllegalAccessError("MetaData:getSyncAction should not be called"); - } - -} diff --git a/app/src/main/java/net/micode/notes/gtask/data/Node.java b/app/src/main/java/net/micode/notes/gtask/data/Node.java deleted file mode 100644 index ad7e431..0000000 --- a/app/src/main/java/net/micode/notes/gtask/data/Node.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * 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; - -/** - * Google Tasks 同步节点抽象基类 - *- * 定义所有可同步数据模型(Task、TaskList、MetaData)的公共属性和抽象方法。 - * 负责管理同步状态、Google ID、名称、最后修改时间和删除标记等通用属性。 - * 子类需要实现具体的 JSON 转换和同步动作生成逻辑。 - *
- */ -public abstract class Node { - /** - * 无需同步操作 - */ - public static final int SYNC_ACTION_NONE = 0; - - /** - * 需要添加到远程服务器 - */ - public static final int SYNC_ACTION_ADD_REMOTE = 1; - - /** - * 需要添加到本地数据库 - */ - public static final int SYNC_ACTION_ADD_LOCAL = 2; - - /** - * 需要从远程服务器删除 - */ - public static final int SYNC_ACTION_DEL_REMOTE = 3; - - /** - * 需要从本地数据库删除 - */ - public static final int SYNC_ACTION_DEL_LOCAL = 4; - - /** - * 需要更新到远程服务器 - */ - public static final int SYNC_ACTION_UPDATE_REMOTE = 5; - - /** - * 需要更新到本地数据库 - */ - public static final int SYNC_ACTION_UPDATE_LOCAL = 6; - - /** - * 同步冲突,需要特殊处理 - */ - public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; - - /** - * 同步错误 - */ - public static final int SYNC_ACTION_ERROR = 8; - - /** - * Google Tasks ID,用于唯一标识远程任务 - */ - private String mGid; - - /** - * 节点名称 - */ - private String mName; - - /** - * 最后修改时间(时间戳) - */ - private long mLastModified; - - /** - * 删除标记,true 表示已删除 - */ - private boolean mDeleted; - - /** - * 构造一个新的节点实例 - *- * 初始化所有属性为默认值:GID 为 null,名称为空字符串,最后修改时间为 0,删除标记为 false。 - *
- */ - public Node() { - mGid = null; - mName = ""; - mLastModified = 0; - mDeleted = false; - } - - /** - * 获取创建动作的 JSON 对象 - *- * 根据指定的动作 ID 生成用于在远程服务器创建节点的 JSON 请求。 - *
- * - * @param actionId 动作 ID,标识具体的创建操作类型 - * @return 包含创建动作信息的 JSON 对象 - */ - public abstract JSONObject getCreateAction(int actionId); - - /** - * 获取更新动作的 JSON 对象 - *- * 根据指定的动作 ID 生成用于在远程服务器更新节点的 JSON 请求。 - *
- * - * @param actionId 动作 ID,标识具体的更新操作类型 - * @return 包含更新动作信息的 JSON 对象 - */ - public abstract JSONObject getUpdateAction(int actionId); - - /** - * 根据远程 JSON 设置节点内容 - *- * 从远程服务器返回的 JSON 对象中解析并设置节点的属性值。 - *
- * - * @param js 远程服务器返回的 JSON 对象 - */ - public abstract void setContentByRemoteJSON(JSONObject js); - - /** - * 根据本地 JSON 设置节点内容 - *- * 从本地数据库存储的 JSON 对象中解析并设置节点的属性值。 - *
- * - * @param js 本地数据库存储的 JSON 对象 - */ - public abstract void setContentByLocalJSON(JSONObject js); - - /** - * 从节点内容生成本地 JSON 对象 - *- * 将节点的当前属性值转换为 JSON 对象,用于存储到本地数据库。 - *
- * - * @return 包含节点内容的 JSON 对象 - */ - public abstract JSONObject getLocalJSONFromContent(); - - /** - * 根据数据库游标获取同步动作 - *- * 比较本地数据库中的数据与当前节点状态,确定需要执行的同步动作类型。 - *
- * - * @param c 指向本地数据库记录的游标 - * @return 同步动作类型,取值为 SYNC_ACTION_* 常量之一 - */ - public abstract int getSyncAction(Cursor c); - - /** - * 设置 Google Tasks ID - * - * @param gid Google Tasks 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 删除标记,true 表示已删除 - */ - public void setDeleted(boolean deleted) { - this.mDeleted = deleted; - } - - /** - * 获取 Google Tasks ID - * - * @return Google Tasks ID,如果未设置则返回 null - */ - public String getGid() { - return this.mGid; - } - - /** - * 获取节点名称 - * - * @return 节点名称 - */ - public String getName() { - return this.mName; - } - - /** - * 获取最后修改时间 - * - * @return 最后修改时间(时间戳) - */ - public long getLastModified() { - return this.mLastModified; - } - - /** - * 获取删除标记 - * - * @return 删除标记,true 表示已删除 - */ - public boolean getDeleted() { - return this.mDeleted; - } - -} diff --git a/app/src/main/java/net/micode/notes/gtask/data/SqlData.java b/app/src/main/java/net/micode/notes/gtask/data/SqlData.java deleted file mode 100644 index 174560e..0000000 --- a/app/src/main/java/net/micode/notes/gtask/data/SqlData.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - * 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; - - -/** - * SQLite 数据内容类 - *- * 表示笔记的一条数据记录,存储笔记的具体内容信息。 - * 每条数据记录包含 MIME 类型、内容文本和扩展数据字段。 - * 支持从 JSON 对象加载内容或将内容导出为 JSON,用于与 Google Tasks 的数据同步。 - *
- */ -public class SqlData { - private static final String TAG = SqlData.class.getSimpleName(); - - /** 无效 ID 标识符 */ - private static final int INVALID_ID = -99999; - - /** 数据表查询投影字段数组 */ - public static final String[] PROJECTION_DATA = new String[] { - DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, - DataColumns.DATA3 - }; - - /** 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; - - /** 扩展数据 1 字段在投影数组中的索引 */ - public static final int DATA_CONTENT_DATA_1_COLUMN = 3; - - /** 扩展数据 3 字段在投影数组中的索引 */ - public static final int DATA_CONTENT_DATA_3_COLUMN = 4; - - private ContentResolver mContentResolver; - - private boolean mIsCreate; - - private long mDataId; - - private String mDataMimeType; - - private String mDataContent; - - private long mDataContentData1; - - private String mDataContentData3; - - private ContentValues mDiffDataValues; - - /** - * 构造一个新建的数据对象 - *- * 创建一个尚未保存到数据库的新数据记录,初始化所有字段为默认值。 - * 标记为创建状态,后续调用 commit 方法时会执行插入操作。 - *
- * - * @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(); - } - - /** - * 从数据库游标构造数据对象 - *- * 从游标中读取数据记录并初始化对象。 - * 标记为非创建状态,后续调用 commit 方法时会执行更新操作。 - *
- * - * @param context 上下文对象 - * @param c 指向数据记录的数据库游标 - */ - public SqlData(Context context, Cursor c) { - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(c); - mDiffDataValues = new ContentValues(); - } - - /** - * 从数据库游标加载数据内容 - *- * 从游标的当前行读取所有数据字段值并初始化对象的成员变量。 - *
- * - * @param c 指向数据记录的数据库游标 - */ - 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 对象设置数据内容 - *- * 解析 JSON 对象中的数据字段,更新当前对象的成员变量。 - * 比较新旧值,将变更记录到差异值集合中。 - *
- * - * @param js 包含数据信息的 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 对象格式。 - *
- * - * @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; - } - - /** - * 提交数据变更到数据库 - *- * 根据当前状态执行插入或更新操作: - * - 如果是新建数据,插入新记录并获取生成的 ID - * - 如果是已存在的数据,更新变更的字段 - *
- * - * @param noteId 关联的笔记 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 - */ - public long getId() { - return mDataId; - } -} diff --git a/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java b/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java deleted file mode 100644 index 3355141..0000000 --- a/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java +++ /dev/null @@ -1,668 +0,0 @@ -/* - * 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; - - -/** - * SQLite 笔记数据类 - *- * 表示本地数据库中的一条笔记记录,负责笔记数据的增删改查操作。 - * 支持与 Google Tasks 的双向同步,能够从 JSON 对象加载内容或将内容导出为 JSON。 - * 区分普通笔记、文件夹和系统文件夹三种类型,提供版本控制和本地修改标记功能。 - *
- */ -public class SqlNote { - private static final String TAG = SqlNote.class.getSimpleName(); - - /** 无效 ID 标识符 */ - private static final int INVALID_ID = -99999; - - /** 笔记表查询投影字段数组 */ - public static final String[] PROJECTION_NOTE = new String[] { - NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, - NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, - 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; - - /** Widget ID 字段在投影数组中的索引 */ - public static final int WIDGET_ID_COLUMN = 10; - - /** Widget 类型字段在投影数组中的索引 */ - 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 Tasks ID 字段在投影数组中的索引 */ - public static final int GTASK_ID_COLUMN = 15; - - /** 版本号字段在投影数组中的索引 */ - public static final int VERSION_COLUMN = 16; - - private Context mContext; - - private ContentResolver mContentResolver; - - private boolean mIsCreate; - - private long mId; - - private long mAlertDate; - - private int mBgColorId; - - private long mCreatedDate; - - private int mHasAttachment; - - private long mModifiedDate; - - private long mParentId; - - private String mSnippet; - - private int mType; - - private int mWidgetId; - - private int mWidgetType; - - private long mOriginParent; - - private long mVersion; - - private ContentValues mDiffNoteValues; - - private ArrayList- * 创建一个尚未保存到数据库的新笔记,初始化所有字段为默认值。 - * 标记为创建状态,后续调用 commit 方法时会执行插入操作。 - *
- * - * @param context 上下文对象,用于获取 ContentResolver 和默认资源 - */ - public SqlNote(Context context) { - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = true; - mId = INVALID_ID; - mAlertDate = 0; - mBgColorId = ResourceParser.getDefaultBgId(context); - mCreatedDate = System.currentTimeMillis(); - mHasAttachment = 0; - mModifiedDate = System.currentTimeMillis(); - mParentId = 0; - mSnippet = ""; - mType = Notes.TYPE_NOTE; - mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; - mWidgetType = Notes.TYPE_WIDGET_INVALIDE; - mOriginParent = 0; - mVersion = 0; - mDiffNoteValues = new ContentValues(); - mDataList = new ArrayList- * 从游标中读取笔记数据并初始化对象,如果笔记类型为普通笔记则加载其数据内容。 - * 标记为非创建状态,后续调用 commit 方法时会执行更新操作。 - *
- * - * @param context 上下文对象 - * @param c 指向笔记记录的数据库游标 - */ - public SqlNote(Context context, Cursor c) { - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(c); - mDataList = new ArrayList- * 根据笔记 ID 从数据库查询记录并初始化对象,如果笔记类型为普通笔记则加载其数据内容。 - * 标记为非创建状态,后续调用 commit 方法时会执行更新操作。 - *
- * - * @param context 上下文对象 - * @param id 笔记在数据库中的 ID - */ - public SqlNote(Context context, long id) { - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(id); - mDataList = new ArrayList- * 根据笔记 ID 查询数据库获取笔记记录,并调用 loadFromCursor(Cursor) 加载数据。 - *
- * - * @param id 笔记在数据库中的 ID - */ - private void loadFromCursor(long id) { - Cursor c = null; - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", - new String[] { - String.valueOf(id) - }, null); - if (c != null) { - c.moveToNext(); - loadFromCursor(c); - } else { - Log.w(TAG, "loadFromCursor: cursor = null"); - } - } finally { - if (c != null) - c.close(); - } - } - - /** - * 从数据库游标加载笔记数据 - *- * 从游标的当前行读取所有笔记字段值并初始化对象的成员变量。 - *
- * - * @param c 指向笔记记录的数据库游标 - */ - private void loadFromCursor(Cursor c) { - mId = c.getLong(ID_COLUMN); - mAlertDate = c.getLong(ALERTED_DATE_COLUMN); - mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); - mCreatedDate = c.getLong(CREATED_DATE_COLUMN); - mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); - mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); - mParentId = c.getLong(PARENT_ID_COLUMN); - mSnippet = c.getString(SNIPPET_COLUMN); - mType = c.getInt(TYPE_COLUMN); - mWidgetId = c.getInt(WIDGET_ID_COLUMN); - mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); - mVersion = c.getLong(VERSION_COLUMN); - } - - /** - * 加载笔记的数据内容 - *- * 从数据库查询当前笔记的所有数据记录(Data 表),并创建 SqlData 对象列表。 - * 仅对普通笔记类型有效,文件夹类型没有数据内容。 - *
- */ - private void loadDataContent() { - Cursor c = null; - mDataList.clear(); - try { - c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, - "(note_id=?)", new String[] { - String.valueOf(mId) - }, null); - if (c != null) { - if (c.getCount() == 0) { - Log.w(TAG, "it seems that the note has not data"); - return; - } - while (c.moveToNext()) { - SqlData data = new SqlData(mContext, c); - mDataList.add(data); - } - } else { - Log.w(TAG, "loadDataContent: cursor = null"); - } - } finally { - if (c != null) - c.close(); - } - } - - /** - * 从 JSON 对象设置笔记内容 - *- * 解析 JSON 对象中的笔记信息和数据,更新当前笔记的字段值。 - * 根据笔记类型(系统文件夹、文件夹、普通笔记)执行不同的更新逻辑。 - * 对于普通笔记,会同时更新其数据内容列表。 - *
- * - * @param js 包含笔记信息的 JSON 对象 - * @return 如果设置成功返回 true,否则返回 false - */ - public boolean setContent(JSONObject js) { - try { - JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { - Log.w(TAG, "cannot set system folder"); - } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { - // for folder we can only update the snnipet and type - String snippet = note.has(NoteColumns.SNIPPET) ? note - .getString(NoteColumns.SNIPPET) : ""; - if (mIsCreate || !mSnippet.equals(snippet)) { - mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); - } - mSnippet = snippet; - - int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) - : Notes.TYPE_NOTE; - if (mIsCreate || mType != type) { - mDiffNoteValues.put(NoteColumns.TYPE, type); - } - mType = type; - } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { - JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; - if (mIsCreate || mId != id) { - mDiffNoteValues.put(NoteColumns.ID, id); - } - mId = id; - - long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note - .getLong(NoteColumns.ALERTED_DATE) : 0; - if (mIsCreate || mAlertDate != alertDate) { - mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); - } - mAlertDate = alertDate; - - int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note - .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); - if (mIsCreate || mBgColorId != bgColorId) { - mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); - } - mBgColorId = bgColorId; - - long createDate = note.has(NoteColumns.CREATED_DATE) ? note - .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); - if (mIsCreate || mCreatedDate != createDate) { - mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); - } - mCreatedDate = createDate; - - int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note - .getInt(NoteColumns.HAS_ATTACHMENT) : 0; - if (mIsCreate || mHasAttachment != hasAttachment) { - mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); - } - mHasAttachment = hasAttachment; - - long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note - .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); - if (mIsCreate || mModifiedDate != modifiedDate) { - mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); - } - mModifiedDate = modifiedDate; - - long parentId = note.has(NoteColumns.PARENT_ID) ? note - .getLong(NoteColumns.PARENT_ID) : 0; - if (mIsCreate || mParentId != parentId) { - mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); - } - mParentId = parentId; - - String snippet = note.has(NoteColumns.SNIPPET) ? note - .getString(NoteColumns.SNIPPET) : ""; - if (mIsCreate || !mSnippet.equals(snippet)) { - mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); - } - mSnippet = snippet; - - int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) - : Notes.TYPE_NOTE; - if (mIsCreate || mType != type) { - mDiffNoteValues.put(NoteColumns.TYPE, type); - } - mType = type; - - int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) - : AppWidgetManager.INVALID_APPWIDGET_ID; - if (mIsCreate || mWidgetId != widgetId) { - mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); - } - mWidgetId = widgetId; - - int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note - .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; - if (mIsCreate || mWidgetType != widgetType) { - mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); - } - mWidgetType = widgetType; - - long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note - .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; - if (mIsCreate || mOriginParent != originParent) { - mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); - } - mOriginParent = originParent; - - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - SqlData sqlData = null; - if (data.has(DataColumns.ID)) { - long dataId = data.getLong(DataColumns.ID); - for (SqlData temp : mDataList) { - if (dataId == temp.getId()) { - sqlData = temp; - } - } - } - - if (sqlData == null) { - sqlData = new SqlData(mContext); - mDataList.add(sqlData); - } - - sqlData.setContent(data); - } - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return false; - } - return true; - } - - /** - * 获取笔记内容的 JSON 对象 - *- * 将当前笔记的所有字段和数据内容导出为 JSON 对象格式。 - * 根据笔记类型生成不同结构的 JSON,普通笔记包含数据数组。 - *
- * - * @return 包含笔记信息的 JSON 对象,如果尚未创建到数据库则返回 null - */ - public JSONObject getContent() { - try { - JSONObject js = new JSONObject(); - - if (mIsCreate) { - Log.e(TAG, "it seems that we haven't created this in database yet"); - return null; - } - - JSONObject note = new JSONObject(); - if (mType == Notes.TYPE_NOTE) { - note.put(NoteColumns.ID, mId); - note.put(NoteColumns.ALERTED_DATE, mAlertDate); - note.put(NoteColumns.BG_COLOR_ID, mBgColorId); - note.put(NoteColumns.CREATED_DATE, mCreatedDate); - note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); - note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); - note.put(NoteColumns.PARENT_ID, mParentId); - note.put(NoteColumns.SNIPPET, mSnippet); - note.put(NoteColumns.TYPE, mType); - note.put(NoteColumns.WIDGET_ID, mWidgetId); - note.put(NoteColumns.WIDGET_TYPE, mWidgetType); - note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); - js.put(GTaskStringUtils.META_HEAD_NOTE, note); - - JSONArray dataArray = new JSONArray(); - for (SqlData sqlData : mDataList) { - JSONObject data = sqlData.getContent(); - if (data != null) { - dataArray.put(data); - } - } - js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); - } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { - note.put(NoteColumns.ID, mId); - note.put(NoteColumns.TYPE, mType); - note.put(NoteColumns.SNIPPET, mSnippet); - js.put(GTaskStringUtils.META_HEAD_NOTE, note); - } - - return js; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - return null; - } - - /** - * 设置父文件夹 ID - *- * 更新笔记的父文件夹 ID,并将变更记录到差异值集合中。 - *
- * - * @param id 新的父文件夹 ID - */ - public void setParentId(long id) { - mParentId = id; - mDiffNoteValues.put(NoteColumns.PARENT_ID, id); - } - - /** - * 设置 Google Tasks ID - *- * 将 Google Tasks 的任务 ID 关联到当前笔记,用于同步标识。 - *
- * - * @param gid Google Tasks 任务 ID - */ - public void setGtaskId(String gid) { - mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); - } - - /** - * 设置同步 ID - *- * 记录最后一次同步的时间戳,用于判断本地和远程数据的同步状态。 - *
- * - * @param syncId 同步时间戳 - */ - public void setSyncId(long syncId) { - mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); - } - - /** - * 重置本地修改标记 - *- * 将本地修改标记设置为 0,表示笔记已同步,无待同步的本地修改。 - *
- */ - public void resetLocalModified() { - mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); - } - - /** - * 获取笔记 ID - * - * @return 笔记在数据库中的 ID,如果尚未创建则返回 INVALID_ID - */ - public long getId() { - return mId; - } - - /** - * 获取父文件夹 ID - * - * @return 父文件夹在数据库中的 ID - */ - public long getParentId() { - return mParentId; - } - - /** - * 获取笔记摘要文本 - * - * @return 笔记的摘要文本 - */ - public String getSnippet() { - return mSnippet; - } - - /** - * 判断是否为普通笔记类型 - * - * @return 如果是普通笔记返回 true,否则返回 false - */ - public boolean isNoteType() { - return mType == Notes.TYPE_NOTE; - } - - /** - * 提交笔记变更到数据库 - *- * 根据当前状态执行插入或更新操作: - * - 如果是新建笔记,插入新记录并获取生成的 ID - * - 如果是已存在的笔记,更新变更的字段 - * - 对于普通笔记,同时提交其数据内容 - *
- * - * @param validateVersion 是否验证版本号,为 true 时仅更新版本号不大于当前版本的记录 - * @throws ActionFailureException 如果创建笔记失败 - * @throws IllegalStateException 如果尝试更新无效 ID 的笔记 - */ - public void commit(boolean validateVersion) { - if (mIsCreate) { - if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { - mDiffNoteValues.remove(NoteColumns.ID); - } - - Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); - try { - mId = Long.valueOf(uri.getPathSegments().get(1)); - } catch (NumberFormatException e) { - Log.e(TAG, "Get note id error :" + e.toString()); - throw new ActionFailureException("create note failed"); - } - if (mId == 0) { - throw new IllegalStateException("Create thread id failed"); - } - - if (mType == Notes.TYPE_NOTE) { - for (SqlData sqlData : mDataList) { - sqlData.commit(mId, false, -1); - } - } - } else { - if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { - Log.e(TAG, "No such note"); - throw new IllegalStateException("Try to update note with invalid id"); - } - if (mDiffNoteValues.size() > 0) { - mVersion ++; - int result = 0; - if (!validateVersion) { - result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" - + NoteColumns.ID + "=?)", new String[] { - String.valueOf(mId) - }); - } else { - // 仅更新版本号不大于当前版本的记录,防止并发更新冲突 - result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" - + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", - new String[] { - String.valueOf(mId), String.valueOf(mVersion) - }); - } - if (result == 0) { - Log.w(TAG, "there is no update. maybe user updates note when syncing"); - } - } - - if (mType == Notes.TYPE_NOTE) { - for (SqlData sqlData : mDataList) { - sqlData.commit(mId, validateVersion, mVersion); - } - } - } - - // 从数据库重新加载最新数据,确保内存状态与数据库一致 - loadFromCursor(mId); - if (mType == Notes.TYPE_NOTE) - loadDataContent(); - - mDiffNoteValues.clear(); - mIsCreate = false; - } -} diff --git a/app/src/main/java/net/micode/notes/gtask/data/Task.java b/app/src/main/java/net/micode/notes/gtask/data/Task.java deleted file mode 100644 index f9f0ef3..0000000 --- a/app/src/main/java/net/micode/notes/gtask/data/Task.java +++ /dev/null @@ -1,499 +0,0 @@ -/* - * 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.text.TextUtils; -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.gtask.exception.ActionFailureException; -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - - -/** - * Google Tasks 任务类 - *- * 继承自 Node,表示 Google Tasks 中的一个任务项。 - * 负责管理任务的完成状态、备注信息、元数据、前驱兄弟节点和父任务列表。 - * 支持与本地笔记的双向同步,能够生成创建和更新动作的 JSON 对象。 - *
- */ -public class Task extends Node { - /** - * 日志标签 - */ - private static final String TAG = Task.class.getSimpleName(); - - /** - * 完成状态标记,true 表示已完成 - */ - private boolean mCompleted; - - /** - * 任务备注信息 - */ - private String mNotes; - - /** - * 元数据 JSON 对象,包含本地笔记的完整信息 - */ - private JSONObject mMetaInfo; - - /** - * 前驱兄弟任务,用于维护任务在列表中的顺序 - */ - private Task mPriorSibling; - - /** - * 父任务列表 - */ - private TaskList mParent; - - /** - * 构造一个新的任务实例 - *- * 初始化所有属性为默认值:未完成、备注为 null、无前驱兄弟、无父列表、无元数据。 - *
- */ - public Task() { - super(); - mCompleted = false; - mNotes = null; - mPriorSibling = null; - mParent = null; - mMetaInfo = null; - } - - /** - * 获取创建动作的 JSON 对象 - *- * 生成用于在远程服务器创建任务的 JSON 请求,包含任务名称、备注、父列表 ID 等信息。 - *
- * - * @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 对象 - *- * 生成用于在远程服务器更新任务的 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; - } - - /** - * 根据远程 JSON 设置内容 - *- * 从远程服务器返回的 JSON 对象中解析并设置任务的属性值,包括 ID、名称、备注、完成状态等。 - *
- * - * @param js 远程服务器返回的 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 设置内容 - *- * 从本地数据库存储的 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 对象,用于存储到本地数据库。 - * 如果是新建任务,创建新的 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; - } - } - - /** - * 设置元数据信息 - *- * 从元数据对象中解析并设置任务的元信息 JSON 对象。 - * 元信息包含本地笔记的完整结构,用于双向同步。 - *
- * - * @param 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 指向本地数据库记录的游标 - * @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 完成状态,true 表示已完成 - */ - 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 完成状态,true 表示已完成 - */ - 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/app/src/main/java/net/micode/notes/gtask/data/TaskList.java b/app/src/main/java/net/micode/notes/gtask/data/TaskList.java deleted file mode 100644 index d454fe7..0000000 --- a/app/src/main/java/net/micode/notes/gtask/data/TaskList.java +++ /dev/null @@ -1,510 +0,0 @@ -/* - * 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; - - -/** - * Google Tasks 任务列表类 - *- * 继承自 Node,表示 Google Tasks 中的一个任务列表(文件夹)。 - * 负责管理任务列表的子任务集合,提供任务的增删改查操作。 - * 支持与本地笔记文件夹的双向同步,能够生成创建和更新动作的 JSON 对象。 - *
- */ -public class TaskList extends Node { - /** - * 日志标签 - */ - private static final String TAG = TaskList.class.getSimpleName(); - - /** - * 任务列表索引 - */ - private int mIndex; - - /** - * 子任务列表 - */ - private ArrayList- * 初始化子任务列表为空,索引设置为 1。 - *
- */ - public TaskList() { - super(); - mChildren = new ArrayList- * 生成用于在远程服务器创建任务列表的 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 对象 - *- * 生成用于在远程服务器更新任务列表的 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; - } - - /** - * 根据远程 JSON 设置内容 - *- * 从远程服务器返回的 JSON 对象中解析并设置任务列表的属性值。 - *
- * - * @param js 远程服务器返回的 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 设置内容 - *- * 从本地数据库存储的 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) { - // 系统文件夹,根据 ID 设置对应的名称 - 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 指向本地数据库记录的游标 - * @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 插入位置索引,必须在 0 到子任务数量之间 - * @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 目标位置索引,必须在 0 到子任务数量减 1 之间 - * @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)); - } - - /** - * 根据 GID 查找子任务 - * - * @param gid Google Tasks 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 索引位置,必须在 0 到子任务数量减 1 之间 - * @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); - } - - /** - * 根据 GID 获取子任务 - * - * @param gid Google Tasks ID - * @return 对应的子任务,如果未找到则返回 null - */ - public Task getChilTaskByGid(String gid) { - for (Task task : mChildren) { - if (task.getGid().equals(gid)) - return task; - } - return null; - } - - /** - * 获取子任务列表 - * - * @return 子任务列表的副本 - */ - public ArrayList- * 用于表示 Google Tasks 同步过程中操作执行失败的情况。 - * 当同步操作(如创建、更新、删除任务或任务列表)失败时抛出此异常。 - * 该异常继承自 RuntimeException,属于非受检异常,调用方可以选择性处理。 - *
- */ -public class ActionFailureException extends RuntimeException { - private static final long serialVersionUID = 4425249765923293627L; - - /** - * 构造一个无详细信息的操作失败异常 - */ - public ActionFailureException() { - super(); - } - - /** - * 构造一个带有详细信息的操作失败异常 - * - * @param paramString 异常的详细信息,描述操作失败的具体原因 - */ - public ActionFailureException(String paramString) { - super(paramString); - } - - /** - * 构造一个带有详细信息和原因的操作失败异常 - * - * @param paramString 异常的详细信息,描述操作失败的具体原因 - * @param paramThrowable 导致此异常的底层异常或错误 - */ - public ActionFailureException(String paramString, Throwable paramThrowable) { - super(paramString, paramThrowable); - } -} diff --git a/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java b/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java deleted file mode 100644 index a7aeedf..0000000 --- a/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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; - -/** - * 网络异常类 - *- * 用于表示 Google Tasks 同步过程中发生的网络相关错误。 - * 当网络连接失败、超时或无法访问 Google Tasks 服务时抛出此异常。 - * 该异常继承自 Exception,属于受检异常,调用方必须处理或继续抛出。 - *
- */ -public class NetworkFailureException extends Exception { - private static final long serialVersionUID = 2107610287180234136L; - - /** - * 构造一个无详细信息的网络异常 - */ - public NetworkFailureException() { - super(); - } - - /** - * 构造一个带有详细信息的网络异常 - * - * @param paramString 异常的详细信息,描述网络失败的具体原因 - */ - public NetworkFailureException(String paramString) { - super(paramString); - } - - /** - * 构造一个带有详细信息和原因的网络异常 - * - * @param paramString 异常的详细信息,描述网络失败的具体原因 - * @param paramThrowable 导致此异常的底层异常或错误 - */ - public NetworkFailureException(String paramString, Throwable paramThrowable) { - super(paramString, paramThrowable); - } -} diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java deleted file mode 100644 index f8ea190..0000000 --- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java +++ /dev/null @@ -1,222 +0,0 @@ - -/* - * 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; - - -/** - * Google Tasks 同步异步任务 - *- * 继承自 AsyncTask,用于在后台执行 Google Tasks 同步操作。 - * 支持进度更新、通知显示和同步完成回调。 - *
- */ -public class GTaskASyncTask extends AsyncTask- * 定义同步完成时的回调方法,用于通知调用方同步任务已结束。 - *
- */ - public interface OnCompleteListener { - /** - * 同步完成时的回调方法 - */ - void onComplete(); - } - - /** 应用上下文 */ - private Context mContext; - - /** 通知管理器 */ - private NotificationManager mNotifiManager; - - /** Google Tasks 管理器实例 */ - private GTaskManager mTaskManager; - - /** 同步完成监听器 */ - private OnCompleteListener mOnCompleteListener; - - /** - * 构造函数 - *- * 初始化异步任务所需的上下文、监听器、通知管理器和任务管理器。 - *
- * - * @param context 应用上下文 - * @param listener 同步完成监听器 - */ - public GTaskASyncTask(Context context, OnCompleteListener listener) { - mContext = context; - mOnCompleteListener = listener; - // 获取系统通知服务 - mNotifiManager = (NotificationManager) mContext - .getSystemService(Context.NOTIFICATION_SERVICE); - // 获取 GTaskManager 单例 - mTaskManager = GTaskManager.getInstance(); - } - - /** - * 取消同步操作 - *- * 调用 GTaskManager 的 cancelSync() 方法取消正在进行的同步。 - *
- */ - public void cancelSync() { - mTaskManager.cancelSync(); - } - - /** - * 发布同步进度 - *- * 调用 AsyncTask 的 publishProgress() 方法发布进度消息到 UI 线程。 - *
- * - * @param message 进度消息 - */ - public void publishProgess(String message) { - publishProgress(new String[] { - message - }); - } - - /** - * 显示同步通知 - *- * 在状态栏显示同步进度或结果通知。 - * 同步成功时跳转到笔记列表,其他情况跳转到设置页面。 - *
- * - * @param tickerId 通知标题字符串资源 ID - * @param content 通知内容文本 - */ - private void showNotification(int tickerId, String content) { - PendingIntent pendingIntent; - // 根据同步结果选择跳转目标 - if (tickerId != R.string.ticker_success) { - // 同步失败或取消,跳转到设置页面 - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE); - } else { - // 同步成功,跳转到笔记列表 - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE); - } - // 构建通知 - Notification.Builder builder = new Notification.Builder(mContext) - .setAutoCancel(true) - .setContentTitle(mContext.getString(R.string.app_name)) - .setContentText(content) - .setContentIntent(pendingIntent) - .setWhen(System.currentTimeMillis()) - .setOngoing(true); - Notification notification=builder.getNotification(); - // 显示通知 - mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); - } - - /** - * 后台执行同步操作 - *- * 在后台线程执行 Google Tasks 同步,发布登录进度并返回同步结果。 - *
- * - * @param unused 未使用的参数 - * @return 同步状态码(GTaskManager.STATE_SUCCESS、STATE_NETWORK_ERROR、STATE_INTERNAL_ERROR、STATE_SYNC_IN_PROGRESS 或 STATE_SYNC_CANCELLED) - */ - @Override - protected Integer doInBackground(Void... unused) { - // 发布登录进度 - publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity - .getSyncAccountName(mContext))); - // 执行同步并返回结果 - return mTaskManager.sync(mContext, this); - } - - /** - * 进度更新回调 - *- * 在 UI 线程更新同步进度,显示通知并发送广播。 - *
- * - * @param progress 进度消息数组 - */ - @Override - protected void onProgressUpdate(String... progress) { - // 显示进度通知 - showNotification(R.string.ticker_syncing, progress[0]); - // 如果上下文是 GTaskSyncService,发送广播 - if (mContext instanceof GTaskSyncService) { - ((GTaskSyncService) mContext).sendBroadcast(progress[0]); - } - } - - /** - * 同步完成回调 - *- * 根据同步结果显示相应的通知,并调用完成监听器。 - * 更新最后同步时间(仅在同步成功时)。 - *
- * - * @param result 同步结果状态码 - */ - @Override - protected void onPostExecute(Integer result) { - // 根据同步结果显示相应通知 - if (result == GTaskManager.STATE_SUCCESS) { - // 同步成功 - showNotification(R.string.ticker_success, mContext.getString( - R.string.success_sync_account, mTaskManager.getSyncAccount())); - // 更新最后同步时间 - NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); - } else if (result == GTaskManager.STATE_NETWORK_ERROR) { - // 网络错误 - showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); - } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { - // 内部错误 - showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); - } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { - // 同步已取消 - showNotification(R.string.ticker_cancel, mContext - .getString(R.string.error_sync_cancelled)); - } - // 调用完成监听器 - if (mOnCompleteListener != null) { - new Thread(new Runnable() { - - public void run() { - mOnCompleteListener.onComplete(); - } - }).start(); - } - } -} diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java deleted file mode 100644 index 8201fbd..0000000 --- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java +++ /dev/null @@ -1,784 +0,0 @@ -/* - * 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.accounts.Account; -import android.accounts.AccountManager; -import android.accounts.AccountManagerFuture; -import android.app.Activity; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; - -import net.micode.notes.gtask.data.Node; -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.GTaskStringUtils; -import net.micode.notes.ui.NotesPreferenceActivity; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.cookie.Cookie; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.LinkedList; -import java.util.List; -import java.util.zip.GZIPInputStream; -import java.util.zip.Inflater; -import java.util.zip.InflaterInputStream; - - -/** - * Google Tasks 客户端类 - *- * 单例模式实现的 Google Tasks API 客户端,负责与 Google Tasks 服务器的网络通信。 - * 提供登录认证、任务列表和任务的增删改查、批量更新等功能。 - * 使用 HTTP 协议与 Google Tasks API 交互,支持 Cookie 认证和会话管理。 - *
- */ -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"; - - /** 单例实例 */ - private static GTaskClient mInstance = null; - - private DefaultHttpClient mHttpClient; - - private String mGetUrl; - - private String mPostUrl; - - private long mClientVersion; - - private boolean mLoggedin; - - private long mLastLoginTime; - - private int mActionId; - - private Account mAccount; - - private JSONArray mUpdateArray; - - /** - * 私有构造函数 - *- * 初始化所有成员变量为默认值,防止外部直接实例化。 - *
- */ - private GTaskClient() { - mHttpClient = null; - mGetUrl = GTASK_GET_URL; - 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 - *- * 检查登录状态和账户信息,必要时重新登录。 - * Cookie 有效期为 5 分钟,超时后需要重新登录。 - * 支持自定义域名账户和标准 Gmail/Googlemail 账户。 - *
- * - * @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 账户获取认证令牌 - *- * 从系统账户管理器获取 Google 账户的认证令牌。 - * 如果 invalidateToken 为 true,会先使旧令牌失效再获取新令牌。 - *
- * - * @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- * 使用认证令牌尝试登录 Google Tasks,如果失败则使令牌失效并重试。 - *
- * - * @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 - *- * 向 Google Tasks 服务器发送 GET 请求进行认证,获取 Cookie 和客户端版本号。 - *
- * - * @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- * 每次调用返回递增的动作 ID,用于标识不同的操作请求。 - *
- * - * @return 动作 ID - */ - private int getActionId() { - return mActionId++; - } - - /** - * 创建 HTTP POST 请求对象 - *- * 配置请求头,设置内容类型为 application/x-www-form-urlencoded。 - *
- * - * @return 配置好的 HttpPost 对象 - */ - private HttpPost createHttpPost() { - HttpPost httpPost = new HttpPost(mPostUrl); - httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); - httpPost.setHeader("AT", "1"); - return httpPost; - } - - /** - * 获取 HTTP 响应内容 - *- * 解析 HTTP 实体的内容,支持 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 服务器 - *- * 将 JSON 数据封装为 POST 请求发送到服务器,并解析返回的 JSON 响应。 - *
- * - * @param js 要发送的 JSON 对象 - * @return 服务器返回的 JSON 对象 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果未登录或 JSON 解析失败 - */ - 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- * 向 Google Tasks 服务器发送创建任务请求,获取服务器分配的任务 ID。 - *
- * - * @param task 要创建的任务对象 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果 JSON 处理失败 - */ - public void createTask(Task task) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // action_list - actionList.put(task.getCreateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // post - JSONObject jsResponse = postRequest(jsPost); - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create task: handing jsonobject failed"); - } - } - - /** - * 创建新的任务列表 - *- * 向 Google Tasks 服务器发送创建任务列表请求,获取服务器分配的任务列表 ID。 - *
- * - * @param tasklist 要创建的任务列表对象 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果 JSON 处理失败 - */ - public void createTaskList(TaskList tasklist) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // action_list - actionList.put(tasklist.getCreateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // post - JSONObject jsResponse = postRequest(jsPost); - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create tasklist: handing jsonobject failed"); - } - } - - /** - * 提交批量更新请求 - *- * 将待更新的节点批量发送到 Google Tasks 服务器。 - * 如果没有待更新的节点,则不执行任何操作。 - *
- * - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果 JSON 处理失败 - */ - public void commitUpdate() throws NetworkFailureException { - if (mUpdateArray != null) { - try { - JSONObject jsPost = new JSONObject(); - - // action_list - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - postRequest(jsPost); - mUpdateArray = null; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("commit update: handing jsonobject failed"); - } - } - } - - /** - * 添加待更新节点到批量更新队列 - *- * 将节点添加到更新队列中,当队列超过 10 个节点时自动提交。 - *
- * - * @param node 要更新的节点,如果为 null 则不执行任何操作 - * @throws NetworkFailureException 如果提交更新时网络请求失败 - */ - public void addUpdateNode(Node node) throws NetworkFailureException { - if (node != null) { - // too many update items may result in an error - // set max to 10 items - 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 如果 JSON 处理失败 - */ - 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"); - } - } - - /** - * 删除节点 - *- * 向 Google Tasks 服务器发送删除节点请求,将节点标记为已删除。 - *
- * - * @param node 要删除的节点 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果 JSON 处理失败 - */ - 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"); - } - } - - /** - * 获取所有任务列表 - *- * 从 Google Tasks 服务器获取当前账户的所有任务列表。 - *
- * - * @return 包含所有任务列表信息的 JSON 数组 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果未登录或 JSON 解析失败 - */ - 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"); - } - } - - /** - * 获取指定任务列表中的所有任务 - *- * 从 Google Tasks 服务器获取指定任务列表中的所有任务。 - *
- * - * @param listGid 任务列表的 Google ID - * @return 包含该任务列表中所有任务信息的 JSON 数组 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果 JSON 处理失败 - */ - 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"); - } - } - - /** - * 获取同步账户 - * - * @return 当前登录的 Google 账户 - */ - public Account getSyncAccount() { - return mAccount; - } - - /** - * 重置更新数组 - *- * 清空待更新的节点队列,取消所有未提交的更新操作。 - *
- */ - public void resetUpdateArray() { - mUpdateArray = null; - } -} diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java deleted file mode 100644 index 6beb7a7..0000000 --- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java +++ /dev/null @@ -1,857 +0,0 @@ -/* - * 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; - - -/** - * Google Tasks 同步管理器 - *- * 单例模式实现的同步管理器,负责本地笔记与 Google Tasks 之间的数据同步。 - * 提供完整的双向同步功能,包括文件夹、笔记的增删改查操作。 - * 支持同步状态管理、冲突解决和元数据维护。 - *
- */ -public class GTaskManager { - private static final String TAG = GTaskManager.class.getSimpleName(); - - /** 同步成功状态码 */ - public static final int STATE_SUCCESS = 0; - - /** 网络错误状态码 */ - public static final int STATE_NETWORK_ERROR = 1; - - /** 内部错误状态码 */ - public static final int STATE_INTERNAL_ERROR = 2; - - /** 同步进行中状态码 */ - public static final int STATE_SYNC_IN_PROGRESS = 3; - - /** 同步已取消状态码 */ - public static final int STATE_SYNC_CANCELLED = 4; - - private static GTaskManager mInstance = null; - - private Activity mActivity; - - private Context mContext; - - private ContentResolver mContentResolver; - - private boolean mSyncing; - - private boolean mCancelled; - - private HashMap- * 初始化所有成员变量,防止外部直接实例化。 - *
- */ - private GTaskManager() { - mSyncing = false; - mCancelled = false; - mGTaskListHashMap = new HashMap- * 使用双重检查锁定确保线程安全的单例实现。 - *
- * - * @return GTaskManager 单例实例 - */ - public static synchronized GTaskManager getInstance() { - if (mInstance == null) { - mInstance = new GTaskManager(); - } - return mInstance; - } - - /** - * 设置 Activity 上下文 - *- * 用于获取 Google 账户的认证令牌。 - *
- * - * @param activity Activity 上下文 - */ - public synchronized void setActivityContext(Activity activity) { - // used for getting authtoken - mActivity = activity; - } - - /** - * 执行同步操作 - *- * 执行本地笔记与 Google Tasks 之间的双向同步。 - * 包括登录 Google Tasks、初始化任务列表、同步内容等步骤。 - *
- * - * @param context 应用上下文 - * @param asyncTask 异步任务对象,用于发布进度 - * @return 同步状态码(STATE_SUCCESS、STATE_NETWORK_ERROR、STATE_INTERNAL_ERROR、STATE_SYNC_IN_PROGRESS 或 STATE_SYNC_CANCELLED) - */ - public int sync(Context context, GTaskASyncTask asyncTask) { - if (mSyncing) { - Log.d(TAG, "Sync is in progress"); - return STATE_SYNC_IN_PROGRESS; - } - mContext = context; - mContentResolver = mContext.getContentResolver(); - mSyncing = true; - mCancelled = false; - mGTaskListHashMap.clear(); - mGTaskHashMap.clear(); - mMetaHashMap.clear(); - mLocalDeleteIdMap.clear(); - mGidToNid.clear(); - mNidToGid.clear(); - - try { - GTaskClient client = GTaskClient.getInstance(); - client.resetUpdateArray(); - - // login google task - if (!mCancelled) { - if (!client.login(mActivity)) { - throw new NetworkFailureException("login google task failed"); - } - } - - // get the task list from google - asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); - initGTaskList(); - - // do content sync work - asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); - syncContent(); - } catch (NetworkFailureException e) { - Log.e(TAG, e.toString()); - return STATE_NETWORK_ERROR; - } catch (ActionFailureException e) { - Log.e(TAG, e.toString()); - return STATE_INTERNAL_ERROR; - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return STATE_INTERNAL_ERROR; - } finally { - mGTaskListHashMap.clear(); - mGTaskHashMap.clear(); - mMetaHashMap.clear(); - mLocalDeleteIdMap.clear(); - mGidToNid.clear(); - mNidToGid.clear(); - mSyncing = false; - } - - return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; - } - - private void initGTaskList() throws NetworkFailureException { - if (mCancelled) - return; - GTaskClient client = GTaskClient.getInstance(); - try { - JSONArray jsTaskLists = client.getTaskLists(); - - // init meta list first - mMetaList = null; - for (int i = 0; i < jsTaskLists.length(); i++) { - JSONObject object = jsTaskLists.getJSONObject(i); - String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); - - if (name - .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { - mMetaList = new TaskList(); - mMetaList.setContentByRemoteJSON(object); - - // load meta data - JSONArray jsMetas = client.getTaskList(gid); - for (int j = 0; j < jsMetas.length(); j++) { - object = (JSONObject) jsMetas.getJSONObject(j); - MetaData metaData = new MetaData(); - metaData.setContentByRemoteJSON(object); - if (metaData.isWorthSaving()) { - mMetaList.addChildTask(metaData); - if (metaData.getGid() != null) { - mMetaHashMap.put(metaData.getRelatedGid(), metaData); - } - } - } - } - } - - // create meta list if not existed - if (mMetaList == null) { - mMetaList = new TaskList(); - mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META); - GTaskClient.getInstance().createTaskList(mMetaList); - } - - // init task list - for (int i = 0; i < jsTaskLists.length(); i++) { - JSONObject object = jsTaskLists.getJSONObject(i); - String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); - - if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) - && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META)) { - TaskList tasklist = new TaskList(); - tasklist.setContentByRemoteJSON(object); - mGTaskListHashMap.put(gid, tasklist); - mGTaskHashMap.put(gid, tasklist); - - // load tasks - JSONArray jsTasks = client.getTaskList(gid); - for (int j = 0; j < jsTasks.length(); j++) { - object = (JSONObject) jsTasks.getJSONObject(j); - gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - Task task = new Task(); - task.setContentByRemoteJSON(object); - if (task.isWorthSaving()) { - task.setMetaInfo(mMetaHashMap.get(gid)); - tasklist.addChildTask(task); - mGTaskHashMap.put(gid, task); - } - } - } - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("initGTaskList: handing JSONObject failed"); - } - } - - private void syncContent() throws NetworkFailureException { - int syncType; - Cursor c = null; - String gid; - Node node; - - mLocalDeleteIdMap.clear(); - - if (mCancelled) { - return; - } - - // for local deleted note - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type<>? AND parent_id=?)", new String[] { - String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) - }, null); - if (c != null) { - while (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); - } - - mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); - } - } else { - Log.w(TAG, "failed to query trash folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // sync folder first - syncFolder(); - - // for note existing in database - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type=? AND parent_id<>?)", new String[] { - String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) - }, NoteColumns.TYPE + " DESC"); - if (c != null) { - while (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); - mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); - syncType = node.getSyncAction(c); - } else { - if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { - // local add - syncType = Node.SYNC_ACTION_ADD_REMOTE; - } else { - // remote delete - syncType = Node.SYNC_ACTION_DEL_LOCAL; - } - } - doContentSync(syncType, node, c); - } - } else { - Log.w(TAG, "failed to query existing note in database"); - } - - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // go through remaining items - Iterator- * 设置取消标志,停止正在进行的同步操作。 - *
- */ - public void cancelSync() { - mCancelled = true; - } -} diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java deleted file mode 100644 index d207f97..0000000 --- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * 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.app.Service; -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.os.IBinder; - -/** - * Google Tasks 同步服务 - *- * 负责管理本地笔记与 Google Tasks 之间的后台同步操作。 - * 通过异步任务执行同步,支持同步状态广播和进度更新。 - *
- */ -public class GTaskSyncService extends Service { - /** Intent 附加参数名称,用于指定同步操作类型 */ - public final static String ACTION_STRING_NAME = "sync_action_type"; - - /** 启动同步操作的 Action 值 */ - public final static int ACTION_START_SYNC = 0; - - /** 取消同步操作的 Action 值 */ - public final static int ACTION_CANCEL_SYNC = 1; - - /** 无效的 Action 值 */ - public final static int ACTION_INVALID = 2; - - /** 同步服务广播名称 */ - public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; - - /** 广播附加参数名称,用于标识是否正在同步 */ - public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; - - /** 广播附加参数名称,用于传递同步进度消息 */ - public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; - - /** 同步异步任务实例 */ - private static GTaskASyncTask mSyncTask = null; - - /** 同步进度消息 */ - private static String mSyncProgress = ""; - - /** - * 启动同步操作 - *- * 创建并执行 GTaskASyncTask 异步任务,监听同步完成事件。 - * 同步完成后发送广播并停止服务。 - *
- */ - private void startSync() { - // 检查是否已有同步任务在运行 - if (mSyncTask == null) { - mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { - public void onComplete() { - // 清空同步任务引用 - mSyncTask = null; - // 发送同步完成广播 - sendBroadcast(""); - // 停止服务 - stopSelf(); - } - }); - // 发送同步开始广播 - sendBroadcast(""); - // 执行异步同步任务 - mSyncTask.execute(); - } - } - - /** - * 取消同步操作 - *- * 如果存在正在运行的同步任务,则调用其 cancelSync() 方法取消同步。 - *
- */ - private void cancelSync() { - if (mSyncTask != null) { - // 取消异步同步任务 - mSyncTask.cancelSync(); - } - } - - /** - * 服务创建时的回调 - *- * 初始化同步任务为 null。 - *
- */ - @Override - public void onCreate() { - mSyncTask = null; - } - - /** - * 服务启动命令的回调 - *- * 根据 Intent 中的 Action 类型执行相应的同步操作。 - * 支持 ACTION_START_SYNC 和 ACTION_CANCEL_SYNC 两种操作。 - *
- * - * @param intent 启动服务的 Intent,包含 Action 类型参数 - * @param flags 启动标志 - * @param startId 启动 ID - * @return START_STICKY 表示服务被杀死后会自动重启 - */ - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - Bundle bundle = intent.getExtras(); - // 检查 Intent 是否包含 Action 参数 - if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { - // 根据 Action 类型执行相应操作 - 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(); - } - } - - /** - * 绑定服务的回调 - *- * 本服务不支持绑定,返回 null。 - *
- * - * @param intent 绑定服务的 Intent - * @return null,表示不支持绑定 - */ - public IBinder onBind(Intent intent) { - return null; - } - - /** - * 发送同步状态广播 - *- * 向应用发送广播,包含当前同步状态和进度消息。 - *
- * - * @param msg 同步进度消息 - */ - public void sendBroadcast(String msg) { - // 更新同步进度消息 - mSyncProgress = msg; - Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); - // 添加是否正在同步的标志 - intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); - // 添加进度消息 - intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); - // 发送广播 - sendBroadcast(intent); - } - - /** - * 启动同步服务 - *- * 设置 Activity 上下文到 GTaskManager,然后启动同步服务执行同步操作。 - *
- * - * @param activity Activity 上下文,用于获取 Google 账户认证信息 - */ - public static void startSync(Activity 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); - } - - /** - * 取消同步服务 - *- * 启动同步服务并发送取消同步的命令。 - *
- * - * @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/app/src/main/java/net/micode/notes/model/Note.java b/app/src/main/java/net/micode/notes/model/Note.java deleted file mode 100644 index 4cbd456..0000000 --- a/app/src/main/java/net/micode/notes/model/Note.java +++ /dev/null @@ -1,425 +0,0 @@ -/* - * 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; - - -/** - * 笔记数据模型类 - *- * 负责管理笔记的基本信息和数据内容,支持笔记的创建、修改和同步操作。 - * 包含笔记元数据(如创建时间、修改时间、父文件夹等)和笔记数据(文本、通话记录等)。 - *
- */ -public class Note { - /** 笔记差异值,用于记录需要同步的字段变更 */ - private ContentValues mNoteDiffValues; - - /** 笔记数据对象,包含文本数据和通话数据 */ - private NoteData mNoteData; - - /** 日志标签 */ - private static final String TAG = "Note"; - - /** - * 创建新笔记 ID - *- * 在数据库中创建一条新笔记记录,并返回其 ID。 - * 初始化笔记的创建时间、修改时间、类型和父文件夹 ID。 - *
- * - * @param context 应用上下文 - * @param folderId 父文件夹 ID - * @return 新创建的笔记 ID,失败时返回 0 - */ - public static synchronized long getNewNoteId(Context context, long folderId) { - // 在数据库中创建新笔记 - 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 { - // 从 URI 中提取笔记 ID - 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 属性键名 - * @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 数据键名 - * @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 - * - * @return 文本数据 ID - */ - public long getTextDataId() { - return mNoteData.mTextDataId; - } - - /** - * 设置通话数据 ID - *- * 设置笔记通话数据的数据库记录 ID。 - *
- * - * @param id 通话数据 ID - */ - public void setCallDataId(long id) { - mNoteData.setCallDataId(id); - } - - /** - * 设置通话数据 - *- * 设置笔记的通话数据内容。 - *
- * - * @param key 数据键名 - * @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 应用上下文 - * @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; - } - - /** - * 理论上,数据变更后应更新 {@link NoteColumns#LOCAL_MODIFIED} 和 - * {@link NoteColumns#MODIFIED_DATE}。为数据安全,即使更新失败也更新笔记数据信息 - */ - if (context.getContentResolver().update( - ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, - null) == 0) { - Log.e(TAG, "Update note error, should not happen"); - // 不返回,继续执行 - } - 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"; - - /** - * 构造函数 - *- * 初始化文本数据和通话数据的 ContentValues 对象。 - *
- */ - 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,必须大于 0 - */ - void setTextDataId(long id) { - if(id <= 0) { - throw new IllegalArgumentException("Text data id should larger than 0"); - } - mTextDataId = id; - } - - /** - * 设置通话数据 ID - *- * 设置通话数据的数据库记录 ID。 - *
- * - * @param id 通话数据 ID,必须大于 0 - */ - void setCallDataId(long id) { - if (id <= 0) { - throw new IllegalArgumentException("Call data id should larger than 0"); - } - mCallDataId = id; - } - - /** - * 设置通话数据 - *- * 设置笔记的通话数据内容,并标记为本地修改。 - *
- * - * @param key 数据键名 - * @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 数据键名 - * @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 - *- * 将文本数据和通话数据的修改同步到数据库。 - * 支持新增和更新操作。 - *
- * - * @param context 应用上下文 - * @param noteId 笔记 ID - * @return 笔记 URI,失败时返回 null - */ - Uri pushIntoContentResolver(Context context, long noteId) { - /** - * 安全性检查 - */ - if (noteId <= 0) { - throw new IllegalArgumentException("Wrong note id:" + noteId); - } - - ArrayList- * 表示正在编辑或查看的笔记对象,提供笔记的加载、保存和修改功能。 - * 支持文本笔记和通话记录笔记两种类型,包含笔记的所有属性和设置监听器。 - *
- */ -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; - - /** Widget ID */ - private int mWidgetId; - - /** Widget 类型 */ - private int mWidgetType; - - /** 父文件夹 ID */ - private long mFolderId; - - /** 应用上下文 */ - private Context mContext; - - /** 日志标签 */ - private static final String TAG = "WorkingNote"; - - /** 是否已删除 */ - private boolean mIsDeleted; - - /** 笔记设置变更监听器 */ - private NoteSettingChangedListener mNoteSettingStatusListener; - - /** 数据查询投影 - 笔记数据 */ - public static final String[] DATA_PROJECTION = new String[] { - DataColumns.ID, - DataColumns.CONTENT, - DataColumns.MIME_TYPE, - DataColumns.DATA1, - DataColumns.DATA2, - DataColumns.DATA3, - DataColumns.DATA4, - }; - - /** 数据查询投影 - 笔记元数据 */ - 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; - - /** 数据 MIME 类型列索引 */ - 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; - - /** 笔记 Widget ID 列索引 */ - private static final int NOTE_WIDGET_ID_COLUMN = 3; - - /** 笔记 Widget 类型列索引 */ - private static final int NOTE_WIDGET_TYPE_COLUMN = 4; - - /** 笔记修改日期列索引 */ - private static final int NOTE_MODIFIED_DATE_COLUMN = 5; - - /** - * 新建笔记构造函数 - *- * 创建一个新的空笔记对象,初始化所有属性为默认值。 - *
- * - * @param context 应用上下文 - * @param folderId 父文件夹 ID - */ - // New note construct - 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; - } - - /** - * 已有笔记构造函数 - *- * 从数据库加载现有笔记数据,初始化笔记对象。 - *
- * - * @param context 应用上下文 - * @param noteId 笔记 ID - * @param folderId 父文件夹 ID - */ - // Existing note construct - private WorkingNote(Context context, long noteId, long folderId) { - mContext = context; - mNoteId = noteId; - mFolderId = folderId; - mIsDeleted = false; - mNote = new Note(); - loadNote(); - } - - /** - * 加载笔记元数据 - *- * 从数据库加载笔记的基本信息,包括父文件夹、背景颜色、Widget 信息等。 - *
- */ - 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(); - } - - /** - * 加载笔记数据内容 - *- * 从数据库加载笔记的详细数据,包括文本内容和通话记录。 - *
- */ - 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 Widget ID - * @param widgetType Widget 类型 - * @param defaultBgColorId 默认背景颜色 ID - * @return 新创建的 WorkingNote 对象 - */ - 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 加载的 WorkingNote 对象 - */ - public static WorkingNote load(Context context, long id) { - return new WorkingNote(context, id, 0); - } - - /** - * 保存笔记 - *- * 将笔记的修改保存到数据库。 - * 如果笔记不存在则创建新笔记,否则更新现有笔记。 - * 如果有 Widget 则更新 Widget 内容。 - *
- * - * @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); - - /** - * 如果存在该笔记的 Widget,则更新 Widget 内容 - */ - if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID - && mWidgetType != Notes.TYPE_WIDGET_INVALIDE - && mNoteSettingStatusListener != null) { - mNoteSettingStatusListener.onWidgetChanged(); - } - return true; - } else { - return false; - } - } - - /** - * 检查笔记是否存在于数据库 - * - * @return 如果笔记 ID 大于 0 返回 true,否则返回 false - */ - public boolean existInDatabase() { - return mNoteId > 0; - } - - /** - * 检查是否值得保存 - *- * 判断笔记是否有需要保存的修改。 - *
- * - * @return 如果值得保存返回 true,否则返回 false - */ - private boolean isWorthSaving() { - if (mIsDeleted || (!existInDatabase() && 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); - } - } - - /** - * 标记删除 - *- * 标记笔记为删除状态,并更新 Widget。 - *
- * - * @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 - *- * 设置笔记的背景颜色,并通知监听器。 - *
- * - * @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)); - } - } - - /** - * 设置 Widget 类型 - * - * @param type Widget 类型 - */ - public void setWidgetType(int type) { - if (type != mWidgetType) { - mWidgetType = type; - mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); - } - } - - /** - * 设置 Widget ID - * - * @param id Widget ID - */ - public void setWidgetId(int id) { - if (id != mWidgetId) { - mWidgetId = id; - mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); - } - } - - /** - * 设置工作文本 - *- * 设置笔记的文本内容。 - *
- * - * @param text 文本内容 - */ - public void setWorkingText(String text) { - if (!TextUtils.equals(mContent, text)) { - mContent = text; - mNote.setTextData(DataColumns.CONTENT, mContent); - } - } - - /** - * 转换为通话记录笔记 - *- * 将笔记转换为通话记录类型,设置电话号码和通话日期。 - *
- * - * @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 - * - * @return 背景颜色资源 ID - */ - public int getBgColorResId() { - return NoteBgResources.getNoteBgResource(mBgColorId); - } - - /** - * 获取背景颜色 ID - * - * @return 背景颜色 ID - */ - public int getBgColorId() { - return mBgColorId; - } - - /** - * 获取标题背景资源 ID - * - * @return 标题背景资源 ID - */ - public int getTitleBgResId() { - return NoteBgResources.getNoteTitleBgResource(mBgColorId); - } - - /** - * 获取清单模式 - * - * @return 清单模式值 - */ - public int getCheckListMode() { - return mMode; - } - - /** - * 获取笔记 ID - * - * @return 笔记 ID - */ - public long getNoteId() { - return mNoteId; - } - - /** - * 获取父文件夹 ID - * - * @return 父文件夹 ID - */ - public long getFolderId() { - return mFolderId; - } - - /** - * 获取 Widget ID - * - * @return Widget ID - */ - public int getWidgetId() { - return mWidgetId; - } - - /** - * 获取 Widget 类型 - * - * @return Widget 类型 - */ - public int getWidgetType() { - return mWidgetType; - } - - /** - * 笔记设置变更监听器接口 - *- * 定义笔记设置变更时的回调方法,用于通知 UI 更新。 - *
- */ - public interface NoteSettingChangedListener { - /** - * 当前笔记背景颜色变更时调用 - */ - void onBackgroundColorChanged(); - - /** - * 用户设置闹钟时调用 - * - * @param date 提醒日期 - * @param set 是否设置提醒 - */ - void onClockAlertChanged(long date, boolean set); - - /** - * 用户从 Widget 创建笔记时调用 - */ - void onWidgetChanged(); - - /** - * 在清单模式和普通模式之间切换时调用 - * - * @param oldMode 变更前的模式 - * @param newMode 变更后的模式 - */ - void onCheckListModeChanged(int oldMode, int newMode); - } -} diff --git a/app/src/main/java/net/micode/notes/tool/BackupUtils.java b/app/src/main/java/net/micode/notes/tool/BackupUtils.java deleted file mode 100644 index 10c3994..0000000 --- a/app/src/main/java/net/micode/notes/tool/BackupUtils.java +++ /dev/null @@ -1,460 +0,0 @@ -/* - * 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"; - // Singleton stuff - /** 单例实例 */ - private static BackupUtils sInstance; - - /** - * 获取备份工具类的单例实例 - * - * @param context 应用上下文 - * @return 备份工具类实例 - */ - public static synchronized BackupUtils getInstance(Context context) { - if (sInstance == null) { - sInstance = new BackupUtils(context); - } - return sInstance; - } - - /** - * 备份或恢复的状态常量 - *- * 以下状态常量用于表示备份或恢复操作的状态。 - *
- */ - // Currently, the sdcard is not mounted - /** SD 卡未挂载 */ - public static final int STATE_SD_CARD_UNMOUONTED = 0; - // The backup file not exist - /** 备份文件不存在 */ - public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; - // The data is not well formated, may be changed by other programs - /** 数据格式损坏,可能被其他程序修改 */ - public static final int STATE_DATA_DESTROIED = 2; - // Some run-time exception which causes restore or backup fails - /** 系统错误,运行时异常导致备份或恢复失败 */ - public static final int STATE_SYSTEM_ERROR = 3; - // Backup or restore success - /** 备份或恢复成功 */ - public static final int STATE_SUCCESS = 4; - - /** 文本导出对象 */ - private TextExport mTextExport; - - /** - * 私有构造函数 - * - * @param context 应用上下文 - */ - private BackupUtils(Context context) { - mTextExport = new TextExport(context); - } - - /** - * 检查外部存储是否可用 - * - * @return 如果外部存储已挂载且可读写则返回 true,否则返回 false - */ - private static boolean externalStorageAvailable() { - return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); - } - - /** - * 导出笔记数据为文本文件 - * - * @return 导出状态码,可能为 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 - }; - - /** 笔记 ID 列索引 */ - 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; - - /** 数据 MIME 类型列索引 */ - 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; - - /** - * 构造函数 - * - * @param context 应用上下文 - */ - public TextExport(Context context) { - TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); - mContext = context; - mFileName = ""; - mFileDirectory = ""; - } - - /** - * 获取指定格式的文本 - * - * @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(); - } - } - - /** - * 导出指定笔记到输出流 - *- * 查询笔记的所有数据,根据 MIME 类型分别处理通话记录和普通笔记。 - *
- * - * @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()); - } - } - - /** - * 导出笔记数据为文本文件 - *- * 将所有笔记、文件夹和通话记录导出为用户可读的文本文件。 - * 首先导出文件夹及其笔记,然后导出根目录下的笔记。 - *
- * - * @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; - } - - /** - * 获取导出文本文件的输出流 - *- * 在 SD 卡上创建导出文件,并返回对应的 PrintStream。 - *
- * - * @return PrintStream 对象,如果创建失败则返回 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 卡上生成导出文本文件 - *- * 在指定的路径下创建导出文件,如果目录不存在则创建目录。 - *
- * - * @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/app/src/main/java/net/micode/notes/tool/DataUtils.java b/app/src/main/java/net/micode/notes/tool/DataUtils.java deleted file mode 100644 index d982351..0000000 --- a/app/src/main/java/net/micode/notes/tool/DataUtils.java +++ /dev/null @@ -1,439 +0,0 @@ -/* - * 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; - - -/** - * 数据工具类 - *- * 提供笔记数据的批量操作、查询和统计功能。 - * 支持批量删除、移动笔记,以及各种数据查询操作。 - *
- */ -public class DataUtils { - /** 日志标签 */ - public static final String TAG = "DataUtils"; - - /** - * 批量删除笔记 - *- * 从数据库中批量删除指定 ID 的笔记。 - * 跳过系统根文件夹,不允许删除系统文件夹。 - *
- * - * @param resolver ContentResolver 对象 - * @param ids 要删除的笔记 ID 集合 - * @return 如果删除成功返回 true,否则返回 false - */ - public static boolean batchDeleteNotes(ContentResolver resolver, HashSet- * 将笔记从源文件夹移动到目标文件夹,并记录原始父文件夹 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); - } - - /** - * 批量移动笔记到指定文件夹 - *- * 将多个笔记批量移动到目标文件夹。 - *
- * - * @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) { - Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, - NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + - " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + - " AND " + NoteColumns.SNIPPET + "=?", - new String[] { name }, null); - boolean exist = false; - if(cursor != null) { - if(cursor.getCount() > 0) { - exist = true; - } - cursor.close(); - } - return exist; - } - - /** - * 获取文件夹中的 Widget 信息 - *- * 获取指定文件夹下所有笔记关联的 Widget 信息。 - *
- * - * @param resolver ContentResolver 对象 - * @param folderId 文件夹 ID - * @return Widget 属性集合,如果没有则返回 null - */ - public static HashSet- * 查询指定笔记 ID 关联的通话记录中的电话号码。 - *
- * - * @param resolver ContentResolver 对象 - * @param noteId 笔记 ID - * @return 电话号码,如果未找到则返回空字符串 - */ - public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { - Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, - new String [] { CallNote.PHONE_NUMBER }, - 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 的摘要内容。 - *
- * - * @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/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java b/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java deleted file mode 100644 index ce9eb54..0000000 --- a/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * 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; - -/** - * Google Tasks 字符串常量工具类 - *- * 定义与 Google Tasks 同步相关的所有 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/app/src/main/java/net/micode/notes/tool/ResourceParser.java b/app/src/main/java/net/micode/notes/tool/ResourceParser.java deleted file mode 100644 index 4677289..0000000 --- a/app/src/main/java/net/micode/notes/tool/ResourceParser.java +++ /dev/null @@ -1,321 +0,0 @@ -/* - * 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; - -/** - * 资源解析工具类 - *- * 提供笔记背景颜色、字体大小、Widget 样式等资源的解析和获取功能。 - * 支持多种颜色主题和字体大小的配置。 - *
- */ -public class ResourceParser { - - /** 黄色背景 */ - public static final int YELLOW = 0; - - /** 蓝色背景 */ - public static final int BLUE = 1; - - /** 白色背景 */ - public static final int WHITE = 2; - - /** 绿色背景 */ - public static final int GREEN = 3; - - /** 红色背景 */ - public static final int RED = 4; - - /** 默认背景颜色 */ - public static final int BG_DEFAULT_COLOR = YELLOW; - - /** 小号字体 */ - public static final int TEXT_SMALL = 0; - - /** 中号字体 */ - public static final int TEXT_MEDIUM = 1; - - /** 大号字体 */ - public static final int TEXT_LARGE = 2; - - /** 超大号字体 */ - public static final int TEXT_SUPER = 3; - - /** 默认字体大小 */ - public static final int 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(0-4) - * @return 背景资源 ID - */ - public static int getNoteBgResource(int id) { - return BG_EDIT_RESOURCES[id]; - } - - /** - * 获取笔记标题栏背景资源 ID - * - * @param id 背景颜色 ID(0-4) - * @return 标题栏背景资源 ID - */ - public static int getNoteTitleBgResource(int id) { - return BG_EDIT_TITLE_RESOURCES[id]; - } - } - - /** - * 获取默认背景颜色 ID - *- * 根据用户设置返回默认背景颜色。 - * 如果用户启用了随机背景颜色,则随机返回一个颜色 ID。 - *
- * - * @param context 应用上下文 - * @return 背景颜色 ID(0-4) - */ - 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(0-4) - * @return 首项背景资源 ID - */ - public static int getNoteBgFirstRes(int id) { - return BG_FIRST_RESOURCES[id]; - } - - /** - * 获取笔记列表末项背景资源 ID - * - * @param id 背景颜色 ID(0-4) - * @return 末项背景资源 ID - */ - public static int getNoteBgLastRes(int id) { - return BG_LAST_RESOURCES[id]; - } - - /** - * 获取笔记列表单项背景资源 ID - * - * @param id 背景颜色 ID(0-4) - * @return 单项背景资源 ID - */ - public static int getNoteBgSingleRes(int id) { - return BG_SINGLE_RESOURCES[id]; - } - - /** - * 获取笔记列表中间项背景资源 ID - * - * @param id 背景颜色 ID(0-4) - * @return 中间项背景资源 ID - */ - public static int getNoteBgNormalRes(int id) { - return BG_NORMAL_RESOURCES[id]; - } - - /** - * 获取文件夹背景资源 ID - * - * @return 文件夹背景资源 ID - */ - public static int getFolderBgRes() { - return R.drawable.list_folder; - } - } - - /** - * Widget 背景资源类 - *- * 提供桌面 Widget 的背景颜色资源。 - * 支持 2x2 和 4x4 两种尺寸的 Widget。 - *
- */ - public static class WidgetBgResources { - /** 2x2 Widget 背景资源数组 */ - private final static int [] BG_2X_RESOURCES = new int [] { - R.drawable.widget_2x_yellow, - R.drawable.widget_2x_blue, - R.drawable.widget_2x_white, - R.drawable.widget_2x_green, - R.drawable.widget_2x_red, - }; - - /** - * 获取 2x2 Widget 背景资源 ID - * - * @param id 背景颜色 ID(0-4) - * @return 2x2 Widget 背景资源 ID - */ - public static int getWidget2xBgResource(int id) { - return BG_2X_RESOURCES[id]; - } - - /** 4x4 Widget 背景资源数组 */ - private final static int [] BG_4X_RESOURCES = new int [] { - R.drawable.widget_4x_yellow, - R.drawable.widget_4x_blue, - R.drawable.widget_4x_white, - R.drawable.widget_4x_green, - R.drawable.widget_4x_red - }; - - /** - * 获取 4x4 Widget 背景资源 ID - * - * @param id 背景颜色 ID(0-4) - * @return 4x4 Widget 背景资源 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 超出范围,则返回默认字体大小。 - *
- * - * @param id 字体大小 ID(0-3) - * @return 文本外观样式资源 ID - */ - public static int getTexAppearanceResource(int id) { - /** - * HACKME: 修复在 SharedPreferences 中存储资源 ID 的 bug。 - * ID 可能大于资源数组的长度,在这种情况下, - * 返回 {@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/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java b/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java deleted file mode 100644 index 09181bf..0000000 --- a/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * 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; - -/** - * 闹钟提醒活动 - * - * 这个类负责显示笔记提醒的闹钟界面,当笔记设置的提醒时间到达时, - * 由AlarmReceiver启动此活动,显示笔记内容摘要并播放闹钟声音。 - * - * 主要功能: - * 1. 在锁屏状态下显示闹钟界面 - * 2. 显示笔记内容摘要 - * 3. 播放系统闹钟声音 - * 4. 提供操作选项(关闭提醒或查看笔记) - * - * @see NoteEditActivity - * @see net.micode.notes.tool.DataUtils - */ -public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { - // 当前提醒的笔记ID - private long mNoteId; - // 笔记内容摘要 - private String mSnippet; - // 摘要预览最大长度 - private static final int SNIPPET_PREW_MAX_LEN = 60; - // 媒体播放器,用于播放闹钟声音 - MediaPlayer mPlayer; - - /** - * 活动创建时的初始化方法 - * - * 设置窗口属性,获取笔记信息,检查笔记是否存在, - * 如果存在则显示提醒对话框并播放闹钟声音 - * - * @param savedInstanceState 保存的实例状态 - */ - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - // 请求无标题窗口 - requestWindowFeature(Window.FEATURE_NO_TITLE); - - final Window win = getWindow(); - // 添加FLAG_SHOW_WHEN_LOCKED标志,使活动可以在锁屏界面上显示 - 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 intent = getIntent(); - - try { - // 从Intent中解析出笔记ID - mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); - // 通过笔记ID获取笔记内容摘要 - 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(); - } - } - - /** - * 检查屏幕是否处于开启状态 - * - * @return 如果屏幕开启返回true,否则返回false - */ - private boolean isScreenOn() { - PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); - return pm.isScreenOn(); - } - - /** - * 播放闹钟声音 - * - * 获取系统默认的闹钟铃声,设置音频流类型, - * 并循环播放闹钟声音 - */ - private void playAlarmSound() { - // 获取系统默认的闹钟铃声URI - Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); - - // 获取受静音模式影响的音频流类型 - int silentModeStreams = Settings.System.getInt(getContentResolver(), - Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); - - // 如果闹钟音频流受静音模式影响,使用受影响的流类型 - if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { - mPlayer.setAudioStreamType(silentModeStreams); - } else { - // 否则使用标准闹钟音频流 - mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); - } - try { - // 设置音频源 - mPlayer.setDataSource(this, url); - // 准备播放 - mPlayer.prepare(); - // 设置循环播放 - mPlayer.setLooping(true); - // 开始播放 - mPlayer.start(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (IllegalStateException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * 显示操作对话框 - * - * 创建一个AlertDialog,显示笔记摘要和操作按钮 - * 当屏幕开启时,显示"查看笔记"按钮 - */ - private void showActionDialog() { - // 创建AlertDialog构建器 - AlertDialog.Builder dialog = new AlertDialog.Builder(this); - // 设置对话框标题为应用名称 - dialog.setTitle(R.string.app_name); - // 设置对话框内容为笔记摘要 - dialog.setMessage(mSnippet); - // 添加"确定"按钮,点击事件由当前类处理 - dialog.setPositiveButton(R.string.notealert_ok, this); - // 如果屏幕是开启状态,添加"查看笔记"按钮 - if (isScreenOn()) { - dialog.setNegativeButton(R.string.notealert_enter, this); - } - // 显示对话框并设置关闭监听器 - dialog.show().setOnDismissListener(this); - } - - /** - * 对话框按钮点击事件处理 - * - * 处理用户在提醒对话框中的按钮点击操作,根据点击的按钮执行相应的操作 - * - * @param dialog 触发点击事件的对话框对象,不能为 null - * @param which 点击的按钮ID,取值为 DialogInterface.BUTTON_POSITIVE(确定按钮) - * 或 DialogInterface.BUTTON_NEGATIVE(查看笔记按钮) - */ - public void onClick(DialogInterface dialog, int which) { - switch (which) { - // 如果点击了"查看笔记"按钮(负按钮) - case DialogInterface.BUTTON_NEGATIVE: - // 创建跳转到笔记编辑活动的Intent - Intent intent = new Intent(this, NoteEditActivity.class); - // 设置动作为查看 - intent.setAction(Intent.ACTION_VIEW); - // 传递笔记ID - intent.putExtra(Intent.EXTRA_UID, mNoteId); - // 启动笔记编辑活动 - startActivity(intent); - break; - // 默认情况(点击"确定"按钮) - default: - break; - } - } - - /** - * 对话框关闭事件处理 - * - * 当对话框被关闭时(无论是点击按钮还是外部点击), - * 停止闹钟声音并关闭当前活动 - * - * @param dialog 被关闭的对话框对象,不能为 null - */ - public void onDismiss(DialogInterface dialog) { - // 停止闹钟声音 - stopAlarmSound(); - // 关闭当前活动 - finish(); - } - - /** - * 停止闹钟声音 - * - * 停止媒体播放器,释放资源并将播放器对象置空 - */ - private void stopAlarmSound() { - if (mPlayer != null) { - // 停止播放 - mPlayer.stop(); - // 释放资源 - mPlayer.release(); - // 将播放器对象置空 - mPlayer = null; - } - } -} \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java b/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java deleted file mode 100644 index c00b5c6..0000000 --- a/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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; // 用于处理内容URI的工具类 -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; // 笔记表列定义 - -/** - * 闹钟初始化接收器 - * - * 这个类继承自BroadcastReceiver,用于在系统启动或应用需要时重新初始化所有未触发的笔记提醒闹钟。 - * 它会查询数据库中所有设置了提醒时间且未过期的笔记,并为每个笔记设置系统闹钟。 - * - * 主要触发时机: - * 1. 系统启动完成时(接收BOOT_COMPLETED广播) - * 2. 应用安装或更新后可能需要手动触发 - */ -public class AlarmInitReceiver extends BroadcastReceiver { - - /** - * 数据库查询投影,指定需要从笔记表中获取的列 - * 只需要ID和提醒日期两列,用于设置闹钟 - */ - private static final String [] PROJECTION = new String [] { - NoteColumns.ID, // 笔记ID - NoteColumns.ALERTED_DATE // 提醒日期 - }; - - // 列索引常量,用于从查询结果中获取对应列的数据 - private static final int COLUMN_ID = 0; // ID列在结果集中的索引 - private static final int COLUMN_ALERTED_DATE = 1; // 提醒日期列在结果集中的索引 - - /** - * 接收广播后的处理方法 - * - * 当接收到广播(通常是系统启动完成广播)时,此方法会被调用。 - * 它会查询所有未过期的笔记提醒,并为每个笔记设置系统闹钟。 - * - * @param context 应用上下文,用于访问系统服务和资源 - * @param intent 接收到的广播意图 - */ - @Override - public void onReceive(Context context, Intent intent) { - // 获取当前系统时间,作为查询条件 - long currentDate = System.currentTimeMillis(); - - // 查询所有提醒时间晚于当前时间的笔记 - // 查询条件:提醒日期 > 当前时间 AND 笔记类型 = 普通笔记 - 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); // 排序方式,null表示默认排序 - - // 处理查询结果 - if (c != null) { - // 如果有查询结果,遍历所有符合条件的笔记 - if (c.moveToFirst()) { - do { - // 获取笔记的提醒时间 - long alertDate = c.getLong(COLUMN_ALERTED_DATE); - - // 创建一个指向AlarmReceiver的Intent,用于在闹钟触发时接收广播 - Intent sender = new Intent(context, AlarmReceiver.class); - // 将笔记ID作为URI数据附加到Intent中,这样AlarmReceiver就能知道是哪个笔记的闹钟触发了 - sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); - - // 创建PendingIntent,它封装了上述Intent,可以在指定时间触发 - PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); - - // 获取系统闹钟服务 - AlarmManager alermManager = (AlarmManager) context - .getSystemService(Context.ALARM_SERVICE); - - // 设置闹钟 - // 使用RTC_WAKEUP模式,即使设备处于睡眠状态也会唤醒设备并触发广播 - alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); - } while (c.moveToNext()); // 移动到下一条记录 - } - // 关闭游标,释放资源 - c.close(); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java b/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java deleted file mode 100644 index 1ef8a05..0000000 --- a/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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; // 意图,用于组件间通信 - -/** - * 闹钟接收器 - * - * 这个类继承自BroadcastReceiver,用于接收由AlarmManager设置的闹钟触发事件。 - * 当笔记的提醒时间到达时,AlarmManager会发送一个广播,这个接收器会接收该广播 - * 并启动闹钟提醒界面(AlarmAlertActivity)来显示提醒信息。 - * - * 工作流程: - * 1. AlarmInitReceiver为每个设置了提醒时间的笔记设置系统闹钟 - * 2. 当提醒时间到达时,系统发送广播 - * 3. AlarmReceiver接收广播并启动AlarmAlertActivity显示提醒 - */ -public class AlarmReceiver extends BroadcastReceiver { - - /** - * 接收闹钟广播后的处理方法 - * - * 当闹钟时间到达时,系统会发送广播,此方法会被调用。 - * 它会将接收到的Intent重新定向到AlarmAlertActivity,并添加FLAG_ACTIVITY_NEW_TASK标志 - * 确保即使在非UI上下文中也能启动Activity。 - * - * @param context 应用上下文,用于启动Activity - * @param intent 接收到的闹钟广播Intent,包含触发闹钟的笔记ID等信息 - */ - @Override - public void onReceive(Context context, Intent intent) { - // 将Intent的目标组件设置为AlarmAlertActivity - // 这样当启动Activity时就会显示闹钟提醒界面 - intent.setClass(context, AlarmAlertActivity.class); - - // 添加FLAG_ACTIVITY_NEW_TASK标志 - // 这是必需的,因为从非Activity上下文(如BroadcastReceiver)启动Activity时, - // 必须指定这个标志,表示启动一个新的任务栈 - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - - // 启动AlarmAlertActivity显示闹钟提醒 - // 原始Intent中包含了触发闹钟的笔记ID等信息,AlarmAlertActivity会使用这些信息 - // 来显示相应的笔记内容和提醒信息 - context.startActivity(intent); - } -} \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/ui/DateTimePicker.java b/app/src/main/java/net/micode/notes/ui/DateTimePicker.java deleted file mode 100644 index 015522e..0000000 --- a/app/src/main/java/net/micode/notes/ui/DateTimePicker.java +++ /dev/null @@ -1,651 +0,0 @@ -/* - * 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,提供日期和时间选择的自定义视图组件。 - * 使用NumberPicker组件实现日期、小时、分钟和上午/下午的选择功能。 - * 支持24小时制和12小时制两种显示模式。 - *
- *- * 主要功能: - *
- * 监听日期选择器的值变化,更新内部日期对象并通知外部监听器。 - *
- */ - 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(); - } - }; - - /** - * 小时变更监听器 - *- * 监听小时选择器的值变化,处理跨日情况(如从23点变为0点或从0点变为23点), - * 在12小时制下处理上午/下午的切换。 - *
- */ - private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { - @Override - public void onValueChange(NumberPicker picker, int oldVal, int newVal) { - boolean isDateChanged = false; - Calendar cal = Calendar.getInstance(); - // 处理12小时制下的跨日情况 - if (!mIs24HourView) { - // 从下午11点变为12点,日期加1天 - 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; - // 从12点变为下午11点,日期减1天 - } 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 { - // 处理24小时制下的跨日情况 - 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)); - } - } - }; - - /** - * 分钟变更监听器 - *- * 监听分钟选择器的值变化,处理跨小时情况(如从59分变为0分或从0分变为59分)。 - *
- */ - 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; - // 从最大值变为最小值,小时加1 - if (oldVal == maxValue && newVal == minValue) { - offset += 1; - // 从最小值变为最大值,小时减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); - } - - /** - * 构造器 - * - * 创建日期时间选择器,使用当前系统时间作为初始值。 - * 根据系统设置自动判断是否使用24小时制显示。 - * - * @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)); - } - - /** - * 构造器 - * - * 创建日期时间选择器,使用指定的时间和显示模式作为初始值。 - * 初始化所有NumberPicker组件并设置监听器。 - * - * @param context 应用上下文 - * @param date 初始日期时间,以毫秒为单位的时间戳 - * @param is24HourView 是否使用24小时制显示,true表示24小时制,false表示12小时制 - */ - 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); - - // 更新控件到初始状态 - updateDateControl(); - updateHourControl(); - updateAmPmControl(); - - // 设置24小时制显示模式 - set24HourView(is24HourView); - - // 设置当前时间 - setCurrentDate(date); - - // 设置启用状态 - setEnabled(isEnabled()); - - // 设置内容描述 - mInitialising = false; - } - - /** - * 设置启用状态 - * - * 设置所有NumberPicker组件的启用状态,控制用户是否可以修改日期时间。 - * - * @param enabled true表示启用,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; - } - - /** - * 获取启用状态 - * - * @return true表示已启用,false表示已禁用 - */ - @Override - public boolean isEnabled() { - return mIsEnabled; - } - - /** - * 获取当前日期时间(毫秒) - * - * @return 当前日期时间,以毫秒为单位的时间戳 - */ - public long getCurrentDateInTimeMillis() { - return mDate.getTimeInMillis(); - } - - /** - * 设置当前日期时间 - * - * @param date 要设置的日期时间,以毫秒为单位的时间戳 - */ - 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)); - } - - /** - * 设置当前日期时间 - * - * @param year 年份 - * @param month 月份(0-11) - * @param dayOfMonth 日(1-31) - * @param hourOfDay 小时(0-23) - * @param minute 分钟(0-59) - */ - public void setCurrentDate(int year, int month, - int dayOfMonth, int hourOfDay, int minute) { - setCurrentYear(year); - setCurrentMonth(month); - setCurrentDay(dayOfMonth); - setCurrentHour(hourOfDay); - setCurrentMinute(minute); - } - - /** - * 获取当前年份 - * - * @return 当前年份 - */ - public int getCurrentYear() { - return mDate.get(Calendar.YEAR); - } - - /** - * 设置当前年份 - * - * @param year 要设置的年份 - */ - public void setCurrentYear(int year) { - if (!mInitialising && year == getCurrentYear()) { - return; - } - mDate.set(Calendar.YEAR, year); - updateDateControl(); - onDateTimeChanged(); - } - - /** - * 获取当前月份 - * - * @return 当前月份(0-11) - */ - public int getCurrentMonth() { - return mDate.get(Calendar.MONTH); - } - - /** - * 设置当前月份 - * - * @param month 要设置的月份(0-11) - */ - public void setCurrentMonth(int month) { - if (!mInitialising && month == getCurrentMonth()) { - return; - } - mDate.set(Calendar.MONTH, month); - updateDateControl(); - onDateTimeChanged(); - } - - /** - * 获取当前日 - * - * @return 当前日(1-31) - */ - public int getCurrentDay() { - return mDate.get(Calendar.DAY_OF_MONTH); - } - - /** - * 设置当前日 - * - * @param dayOfMonth 要设置的日(1-31) - */ - public void setCurrentDay(int dayOfMonth) { - if (!mInitialising && dayOfMonth == getCurrentDay()) { - return; - } - mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); - updateDateControl(); - onDateTimeChanged(); - } - - /** - * 获取当前小时(24小时制) - * - * @return 当前小时(0-23) - */ - 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小时制) - * - * @param hourOfDay 要设置的小时(0-23) - */ - public void setCurrentHour(int hourOfDay) { - if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { - return; - } - mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); - if (!mIs24HourView) { - // 处理12小时制下的上午/下午状态 - 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; - } - - /** - * 设置显示模式 - * - * @param is24HourView true表示使用24小时制,false表示使用12小时制 - */ - 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(); - } - - /** - * 更新日期选择器显示 - * - * 根据当前日期更新日期选择器的显示值,显示前后3天,共7天的日期。 - * 每个日期的格式为"MM.dd EEEE"(月.日 星期)。 - */ - private void updateDateControl() { - Calendar cal = Calendar.getInstance(); - // 设置为当前日期的前4天 - cal.setTimeInMillis(mDate.getTimeInMillis()); - cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); - mDateSpinner.setDisplayedValues(null); - // 生成7天的日期显示值 - 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(); - } - - /** - * 更新上午/下午选择器显示 - * - * 根据当前显示模式和上午/下午状态更新上午/下午选择器的可见性和选中值。 - * 在24小时制下隐藏上午/下午选择器,在12小时制下显示并设置当前选中值。 - */ - private void updateAmPmControl() { - if (mIs24HourView) { - // 24小时制下隐藏上午/下午选择器 - mAmPmSpinner.setVisibility(View.GONE); - } else { - // 12小时制下显示上午/下午选择器 - int index = mIsAm ? Calendar.AM : Calendar.PM; - mAmPmSpinner.setValue(index); - mAmPmSpinner.setVisibility(View.VISIBLE); - } - } - - /** - * 更新小时选择器范围 - * - * 根据当前显示模式更新小时选择器的最小值和最大值。 - * 24小时制:0-23,12小时制:1-12。 - */ - 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/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java b/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java deleted file mode 100644 index a95bc43..0000000 --- a/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * 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; - -/** - * 日期时间选择对话框 - *- * 继承自AlertDialog,提供日期和时间选择的对话框界面。 - * 使用DateTimePicker组件作为主视图,支持设置24小时制或12小时制显示。 - *
- *- * 主要功能: - *
- * 用于监听用户在对话框中点击确定按钮后的回调,获取用户选择的日期和时间。 - *
- */ - public interface OnDateTimeSetListener { - /** - * 当用户点击确定按钮时调用 - * - * @param dialog 日期时间选择对话框实例 - * @param date 用户选择的日期时间,以毫秒为单位的时间戳 - */ - void OnDateTimeSet(AlertDialog dialog, long date); - } - - /** - * 构造器 - * - * 创建日期时间选择对话框,初始化DateTimePicker组件并设置默认日期时间。 - * 根据系统设置自动判断是否使用24小时制显示。 - * - * @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) { - // 更新内部Calendar对象 - 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); - // 根据系统设置判断是否使用24小时制 - set24HourView(DateFormat.is24HourFormat(this.getContext())); - // 更新对话框标题 - updateTitle(mDate.getTimeInMillis()); - } - - /** - * 设置是否使用24小时制显示 - *- * 根据系统设置或用户偏好,判断是否使用24小时制显示时间。 - * 如果设置为true,将使用24小时制;如果设置为false,将使用12小时制。 - *
- * - * @param is24HourView true表示使用24小时制,false表示使用12小时制 - */ - public void set24HourView(boolean is24HourView) { - mIs24HourView = is24HourView; - } - - /** - * 设置日期时间设置监听器 - *- * 当用户点击对话框的确定按钮时,调用此监听器的OnDateTimeSet方法, - * 并传递用户选择的日期时间作为参数。 - *
- * - * @param callBack 日期时间设置监听器,当用户点击确定按钮时回调 - */ - public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { - mOnDateTimeSetListener = callBack; - } - - /** - * 更新对话框标题 - * - * 根据指定的日期时间格式化字符串,并设置为对话框标题。 - * 显示格式包含年、月、日和时间,根据mIs24HourView决定是否使用24小时制。 - * - * @param date 要显示的日期时间,以毫秒为单位的时间戳 - */ - private void updateTitle(long date) { - // 设置日期时间格式标志 - int flag = - DateUtils.FORMAT_SHOW_YEAR | - DateUtils.FORMAT_SHOW_DATE | - DateUtils.FORMAT_SHOW_TIME; - // 根据是否24小时制设置相应的格式标志 - flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; - // 格式化日期时间并设置为对话框标题 - setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); - } - - /** - * 处理对话框按钮点击事件 - * - * 当用户点击确定按钮时,调用监听器的OnDateTimeSet方法,传递用户选择的日期时间。 - * - * @param arg0 触发事件的对话框 - * @param arg1 被点击的按钮ID - */ - public void onClick(DialogInterface arg0, int arg1) { - // 如果设置了监听器,通知监听器用户选择的日期时间 - if (mOnDateTimeSetListener != null) { - mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); - } - } - -} \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/ui/DropdownMenu.java b/app/src/main/java/net/micode/notes/ui/DropdownMenu.java deleted file mode 100644 index 7276081..0000000 --- a/app/src/main/java/net/micode/notes/ui/DropdownMenu.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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; - -/** - * 下拉菜单类 - *- * 封装了PopupMenu和Button,提供下拉菜单功能。 - * 点击按钮时显示弹出菜单,支持设置菜单项点击监听器和标题。 - *
- *- * 主要功能: - *
- * 继承自CursorAdapter,用于将数据库中的文件夹数据绑定到ListView中显示。 - * 主要用于笔记移动功能中显示可选择的文件夹列表。 - *
- *- * 主要功能: - *
- * 自定义的LinearLayout,用于显示文件夹列表中的单个文件夹项。 - *
- */ - 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/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java b/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java deleted file mode 100644 index 9544f6c..0000000 --- a/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java +++ /dev/null @@ -1,1188 +0,0 @@ -/* - * 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.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.CheckBox; -import android.widget.CompoundButton; -import android.widget.CompoundButton.OnCheckedChangeListener; -import android.widget.EditText; -import android.widget.ImageView; -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.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 { - /** - * 笔记头部视图持有者 - *- * 持有笔记编辑界面头部区域的UI组件引用,包括修改时间、提醒图标、提醒日期和背景颜色设置按钮。 - *
- */ - private class HeadViewHolder { - public TextView tvModified; - - public ImageView ivAlertIcon; - - public TextView tvAlertDate; - - public ImageView ibSetBgColor; - } - - private static final Map- * 当系统内存不足导致活动被杀死时,重新加载活动需要恢复之前的状态。 - * 从保存的实例状态中恢复笔记ID,并重新初始化活动状态。 - *
- * @param savedInstanceState 包含之前保存状态的Bundle对象 - */ - @Override - protected void onRestoreInstanceState(Bundle savedInstanceState) { - super.onRestoreInstanceState(savedInstanceState); - if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); - if (!initActivityState(intent)) { - finish(); - return; - } - Log.d(TAG, "Restoring from killed activity"); - } - } - - /** - * 初始化活动状态 - *- * 根据传入的Intent初始化活动状态,支持以下操作: - *
- * 设置笔记编辑界面的显示内容,包括: - *
- * 根据笔记是否设置了闹钟提醒,显示或隐藏提醒图标和提醒日期。 - * 如果提醒已过期,显示过期提示;否则显示相对时间。 - *
- */ - private void showAlertHeader() { - if (mWorkingNote.hasClockAlert()) { - long time = System.currentTimeMillis(); - if (time > mWorkingNote.getAlertDate()) { - mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); - } else { - mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( - mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS)); - } - mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); - mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); - } else { - mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); - mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); - }; - } - - @Override - protected void onNewIntent(Intent intent) { - super.onNewIntent(intent); - initActivityState(intent); - } - - /** - * 保存活动实例状态 - *- * 在活动被系统销毁前保存当前笔记的ID,以便后续恢复。 - * 如果是新笔记且尚未保存到数据库,会先保存笔记以生成ID。 - *
- * @param outState 用于保存状态的Bundle对象 - */ - @Override - protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - /** - * For new note without note id, we should firstly save it to - * generate a id. If the editing note is not worth saving, there - * is no id which is equivalent to create new note - */ - if (!mWorkingNote.existInDatabase()) { - saveNote(); - } - outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); - Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); - } - - /** - * 分发触摸事件 - *- * 处理触摸事件,当用户点击背景颜色选择器或字体大小选择器外部区域时, - * 隐藏相应的选择器面板。 - *
- * @param ev 触摸事件对象 - * @return 如果事件被处理返回true,否则返回false - */ - @Override - public boolean dispatchTouchEvent(MotionEvent ev) { - if (mNoteBgColorSelector.getVisibility() == View.VISIBLE - && !inRangeOfView(mNoteBgColorSelector, ev)) { - mNoteBgColorSelector.setVisibility(View.GONE); - return true; - } - - if (mFontSizeSelector.getVisibility() == View.VISIBLE - && !inRangeOfView(mFontSizeSelector, ev)) { - mFontSizeSelector.setVisibility(View.GONE); - return true; - } - return super.dispatchTouchEvent(ev); - } - - /** - * 检查触摸点是否在视图范围内 - *- * 判断给定的触摸事件坐标是否位于指定视图的显示区域内。 - *
- * @param view 要检查的视图 - * @param ev 触摸事件对象 - * @return 如果触摸点在视图范围内返回true,否则返回false - */ - private boolean inRangeOfView(View view, MotionEvent ev) { - int []location = new int[2]; - view.getLocationOnScreen(location); - int x = location[0]; - int y = location[1]; - if (ev.getX() < x - || ev.getX() > (x + view.getWidth()) - || ev.getY() < y - || ev.getY() > (y + view.getHeight())) { - return false; - } - return true; - } - - /** - * 初始化资源 - *- * 初始化所有UI组件的引用,设置点击监听器, - * 并从SharedPreferences中读取字体大小设置。 - *
- */ - private void initResources() { - mHeadViewPanel = findViewById(R.id.note_title); - mNoteHeaderHolder = new HeadViewHolder(); - mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); - mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); - mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); - mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color); - mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); - mNoteEditor = (EditText) findViewById(R.id.note_edit_view); - mNoteEditorPanel = findViewById(R.id.sv_note_edit); - mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector); - for (int id : sBgSelectorBtnsMap.keySet()) { - ImageView iv = (ImageView) findViewById(id); - iv.setOnClickListener(this); - } - - mFontSizeSelector = findViewById(R.id.font_size_selector); - for (int id : sFontSizeBtnsMap.keySet()) { - View view = findViewById(id); - view.setOnClickListener(this); - }; - mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); - mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); - /** - * 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(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { - mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; - } - mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); - } - - /** - * 活动暂停时保存笔记 - *- * 在活动暂停时自动保存笔记内容,并清除设置状态(如打开的颜色选择器)。 - *
- */ - @Override - protected void onPause() { - super.onPause(); - if(saveNote()) { - Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length()); - } - clearSettingState(); - } - - /** - * 更新桌面小部件 - *- * 发送广播通知桌面小部件更新,根据笔记的小部件类型(2x或4x)发送相应的更新意图。 - *
- */ - private void updateWidget() { - Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { - intent.setClass(this, NoteWidgetProvider_2x.class); - } else if (mWorkingNote.getWidgetType() == 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[] { - mWorkingNote.getWidgetId() - }); - - sendBroadcast(intent); - setResult(RESULT_OK, intent); - } - - /** - * 处理点击事件 - *- * 处理各种UI组件的点击事件,包括: - *
- * 如果当前有打开的设置面板(颜色选择器或字体选择器),先关闭面板; - * 否则保存笔记并退出活动。 - *
- */ - @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 (mFontSizeSelector.getVisibility() == View.VISIBLE) { - mFontSizeSelector.setVisibility(View.GONE); - return true; - } - return false; - } - - /** - * 背景颜色改变回调 - *- * 当笔记背景颜色改变时调用,更新UI显示: - *
- * 根据当前笔记的状态动态设置菜单项: - *
- * 处理各种菜单项的点击事件,包括: - *
- * 显示日期时间选择对话框,让用户选择提醒时间。 - * 选择完成后设置笔记的提醒日期。 - *
- */ - 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(); - } - - /** - * 分享笔记到其他应用 - *- * 使用ACTION_SEND Intent将笔记内容分享到支持文本分享的应用。 - *
- * @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); - } - - /** - * 创建新笔记 - *- * 先保存当前编辑的笔记,然后启动新的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); - } - - /** - * 删除当前笔记 - *- * 删除当前编辑的笔记。如果处于同步模式,将笔记移动到垃圾箱; - * 否则直接从数据库中删除。 - *
- */ - private void deleteCurrentNote() { - if (mWorkingNote.existInDatabase()) { - HashSet- * 检查是否配置了同步账户,如果配置了则处于同步模式。 - *
- * @return 如果配置了同步账户返回true,否则返回false - */ - private boolean isSyncMode() { - return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; - } - - /** - * 闹钟提醒改变回调 - *- * 当笔记的闹钟提醒设置改变时调用。 - * 如果笔记尚未保存到数据库,先保存笔记。 - * 然后使用AlarmManager设置或取消闹钟。 - *
- * @param date 提醒日期时间(毫秒) - * @param set true表示设置提醒,false表示取消提醒 - */ - public void onClockAlertChanged(long date, boolean set) { - /** - * User could set clock to an unsaved note, so before setting the - * alert clock, we should save the note first - */ - 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); - } - } - - /** - * 小部件改变回调 - *- * 当笔记的小部件设置改变时调用,更新桌面小部件显示。 - *
- */ - public void onWidgetChanged() { - updateWidget(); - } - - /** - * 编辑文本删除回调 - *- * 在清单模式下删除某个编辑项时调用。 - * 删除指定位置的编辑项,并更新后续项的索引。 - *
- * @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) { - /** - * Should not happen, check for debug - */ - 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 完整的文本内容 - * @param userQuery 用户搜索的关键词 - * @return 带有高亮标记的Spannable对象 - */ - private Spannable getHighlightQueryResult(String 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; - } - - /** - * 创建清单列表项视图 - *- * 创建清单模式下的单个列表项,包含复选框和编辑框。 - * 根据文本内容设置复选框状态和文本样式。 - *
- * @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); - } - } - - /** - * 获取工作文本 - *- * 从当前编辑器中获取文本内容并设置到WorkingNote。 - * 如果是清单模式,将所有清单项合并为文本,并标记已选中项。 - *
- * @return 如果有已选中的清单项返回true,否则返回false - */ - 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 { - mWorkingNote.setWorkingText(mNoteEditor.getText().toString()); - } - return hasChecked; - } - - /** - * 保存笔记 - *- * 将当前编辑的笔记保存到数据库。 - * 保存成功后设置RESULT_OK结果码,用于标识创建/编辑状态。 - *
- * @return 保存成功返回true,失败返回false - */ - 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; - } - - /** - * 发送到桌面 - *- * 将笔记创建为桌面快捷方式。 - * 如果笔记尚未保存到数据库,先保存笔记。 - * 快捷方式使用笔记内容的前10个字符作为标题。 - *
- */ - private void sendToDesktop() { - /** - * Before send message to home, we should make sure that current - * editing note is exists in databases. So, for new note, firstly - * save it - */ - 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); - } - } - - /** - * 生成快捷方式图标标题 - *- * 从笔记内容中提取文本作为快捷方式标题。 - * 移除清单标记,并限制标题长度为10个字符。 - *
- * @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提示 - *- * 显示短时Toast提示消息。 - *
- * @param resId 字符串资源ID - */ - private void showToast(int resId) { - showToast(resId, Toast.LENGTH_SHORT); - } - - /** - * 显示Toast提示 - *- * 显示指定时长的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/app/src/main/java/net/micode/notes/ui/NoteEditText.java b/app/src/main/java/net/micode/notes/ui/NoteEditText.java deleted file mode 100644 index df117b3..0000000 --- a/app/src/main/java/net/micode/notes/ui/NoteEditText.java +++ /dev/null @@ -1,342 +0,0 @@ -/* - * 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.Spanned; -import android.text.TextUtils; -import android.text.style.URLSpan; -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,用于笔记编辑界面,支持多行文本编辑、链接识别和上下文菜单。 - * 提供了与NoteEditActivity的交互接口,用于处理删除和回车事件。 - *
- *- * 主要功能: - *
- * 由NoteEditActivity实现,用于处理EditText的删除、回车和文本变更事件。 - *
- * - * @see NoteEditActivity - */ - public interface OnTextViewChangeListener { - /** - * 当按下删除键且文本为空时调用 - * - * @param index 当前EditText的索引 - * @param text 当前EditText中的文本内容 - */ - void onEditTextDelete(int index, String text); - - /** - * 当按下回车键时调用 - * - * @param index 当前EditText的索引 - * @param text 当前EditText中的文本内容 - */ - void onEditTextEnter(int index, String text); - - /** - * 当文本内容变更时调用 - * - * @param index 当前EditText的索引 - * @param hasText 是否有文本内容 - */ - void onTextChange(int index, boolean hasText); - } - - // 文本视图变更监听器 - private OnTextViewChangeListener mOnTextViewChangeListener; - - /** - * 构造器 - * - * @param context 应用上下文 - */ - public NoteEditText(Context context) { - super(context, null); - mIndex = 0; - } - - /** - * 设置当前EditText的索引 - * - * @param index EditText的索引值 - */ - public void setIndex(int index) { - mIndex = index; - } - - /** - * 设置文本视图变更监听器 - * - * @param listener 文本视图变更监听器对象 - */ - public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { - mOnTextViewChangeListener = listener; - } - - /** - * 构造器 - * - * @param context 应用上下文 - * @param attrs XML属性集 - */ - public NoteEditText(Context context, AttributeSet attrs) { - super(context, attrs, android.R.attr.editTextStyle); - } - - /** - * 构造器 - * - * @param context 应用上下文 - * @param attrs XML属性集 - * @param defStyle 默认样式 - */ - public NoteEditText(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } - - /** - * 处理触摸事件 - * - * 根据触摸位置设置文本选择光标的位置 - * - * @param event 触摸事件对象 - * @return 如果事件被处理返回true,否则返回false - */ - @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 如果事件被处理返回true,否则返回false - */ - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - switch (keyCode) { - case KeyEvent.KEYCODE_ENTER: - // 如果设置了监听器,返回false让onKeyUp处理 - 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 如果事件被处理返回true,否则返回false - */ - @Override - public boolean onKeyUp(int keyCode, KeyEvent event) { - switch(keyCode) { - case KeyEvent.KEYCODE_DEL: - // 处理删除键 - if (mOnTextViewChangeListener != null) { - // 如果光标在开头且不是第一个EditText,删除当前EditText - 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)); - // 通知监听器创建新的EditText - 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); - } - - /** - * 创建上下文菜单 - * - * 如果选中的文本包含URL链接,添加相应的菜单项 - * - * @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); - - // 获取选区内的所有URLSpan - final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); - if (urls.length == 1) { - int defaultResId = 0; - // 根据URL类型确定菜单项文本 - 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) { - // 点击菜单项时打开链接 - urls[0].onClick(NoteEditText.this); - return true; - } - }); - } - } - super.onCreateContextMenu(menu); - } -} diff --git a/app/src/main/java/net/micode/notes/ui/NoteItemData.java b/app/src/main/java/net/micode/notes/ui/NoteItemData.java deleted file mode 100644 index 024cb5d..0000000 --- a/app/src/main/java/net/micode/notes/ui/NoteItemData.java +++ /dev/null @@ -1,400 +0,0 @@ -/* - * 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; - -/** - * 笔记项数据类 - *- * 用于封装笔记列表项的数据信息,从数据库游标中提取笔记的各项属性, - * 并提供便捷的访问方法。该类支持普通笔记、文件夹和通话记录笔记等多种类型。 - *
- *- * 主要功能: - *
- * 根据当前文件夹ID构建查询条件,启动后台查询获取笔记列表数据。 - * 根文件夹使用特殊的查询条件,子文件夹使用普通查询条件。 - *
- */ - 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.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); - } - - /** - * 后台查询处理器 - *- * 继承自AsyncQueryHandler,用于在后台线程执行数据库查询, - * 避免阻塞UI线程。 - *
- */ - private final class BackgroundQueryHandler extends AsyncQueryHandler { - /** - * 构造函数 - * @param contentResolver 内容解析器 - */ - public BackgroundQueryHandler(ContentResolver contentResolver) { - super(contentResolver); - } - - /** - * 查询完成回调 - *- * 根据查询令牌处理不同的查询结果: - *
- * 显示一个对话框,列出所有可用的目标文件夹供用户选择, - * 用于移动选中的笔记到指定文件夹。 - *
- * @param cursor 包含文件夹列表的游标 - */ - 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); - } - - /** - * 批量删除笔记 - *- * 在后台线程中删除选中的笔记。 - * 如果处于同步模式,将笔记移动到垃圾箱文件夹; - * 否则直接删除。同时更新相关的小部件。 - *
- */ - private void batchDelete() { - new AsyncTask- * 删除指定的文件夹及其包含的所有笔记。 - * 如果处于同步模式,将文件夹移动到垃圾箱; - * 否则直接删除。同时更新相关的小部件。 - *
- * @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查看和编辑指定的笔记。 - *
- * @param data 笔记数据项 - */ - private void openNode(NoteItemData data) { - Intent intent = new Intent(this, NoteEditActivity.class); - intent.setAction(Intent.ACTION_VIEW); - intent.putExtra(Intent.EXTRA_UID, data.getId()); - this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); - } - - /** - * 打开文件夹 - *- * 进入指定的文件夹,显示该文件夹中的笔记列表。 - * 更新标题栏显示文件夹名称,并隐藏新建笔记按钮(如果是通话记录文件夹)。 - *
- * @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); - } - - public void onClick(View v) { - switch (v.getId()) { - case R.id.btn_new_note: - createNewNote(); - break; - default: - break; - } - } - - /** - * 显示软键盘 - *- * 强制显示系统软键盘,用于输入文件夹名称。 - *
- */ - private void showSoftInput() { - InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - if (inputMethodManager != null) { - inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - } - } - - /** - * 隐藏软键盘 - *- * 隐藏指定视图的软键盘。 - *
- * @param view 要隐藏键盘的视图 - */ - private void hideSoftInput(View view) { - InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); - } - - /** - * 显示创建或修改文件夹对话框 - *- * 显示一个对话框,允许用户输入文件夹名称。 - * 根据create参数决定是创建新文件夹还是修改现有文件夹名称。 - *
- * @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)) { - 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); - 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 - - } - }); - } - - /** - * 返回键按下处理 - *- * 根据当前列表状态处理返回键事件: - *
- * 发送广播更新指定的小部件,使其显示最新的笔记内容。 - *
- * @param appWidgetId 小部件ID - * @param appWidgetType 小部件类型(2x或4x) - */ - 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; - } - - /** - * 准备选项菜单 - *- * 根据当前列表状态加载不同的菜单资源: - *
- * 处理用户点击选项菜单的事件,包括: - *
- * 启动系统搜索界面,允许用户搜索笔记内容。 - *
- * @return true - */ - @Override - public boolean onSearchRequested() { - startSearch(null, false, null /* appData */, false); - return true; - } - - /** - * 导出笔记为文本文件 - *- * 在后台线程中将所有笔记导出为文本文件到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; - } - - /** - * 启动设置Activity - *- * 启动NotesPreferenceActivity进行应用设置。 - *
- */ - private void startPreferenceActivity() { - Activity from = getParent() != null ? getParent() : this; - Intent intent = new Intent(from, NotesPreferenceActivity.class); - from.startActivityIfNeeded(intent, -1); - } - - /** - * 列表项点击监听器 - *- * 处理笔记列表项的点击事件,根据当前状态和项类型执行相应操作: - *
- * 查询所有可用的文件夹,用于显示在移动笔记的对话框中。 - * 排除垃圾箱文件夹和当前文件夹。 - *
- */ - 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"); - } - - /** - * 列表项长按事件处理 - * - * @param parent 父视图 - * @param view 被长按的视图 - * @param position 列表项位置 - * @param id 列表项ID - * @return true表示事件已处理 - */ - 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/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java b/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java deleted file mode 100644 index 6085bf0..0000000 --- a/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * 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,用于将数据库中的笔记数据绑定到ListView中显示。 - * 它支持笔记的选择模式、批量操作以及与桌面小部件的关联。 - * - * 主要功能: - * 1. 将笔记数据绑定到NotesListItem视图 - * 2. 支持多选模式和批量选择操作 - * 3. 获取选中的笔记ID和关联的桌面小部件信息 - * 4. 统计笔记数量和选中数量 - * - * @see NotesListItem - * @see NoteItemData - */ -public class NotesListAdapter extends CursorAdapter { - private static final String TAG = "NotesListAdapter"; - // 应用上下文 - private Context mContext; - // 记录选中状态的Map,key为位置,value为是否选中 - private HashMap- * 自定义的 LinearLayout,表示笔记列表中的单个笔记项。 - * 该视图显示笔记信息,包括标题、时间、通话名称(针对通话记录)和提醒图标。 - * 支持在多选模式下显示复选框。 - *
- */ -public class NotesListItem extends LinearLayout { - private ImageView mAlert; - private TextView mTitle; - private TextView mTime; - private TextView mCallName; - private NoteItemData mItemData; - private CheckBox mCheckBox; - - /** - * 构造函数 - * @param context 用于加载布局的上下文对象 - */ - public NotesListItem(Context context) { - super(context); - inflate(context, R.layout.note_item, this); - mAlert = (ImageView) findViewById(R.id.iv_alert_icon); - mTitle = (TextView) findViewById(R.id.tv_title); - mTime = (TextView) findViewById(R.id.tv_time); - mCallName = (TextView) findViewById(R.id.tv_name); - mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); - } - - /** - * 绑定笔记数据到视图项 - * @param context 用于访问资源的上下文对象 - * @param data 包含要显示的笔记信息的 NoteItemData 对象 - * @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.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { - mCallName.setVisibility(View.VISIBLE); - mCallName.setText(data.getCallName()); - mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); - mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); - if (data.hasAlert()) { - mAlert.setImageResource(R.drawable.clock); - mAlert.setVisibility(View.VISIBLE); - } else { - mAlert.setVisibility(View.GONE); - } - } else { - 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(DataUtils.getFormattedSnippet(data.getSnippet())); - if (data.hasAlert()) { - mAlert.setImageResource(R.drawable.clock); - mAlert.setVisibility(View.VISIBLE); - } else { - mAlert.setVisibility(View.GONE); - } - } - } - mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); - - setBackground(data); - } - - /** - * 根据笔记项的位置和类型设置合适的背景资源 - * @param data 包含笔记背景颜色和位置信息的 NoteItemData 对象 - */ - 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 包含该笔记信息的 NoteItemData 对象 - */ - public NoteItemData getItemData() { - return mItemData; - } -} diff --git a/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java b/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java deleted file mode 100644 index fe02819..0000000 --- a/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java +++ /dev/null @@ -1,587 +0,0 @@ -/* - * 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; - -import android.os.Build; // 用于版本检查 -import android.content.Context; // 用于 RECEIVER_NOT_EXPORTED 常量 - - -/** - * 设置界面Activity - *- * 该Activity用于管理应用的各种设置,主要包括: - *
- * 该类继承自PreferenceActivity,使用SharedPreferences来持久化设置数据。 - * 通过GTaskReceiver接收同步服务的广播,实时更新同步状态。 - *
- */ -public class NotesPreferenceActivity extends PreferenceActivity { - /** - * SharedPreferences文件名 - */ - public static final String PREFERENCE_NAME = "notes_preferences"; - - /** - * 同步账户名称的SharedPreferences键 - */ - public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; - - /** - * 最后同步时间的SharedPreferences键 - */ - public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; - - /** - * 背景颜色随机显示设置的SharedPreferences键 - */ - public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; - - /** - * 同步账户分类的Preference键 - */ - private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; - - /** - * 账户授权过滤器键,用于添加账户Intent - */ - private static final String AUTHORITIES_FILTER_KEY = "authorities"; - - /** - * 同步账户分类的PreferenceCategory - */ - private PreferenceCategory mAccountCategory; - - /** - * 同步服务广播接收器 - */ - private GTaskReceiver mReceiver; - - /** - * 原始账户数组,用于检测新增账户 - */ - private Account[] mOriAccounts; - - /** - * 是否添加了新账户的标志 - */ - private boolean mHasAddedAccount; - - /** - * 创建Activity - *- * 初始化设置界面,包括: - *
- * 检查是否有新添加的Google账户,如果有则自动设置为同步账户。 - * 然后刷新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(); - } - - /** - * Activity销毁时调用 - *- * 注销同步服务广播接收器,防止内存泄漏。 - *
- */ - @Override - protected void onDestroy() { - if (mReceiver != null) { - unregisterReceiver(mReceiver); - } - super.onDestroy(); - } - - /** - * 加载账户设置选项 - *- * 创建并添加账户Preference到账户分类中。 - * 点击该Preference时: - *
- * 根据当前同步状态设置按钮文本和点击事件: - *
- * 重新加载账户设置选项和同步按钮状态。 - *
- */ - private void refreshUI() { - loadAccountPreference(); - loadSyncButton(); - } - - /** - * 显示选择账户对话框 - *- * 显示一个对话框,列出所有可用的Google账户供用户选择。 - * 同时提供"添加账户"选项,点击后跳转到系统账户添加界面。 - *
- */ - 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(); - } - }); - } - - /** - * 显示更改账户确认对话框 - *- * 显示一个对话框,提供三个选项: - *
- * 从系统AccountManager中获取所有类型为"com.google"的账户。 - *
- * @return Google账户数组 - */ - private Account[] getGoogleAccounts() { - AccountManager accountManager = AccountManager.get(this); - return accountManager.getAccountsByType("com.google"); - } - - /** - * 设置同步账户 - *- * 保存指定的账户名称到SharedPreferences,并清理相关数据: - *
- * 从SharedPreferences中删除同步账户和最后同步时间, - * 并清理所有笔记的GTASK_ID和SYNC_ID。 - *
- */ - 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(); - } - - /** - * 获取同步账户名称 - *- * 从SharedPreferences中读取已设置的同步账户名称。 - *
- * @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, ""); - } - - /** - * 设置最后同步时间 - *- * 将指定的同步时间保存到SharedPreferences。 - *
- * @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(); - } - - /** - * 获取最后同步时间 - *- * 从SharedPreferences中读取最后同步时间。 - *
- * @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); - } - - /** - * 同步服务广播接收器 - *- * 接收GTaskSyncService发送的广播,实时更新UI显示同步状态和进度。 - *
- */ - private class GTaskReceiver extends BroadcastReceiver { - - /** - * 接收广播 - *- * 当收到同步服务广播时,刷新UI并更新同步状态显示。 - *
- * @param context 上下文对象 - * @param intent 广播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)); - } - - } - } - - /** - * 处理菜单项选择 - *- * 处理ActionBar上的菜单项点击事件。 - * 当点击返回按钮时,返回到笔记列表界面。 - *
- * @param item 被点击的菜单项 - * @return true表示已处理,false表示未处理 - */ - 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/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java deleted file mode 100644 index ec6f819..0000000 --- a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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.app.PendingIntent; -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.ContentValues; -import android.content.Context; -import android.content.Intent; -import android.database.Cursor; -import android.util.Log; -import android.widget.RemoteViews; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.tool.ResourceParser; -import net.micode.notes.ui.NoteEditActivity; -import net.micode.notes.ui.NotesListActivity; - -public abstract class NoteWidgetProvider extends AppWidgetProvider { - public static final String [] PROJECTION = new String [] { - NoteColumns.ID, - NoteColumns.BG_COLOR_ID, - NoteColumns.SNIPPET - }; - - public static final int COLUMN_ID = 0; - public static final int COLUMN_BG_COLOR_ID = 1; - public static final int COLUMN_SNIPPET = 2; - - private static final String TAG = "NoteWidgetProvider"; - - @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])}); - } - } - - 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); - } - - protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - update(context, appWidgetManager, appWidgetIds, false); - } - - 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); - } - } - } - - protected abstract int getBgResourceId(int bgId); - - protected abstract int getLayoutId(); - - protected abstract int getWidgetType(); -} diff --git a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java deleted file mode 100644 index adcb2f7..0000000 --- a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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; - - -public class NoteWidgetProvider_2x extends NoteWidgetProvider { - @Override - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - super.update(context, appWidgetManager, appWidgetIds); - } - - @Override - protected int getLayoutId() { - return R.layout.widget_2x; - } - - @Override - protected int getBgResourceId(int bgId) { - return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); - } - - @Override - protected int getWidgetType() { - return Notes.TYPE_WIDGET_2X; - } -} diff --git a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java deleted file mode 100644 index c12a02e..0000000 --- a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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; - - -public class NoteWidgetProvider_4x extends NoteWidgetProvider { - @Override - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - super.update(context, appWidgetManager, appWidgetIds); - } - - protected int getLayoutId() { - return R.layout.widget_4x; - } - - @Override - protected int getBgResourceId(int bgId) { - return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); - } - - @Override - protected int getWidgetType() { - return Notes.TYPE_WIDGET_4X; - } -} diff --git a/app/src/main/res/color/primary_text_dark.xml b/app/src/main/res/color/primary_text_dark.xml deleted file mode 100644 index 7c85459..0000000 --- a/app/src/main/res/color/primary_text_dark.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - -