commit 6229f17b85c1ce536befcd832ecbc8bfbea70443 Author: jmh <2631499212@qq.com> Date: Mon May 19 18:52:21 2025 +0800 jmh diff --git a/doc/小米便签开源代码的泛读报告.docx b/doc/小米便签开源代码的泛读报告.docx new file mode 100644 index 0000000..1d5bf7c Binary files /dev/null and b/doc/小米便签开源代码的泛读报告.docx differ diff --git a/doc/运行结果.doc b/doc/运行结果.doc new file mode 100644 index 0000000..9dc158f Binary files /dev/null and b/doc/运行结果.doc differ diff --git a/src/data/Contact.java b/src/data/Contact.java new file mode 100644 index 0000000..ee8d8bd --- /dev/null +++ b/src/data/Contact.java @@ -0,0 +1,91 @@ + + +java +Copy Code +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; + +/* + * 联系人查询工具类 + * 提供根据电话号码获取联系人姓名的功能 + */ +public class Contact { + // 缓存联系人信息的HashMap,key为电话号码,value为联系人姓名 + private static HashMap sContactCache; + // 日志标签 + private static final String TAG = "Contact"; + + /* + * 联系人查询SQL条件语句模板 + * 包含以下条件: + * 1. 电话号码匹配条件(PHONE_NUMBERS_EQUAL) + * 2. MIME类型为电话类型 + * 3. RAW_CONTACT_ID在phone_lookup表中 + * 其中'+'为占位符,后续会被替换为最小匹配位数 + */ + 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 上下文对象 + * @param phoneNumber 要查询的电话号码 + * @return 联系人姓名,未找到则返回null + */ + public static String getContact(Context context, String phoneNumber) { + // 初始化缓存 + if(sContactCache == null) { + sContactCache = new HashMap(); + } + + // 先检查缓存中是否存在 + if(sContactCache.containsKey(phoneNumber)) { + return sContactCache.get(phoneNumber); + } + + // 构建完整查询条件:替换最小匹配位数占位符 + String selection = CALLER_ID_SELECTION.replace("+", + PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); + + // 查询联系人数据库 + Cursor cursor = context.getContentResolver().query( + Data.CONTENT_URI, // 数据URI + new String [] { Phone.DISPLAY_NAME }, // 查询列 + selection, // 查询条件 + new String[] { phoneNumber }, // 查询参数 + null); // 排序方式 + + // 处理查询结果 + if (cursor != null && cursor.moveToFirst()) { + try { + // 获取第一条记录的姓名 + String name = cursor.getString(0); + // 存入缓存 + sContactCache.put(phoneNumber, name); + return name; + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, " Cursor get string error " + e.toString()); + return null; + } finally { + cursor.close(); // 确保关闭Cursor + } + } else { + Log.d(TAG, "No contact matched with number:" + phoneNumber); + return null; + } + } +} + + diff --git a/src/data/Notes.java b/src/data/Notes.java new file mode 100644 index 0000000..916f21c --- /dev/null +++ b/src/data/Notes.java @@ -0,0 +1,281 @@ +package net.micode.notes.data; + +import android.net.Uri; + +/** + * 该类为笔记内容提供者定义了常量,包括: + * - 笔记类型和文件夹ID + * - Intent额外数据和小部件类型 + * - 笔记和数据的数据库列定义 + */ +public class Notes { + // 内容提供者权限,用于唯一标识内容提供者 + public static final String AUTHORITY = "micode_notes"; + // 日志标签,用于调试输出 + public static final String TAG = "Notes"; + + // 笔记类型常量 + public static final int TYPE_NOTE = 0; // 普通笔记 + public static final int TYPE_FOLDER = 1; // 文件夹 + public static final int TYPE_SYSTEM = 2; // 系统文件夹 + + // 特殊文件夹ID + public static final int ID_ROOT_FOLDER = 0; // 根文件夹ID + public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹ID + public static final int ID_CALL_RECORD_FOLDER = -2; // 通话记录文件夹ID + public static final int ID_TRASH_FOLER = -3; // 回收站文件夹ID + + // Intent额外数据键名,用于在Activity之间传递数据 + public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; + public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; + public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; + public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; + public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; + public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; + + // 小部件类型常量 + public static final int TYPE_WIDGET_INVALIDE = -1; // 无效小部件 + public static final int TYPE_WIDGET_2X = 0; // 2x尺寸小部件 + public static final int TYPE_WIDGET_4X = 1; // 4x尺寸小部件 + + /** + * 包含数据类型的常量 + */ + public static class DataConstants { + public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 文本笔记MIME类型 + public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; // 通话笔记MIME类型 + } + + /** + * 用于查询所有笔记和文件夹的Uri + */ + public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); + + /** + * 用于查询数据项的Uri + */ + public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); + + /** + * 'note'表的列定义 + */ + public interface NoteColumns { + /** + * 行的唯一ID + *

类型: INTEGER (long)

+ */ + public static final String ID = "_id"; + + /** + * 笔记或文件夹的父级ID + *

类型: INTEGER (long)

+ */ + public static final String PARENT_ID = "parent_id"; + + /** + * 笔记或文件夹的创建日期(时间戳) + *

类型: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * 最新修改日期(时间戳) + *

类型: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + + /** + * 提醒/闹钟日期(时间戳) + *

类型: INTEGER (long)

+ */ + public static final String ALERTED_DATE = "alert_date"; + + /** + * 文件夹名称或笔记的文本内容(预览/摘要) + *

类型: TEXT

+ */ + public static final String SNIPPET = "snippet"; + + /** + * 笔记的小部件ID + *

类型: INTEGER (long)

+ */ + public static final String WIDGET_ID = "widget_id"; + + /** + * 笔记的小部件类型 + *

类型: INTEGER (long)

+ */ + public static final String WIDGET_TYPE = "widget_type"; + + /** + * 笔记的背景颜色ID + *

类型: INTEGER (long)

+ */ + public static final String BG_COLOR_ID = "bg_color_id"; + + /** + * 标志指示笔记是否有附件 + * 对于文本笔记,没有附件;对于多媒体笔记,至少有一个附件 + *

类型: INTEGER

+ */ + public static final String HAS_ATTACHMENT = "has_attachment"; + + /** + * 文件夹中笔记的数量(仅对文件夹相关) + *

类型: INTEGER (long)

+ */ + public static final String NOTES_COUNT = "notes_count"; + + /** + * 项目类型:文件夹或笔记 + *

类型: INTEGER

+ */ + public static final String TYPE = "type"; + + /** + * 最后同步ID(用于同步目的) + *

类型: INTEGER (long)

+ */ + public static final String SYNC_ID = "sync_id"; + + /** + * 标志指示是否本地修改 + *

类型: INTEGER

+ */ + public static final String LOCAL_MODIFIED = "local_modified"; + + /** + * 移动到临时文件夹之前的原始父级ID + *

类型 : INTEGER

+ */ + public static final String ORIGIN_PARENT_ID = "origin_parent_id"; + + /** + * Google任务ID(用于Google任务集成) + *

类型 : TEXT

+ */ + public static final String GTASK_ID = "gtask_id"; + + /** + * 版本代码(用于数据版本控制) + *

类型 : INTEGER (long)

+ */ + public static final String VERSION = "version"; + } + + /** + * 'data'表的列定义(包含笔记内容和元数据) + */ + public interface DataColumns { + /** + * 行的唯一ID + *

类型: INTEGER (long)

+ */ + public static final String ID = "_id"; + + /** + * 此行表示的项目的MIME类型 + *

类型: Text

+ */ + public static final String MIME_TYPE = "mime_type"; + + /** + * 此数据所属笔记的引用ID + *

类型: INTEGER (long)

+ */ + public static final String NOTE_ID = "note_id"; + + /** + * 数据项的创建日期(时间戳) + *

类型: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * 最新修改日期(时间戳) + *

类型: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + + /** + * 数据内容(实际笔记内容) + *

类型: TEXT

+ */ + public static final String CONTENT = "content"; + + /** + * 通用数据列,含义由{@link #MIME_TYPE}指定,用于整数数据类型 + *

类型: INTEGER

+ */ + public static final String DATA1 = "data1"; + + /** + * 通用数据列,含义由{@link #MIME_TYPE}指定,用于整数数据类型 + *

类型: INTEGER

+ */ + public static final String DATA2 = "data2"; + + /** + * 通用数据列,含义由{@link #MIME_TYPE}指定,用于文本数据类型 + *

类型: TEXT

+ */ + public static final String DATA3 = "data3"; + + /** + * 通用数据列,含义由{@link #MIME_TYPE}指定,用于文本数据类型 + *

类型: TEXT

+ */ + public static final String DATA4 = "data4"; + + /** + * 通用数据列,含义由{@link #MIME_TYPE}指定,用于文本数据类型 + *

类型: TEXT

+ */ + public static final String DATA5 = "data5"; + } + + /** + * 文本笔记特定的常量 + */ + public static final class TextNote implements DataColumns { + /** + * 模式指示文本是否处于复选框列表模式 + *

类型: Integer 1:复选框列表模式 0:普通模式

+ */ + public static final String MODE = DATA1; + + public static final int MODE_CHECK_LIST = 1; // 复选框列表模式 + + // 文本笔记的MIME类型 + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; + + // 文本笔记的内容URI + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); + } + + /** + * 通话笔记特定的常量 + */ + public static final class CallNote implements DataColumns { + /** + * 此记录的通话日期(时间戳) + *

类型: INTEGER (long)

+ */ + public static final String CALL_DATE = DATA1; + + /** + * 此记录的电话号码 + *

类型: TEXT

+ */ + public static final String PHONE_NUMBER = DATA3; + + // 通话笔记的MIME类型 + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; + + // 通话笔记的内容URI + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); + } +} \ No newline at end of file diff --git a/src/data/NotesDatabaseHelper.java b/src/data/NotesDatabaseHelper.java new file mode 100644 index 0000000..77cb87f --- /dev/null +++ b/src/data/NotesDatabaseHelper.java @@ -0,0 +1,409 @@ +/* + * 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; + +/** + * Database helper class for managing the notes database creation and version management. + * This class handles: + * - Database creation (tables, indexes, triggers) + * - Database version upgrades + * - System folder initialization + */ +public class NotesDatabaseHelper extends SQLiteOpenHelper { + // Database name and version constants + private static final String DB_NAME = "note.db"; + private static final int DB_VERSION = 4; + + // Interface defining table names + public interface TABLE { + public static final String NOTE = "note"; // Table for notes and folders + public static final String DATA = "data"; // Table for note content and metadata + } + + private static final String TAG = "NotesDatabaseHelper"; // Log tag + private static NotesDatabaseHelper mInstance; // Singleton instance + + // SQL statement to create the note table + private static final String CREATE_NOTE_TABLE_SQL = + "CREATE TABLE " + TABLE.NOTE + "(" + + NoteColumns.ID + " INTEGER PRIMARY KEY," + + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + + ")"; + + // SQL statement to create the data table + private static final String CREATE_DATA_TABLE_SQL = + "CREATE TABLE " + TABLE.DATA + "(" + + DataColumns.ID + " INTEGER PRIMARY KEY," + + DataColumns.MIME_TYPE + " TEXT NOT NULL," + + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA1 + " INTEGER," + + DataColumns.DATA2 + " INTEGER," + + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + + ")"; + + // SQL statement to create index on note_id in data table + private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = + "CREATE INDEX IF NOT EXISTS note_id_index ON " + + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; + + /** + * Trigger to increase folder's note count when moving a 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"; + + /** + * Trigger to decrease folder's note count when moving a 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"; + + /** + * Trigger to increase folder's note count when inserting a 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"; + + /** + * Trigger to decrease folder's note count when deleting a 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"; + + /** + * Trigger to update note's content when inserting 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"; + + /** + * Trigger to update note's content when data with {@link DataConstants#NOTE} type is updated + */ + 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"; + + /** + * Trigger to clear note's content when data with {@link DataConstants#NOTE} type is 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"; + + /** + * Trigger to delete data items when their associated note is 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"; + + /** + * Trigger to delete notes when their parent folder is 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"; + + /** + * Trigger to move notes to trash when their parent folder is moved to trash + */ + 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"; + + /** + * Private constructor to enforce singleton pattern + */ + private NotesDatabaseHelper(Context context) { + super(context, DB_NAME, null, DB_VERSION); + } + + /** + * Creates the note table and associated triggers + */ + public void createNoteTable(SQLiteDatabase db) { + db.execSQL(CREATE_NOTE_TABLE_SQL); + reCreateNoteTableTriggers(db); + createSystemFolder(db); + Log.d(TAG, "note table has been created"); + } + + /** + * Recreates all triggers associated with the note table + */ + private void reCreateNoteTableTriggers(SQLiteDatabase db) { + // Drop existing triggers if they exist + 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"); + + // Create new triggers + 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); + } + + /** + * Creates the system folders (root, call records, temp, trash) + */ + private void createSystemFolder(SQLiteDatabase db) { + ContentValues values = new ContentValues(); + + // Create call record folder + values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + // Create root folder + values.clear(); + values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + // Create temporary folder (used for moving notes) + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + // Create trash folder + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + /** + * Creates the data table and associated triggers + */ + 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"); + } + + /** + * Recreates all triggers associated with the data table + */ + private void reCreateDataTableTriggers(SQLiteDatabase db) { + // Drop existing triggers if they exist + 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"); + + // Create new triggers + 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); + } + + /** + * Gets the singleton instance of the database helper + */ + static synchronized NotesDatabaseHelper getInstance(Context context) { + if (mInstance == null) { + mInstance = new NotesDatabaseHelper(context); + } + return mInstance; + } + + @Override + public void onCreate(SQLiteDatabase db) { + // Create both tables when database is first created + createNoteTable(db); + createDataTable(db); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + boolean reCreateTriggers = false; + boolean skipV2 = false; + + // Upgrade path from version 1 to version 2 + if (oldVersion == 1) { + upgradeToV2(db); + skipV2 = true; // this upgrade includes the upgrade from v2 to v3 + oldVersion++; + } + + // Upgrade path from version 2 to version 3 + if (oldVersion == 2 && !skipV2) { + upgradeToV3(db); + reCreateTriggers = true; + oldVersion++; + } + + // Upgrade path from version 3 to version 4 + if (oldVersion == 3) { + upgradeToV4(db); + oldVersion++; + } + + // Recreate triggers if needed + if (reCreateTriggers) { + reCreateNoteTableTriggers(db); + reCreateDataTableTriggers(db); + } + + // Verify we've reached the target version + if (oldVersion != newVersion) { + throw new IllegalStateException("Upgrade notes database to version " + newVersion + + "fails"); + } + } + + /** + * Upgrade database from version 1 to version 2 + * Drops and recreates all tables + */ + 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); + } + + /** + * Upgrade database from version 2 to version 3 + * - Drops unused triggers + * - Adds GTASK_ID column + * - Adds trash folder + */ + 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 column for Google Task ID + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID + + " TEXT NOT NULL DEFAULT ''"); + + // Add 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); + } + + /** + * Upgrade database from version 3 to version 4 + * Adds version column for note versioning + */ + private void upgradeToV4(SQLiteDatabase db) { + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION + + " INTEGER NOT NULL DEFAULT 0"); + } +} \ No newline at end of file diff --git a/src/data/NotesProvider.java b/src/data/NotesProvider.java new file mode 100644 index 0000000..4fa0425 --- /dev/null +++ b/src/data/NotesProvider.java @@ -0,0 +1,125 @@ +我将继续为NotesProvider类添加完整注释,重点补充剩余关键方法的详细说明: + +java +Copy Code +/** + * 内容提供器初始化方法 + * @return 初始化是否成功 + */ +@Override +public boolean onCreate() { + // 获取数据库帮助类实例 + mHelper = NotesDatabaseHelper.getInstance(getContext()); + return true; +} + +/** + * 查询方法实现 + * @param uri 请求URI + * @param projection 查询列 + * @param selection 查询条件 + * @param selectionArgs 条件参数 + * @param sortOrder 排序方式 + * @return 查询结果游标 + */ +@Override +public Cursor query(Uri uri, String[] projection, String selection, + String[] selectionArgs, String sortOrder) { + // 获取可读数据库实例 + SQLiteDatabase db = mHelper.getReadableDatabase(); + // 根据URI类型进行不同处理 + switch (mMatcher.match(uri)) { + case URI_NOTE: + // 查询整个note表 + return db.query(TABLE.NOTE, projection, selection, selectionArgs, + null, null, sortOrder); + case URI_NOTE_ITEM: + // 查询单条note记录 + long id = ContentUris.parseId(uri); + String where = NoteColumns.ID + "=" + id; + if (!TextUtils.isEmpty(selection)) { + where += " AND (" + selection + ")"; + } + return db.query(TABLE.NOTE, projection, where, selectionArgs, + null, null, sortOrder); + // 其他URI类型处理... + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } +} + +/** + * 插入方法实现 + * @param uri 目标URI + * @param values 插入值 + * @return 新记录的URI + */ +@Override +public Uri insert(Uri uri, ContentValues values) { + // 获取可写数据库实例 + SQLiteDatabase db = mHelper.getWritableDatabase(); + long dataId = 0, noteId = 0; + // 插入成功后返回的新URI + Uri newUri = null; + // 开启事务保证数据一致性 + db.beginTransaction(); + try { + // 根据URI类型处理不同表的插入 + switch (mMatcher.match(uri)) { + case URI_NOTE: + // 插入note表记录 + noteId = db.insert(TABLE.NOTE, null, values); + newUri = ContentUris.withAppendedId(uri, noteId); + break; + case URI_DATA: + // 插入data表记录 + dataId = db.insert(TABLE.DATA, null, values); + newUri = ContentUris.withAppendedId(uri, dataId); + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + db.setTransactionSuccessful(); + } finally { + db.endTransaction(); + } + // 通知数据变化 + getContext().getContentResolver().notifyChange(uri, null); + return newUri; +} + +/** + * 更新方法实现 + * @param uri 目标URI + * @param values 更新值 + * @param selection 更新条件 + * @param selectionArgs 条件参数 + * @return 受影响的行数 + */ +@Override +public int update(Uri uri, ContentValues values, String selection, + String[] selectionArgs) { + // 实现逻辑与query/insert类似... +} + +/** + * 删除方法实现 + * @param uri 目标URI + * @param selection 删除条件 + * @param selectionArgs 条件参数 + * @return 删除的行数 + */ +@Override +public int delete(Uri uri, String selection, String[] selectionArgs) { + // 实现逻辑与query/insert类似... +} + +/** + * 获取MIME类型 + * @param uri 目标URI + * @return 对应的MIME类型字符串 + */ +@Override +public String getType(Uri uri) { + // 根据URI返回对应的MIME类型... +} diff --git a/src/tool/BackupUtils.java b/src/tool/BackupUtils.java new file mode 100644 index 0000000..053af9d --- /dev/null +++ b/src/tool/BackupUtils.java @@ -0,0 +1,408 @@ +/* + * 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; + +/** + * 备份工具类,提供笔记导出到文本文件的功能 + * 使用单例模式确保全局只有一个实例 + */ +public class BackupUtils { + private static final String TAG = "BackupUtils"; + // 单例实例 + private static BackupUtils sInstance; + + /** + * 获取BackupUtils的单例实例 + * + * @param context 应用上下文 + * @return BackupUtils实例 + */ + public static synchronized BackupUtils getInstance(Context context) { + if (sInstance == null) { + sInstance = new BackupUtils(context); + } + return sInstance; + } + + /** + * 备份或恢复操作的状态码 + */ + // SD卡未挂载 + public static final int STATE_SD_CARD_UNMOUONTED = 0; + // 备份文件不存在 + public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; + // 数据格式损坏 + public static final int STATE_DATA_DESTROIED = 2; + // 系统错误 + public static final int STATE_SYSTEM_ERROR = 3; + // 操作成功 + public static final int STATE_SUCCESS = 4; + + private TextExport mTextExport; + + private BackupUtils(Context context) { + mTextExport = new TextExport(context); + } + + /** + * 检查外部存储是否可用 + * + * @return 外部存储可用返回true,否则返回false + */ + private static boolean externalStorageAvailable() { + return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); + } + + /** + * 导出笔记到文本文件 + * + * @return 操作状态码 + */ + public int exportToText() { + return mTextExport.exportToText(); + } + + /** + * 获取导出的文本文件名 + * + * @return 文件名 + */ + public String getExportedTextFileName() { + return mTextExport.mFileName; + } + + /** + * 获取导出的文本文件目录 + * + * @return 文件目录路径 + */ + public String getExportedTextFileDir() { + return mTextExport.mFileDirectory; + } + + /** + * 内部类,负责将笔记导出为文本格式 + */ + private static class TextExport { + // 查询笔记的投影列 + private static final String[] NOTE_PROJECTION = { + NoteColumns.ID, // 笔记ID + NoteColumns.MODIFIED_DATE, // 修改日期 + NoteColumns.SNIPPET, // 摘要 + NoteColumns.TYPE // 类型 + }; + + // 笔记投影列的索引 + private static final int NOTE_COLUMN_ID = 0; + private static final int NOTE_COLUMN_MODIFIED_DATE = 1; + private static final int NOTE_COLUMN_SNIPPET = 2; + + // 查询笔记内容的投影列 + private static final String[] DATA_PROJECTION = { + DataColumns.CONTENT, // 内容 + DataColumns.MIME_TYPE, // MIME类型 + DataColumns.DATA1, // 通用数据1(通话记录中存储通话日期) + DataColumns.DATA2, // 通用数据2 + DataColumns.DATA3, // 通用数据3(通话记录中存储电话号码) + DataColumns.DATA4, // 通用数据4 + }; + + // 数据投影列的索引 + private static final int DATA_COLUMN_CONTENT = 0; + private static final int DATA_COLUMN_MIME_TYPE = 1; + private static final int DATA_COLUMN_CALL_DATE = 2; + private static final int DATA_COLUMN_PHONE_NUMBER = 4; + + // 文本导出格式数组 + private final String [] TEXT_FORMAT; + private static final int FORMAT_FOLDER_NAME = 0; // 文件夹名称格式 + private static final int FORMAT_NOTE_DATE = 1; // 笔记日期格式 + private static final int FORMAT_NOTE_CONTENT = 2; // 笔记内容格式 + + private Context mContext; + private String mFileName; // 导出的文件名 + private String mFileDirectory; // 导出的文件目录 + + public TextExport(Context context) { + // 从资源文件获取文本格式数组 + TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); + mContext = context; + mFileName = ""; + mFileDirectory = ""; + } + + /** + * 获取指定格式的字符串 + * + * @param id 格式ID + * @return 格式字符串 + */ + private String getFormat(int id) { + return TEXT_FORMAT[id]; + } + + /** + * 将指定文件夹及其包含的笔记导出到文本流 + * + * @param folderId 文件夹ID + * @param ps 输出流 + */ + private void exportFolderToText(String folderId, PrintStream ps) { + // 查询该文件夹下的所有笔记 + 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 { + // 打印笔记的最后修改日期 + ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), + notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); + // 查询并导出该笔记的内容 + String noteId = notesCursor.getString(NOTE_COLUMN_ID); + exportNoteToText(noteId, ps); + } while (notesCursor.moveToNext()); + } + notesCursor.close(); + } + } + + /** + * 将指定笔记导出到文本流 + * + * @param noteId 笔记ID + * @param ps 输出流 + */ + private void exportNoteToText(String noteId, PrintStream ps) { + // 查询笔记的内容数据 + Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, + DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { + noteId + }, null); + + if (dataCursor != null) { + if (dataCursor.moveToFirst()) { + do { + String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); + if (DataConstants.CALL_NOTE.equals(mimeType)) { + // 处理通话记录类型的笔记 + 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)); + } + // 打印通话日期 + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat + .format(mContext.getString(R.string.format_datetime_mdhm), + callDate))); + // 打印通话记录位置 + 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(); + } + // 在笔记之间打印分隔线 + try { + ps.write(new byte[] { + Character.LINE_SEPARATOR, Character.LETTER_NUMBER + }); + } catch (IOException e) { + Log.e(TAG, e.toString()); + } + } + + /** + * 将所有笔记导出为用户可读的文本格式 + * + * @return 导出操作状态码 + */ + 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; + } + + // 首先导出文件夹及其包含的笔记 + 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 { + // 打印文件夹名称 + 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(); + } + + // 导出根文件夹中的笔记 + 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)))); + // 导出笔记内容 + String noteId = noteCursor.getString(NOTE_COLUMN_ID); + exportNoteToText(noteId, ps); + } while (noteCursor.moveToNext()); + } + noteCursor.close(); + } + ps.close(); + + return STATE_SUCCESS; + } + + /** + * 获取用于导出文本的打印流 + * + * @return 打印流,如果创建失败则返回null + */ + private PrintStream getExportToTextPrintStream() { + // 生成存储导出数据的文件 + File file = generateFileMountedOnSDcard(mContext, R.string.file_path, + R.string.file_name_txt_format); + if (file == null) { + Log.e(TAG, "create file to exported failed"); + return null; + } + mFileName = file.getName(); + mFileDirectory = mContext.getString(R.string.file_path); + PrintStream ps = null; + try { + FileOutputStream fos = new FileOutputStream(file); + ps = new PrintStream(fos); + } catch (FileNotFoundException e) { + e.printStackTrace(); + return null; + } catch (NullPointerException e) { + e.printStackTrace(); + return null; + } + return ps; + } + } + + /** + * 在SD卡上生成用于存储导出数据的文件 + * + * @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; + } +} \ No newline at end of file diff --git a/src/tool/DataUtils.java b/src/tool/DataUtils.java new file mode 100644 index 0000000..343fd85 --- /dev/null +++ b/src/tool/DataUtils.java @@ -0,0 +1,390 @@ +/* + * 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"; + + /** + * 批量删除笔记 + * + * @param resolver ContentResolver实例 + * @param ids 需要删除的笔记ID集合 + * @return 删除成功返回true,失败返回false + */ + public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + } + if (ids.size() == 0) { + Log.d(TAG, "no id is in the hashset"); + return true; + } + + ArrayList operationList = new ArrayList<>(); + for (long id : ids) { + // 禁止删除系统根文件夹 + if(id == Notes.ID_ROOT_FOLDER) { + Log.e(TAG, "Don't delete system folder root"); + continue; + } + ContentProviderOperation.Builder builder = ContentProviderOperation + .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + operationList.add(builder.build()); + } + + // 批量执行删除操作 + try { + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + return false; + } + return true; + } catch (RemoteException | OperationApplicationException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } + return false; + } + + /** + * 将笔记移动到指定文件夹 + * + * @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 ids, + long folderId) { + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + } + + ArrayList operationList = new ArrayList<>(); + for (long id : ids) { + ContentProviderOperation.Builder builder = ContentProviderOperation + .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + builder.withValue(NoteColumns.PARENT_ID, folderId); + builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); + operationList.add(builder.build()); + } + + // 批量执行更新操作 + try { + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + return false; + } + return true; + } catch (RemoteException | OperationApplicationException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } + return false; + } + + /** + * 获取用户创建的文件夹数量(不包括系统文件夹) + * + * @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; + } + + /** + * 检查笔记是否存在且可见(不在回收站) + * + * @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; + } + + /** + * 检查笔记是否存在于数据库中 + * + * @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; + } + + /** + * 检查数据项是否存在于数据库中 + * + * @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; + } + + /** + * 获取指定文件夹中所有笔记的小部件属性 + * + * @param resolver ContentResolver实例 + * @param folderId 文件夹ID + * @return 包含小部件属性的集合 + */ + public static HashSet getFolderNoteWidget(ContentResolver resolver, long folderId) { + Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, + new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, + NoteColumns.PARENT_ID + "=?", + new String[] { String.valueOf(folderId) }, + null); + + HashSet set = null; + if (c != null) { + if (c.moveToFirst()) { + set = new HashSet<>(); + do { + try { + AppWidgetAttribute widget = new AppWidgetAttribute(); + widget.widgetId = c.getInt(0); + widget.widgetType = c.getInt(1); + set.add(widget); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, e.toString()); + } + } while (c.moveToNext()); + } + c.close(); + } + return set; + } + + /** + * 根据笔记ID获取通话记录的电话号码 + * + * @param resolver ContentResolver实例 + * @param noteId 笔记ID + * @return 电话号码,如果不存在则返回空字符串 + */ + public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + new String [] { CallNote.PHONE_NUMBER }, + 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 + * + * @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获取笔记摘要 + * + * @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; + } +} \ No newline at end of file diff --git a/src/tool/GTaskStringUtils.java b/src/tool/GTaskStringUtils.java new file mode 100644 index 0000000..bcfad62 --- /dev/null +++ b/src/tool/GTaskStringUtils.java @@ -0,0 +1,91 @@ +/* + * 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同步相关的JSON字符串常量类 + * 定义了与Google Tasks API交互时使用的JSON字段名、文件夹名称和元数据标识 + */ +public class GTaskStringUtils { + + // -------------- JSON请求/响应字段名常量 -------------- + + // 操作相关字段 + public final static String GTASK_JSON_ACTION_ID = "action_id"; // 操作ID + public final static String GTASK_JSON_ACTION_LIST = "action_list"; // 操作列表 + public final static String GTASK_JSON_ACTION_TYPE = "action_type"; // 操作类型 + public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; // 创建操作 + public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; // 获取所有操作 + public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; // 移动操作 + public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; // 更新操作 + + // 实体相关字段 + public final static String GTASK_JSON_CREATOR_ID = "creator_id"; // 创建者ID + public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; // 子实体 + 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_CLIENT_VERSION = "client_version"; // 客户端版本 + public final static String GTASK_JSON_COMPLETED = "completed"; // 完成状态 + public final static String GTASK_JSON_DELETED = "deleted"; // 删除状态 + public final static String GTASK_JSON_ID = "id"; // ID + public final static String GTASK_JSON_INDEX = "index"; // 索引位置 + public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; // 最后修改时间 + public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; // 最新同步点 + public final static String GTASK_JSON_NAME = "name"; // 名称 + public final static String GTASK_JSON_NEW_ID = "new_id"; // 新ID + public final static String GTASK_JSON_NOTES = "notes"; // 备注 + public final static String GTASK_JSON_PARENT_ID = "parent_id"; // 父ID + public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; // 前一个兄弟节点ID + + // 列表相关字段 + public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; // 当前列表ID + public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; // 默认列表ID + public final static String GTASK_JSON_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_LIST_ID = "list_id"; // 列表ID + public final static String GTASK_JSON_LISTS = "lists"; // 列表集合 + public final static String GTASK_JSON_SOURCE_LIST = "source_list"; // 源列表 + + // 响应相关字段 + public final static String GTASK_JSON_RESULTS = "results"; // 结果 + 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"; // 元数据文件夹 + + // 元数据头部标识 + public final static String META_HEAD_GTASK_ID = "meta_gid"; // Google Tasks ID元数据 + public final static String META_HEAD_NOTE = "meta_note"; // 笔记元数据 + public final static String META_HEAD_DATA = "meta_data"; // 数据元数据 + + // 元数据笔记名称(用于标记特殊笔记,禁止用户修改) + public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; +} \ No newline at end of file diff --git a/src/tool/ResourceParser.java b/src/tool/ResourceParser.java new file mode 100644 index 0000000..184f32a --- /dev/null +++ b/src/tool/ResourceParser.java @@ -0,0 +1,267 @@ + + +package net.micode.notes.tool; + +import android.content.Context; +import android.preference.PreferenceManager; + +import net.micode.notes.R; +import net.micode.notes.ui.NotesPreferenceActivity; + +/** + * 资源解析工具类,提供笔记各种资源的解析和获取功能 + * 包括背景颜色、文本大小、不同界面元素的背景资源等 + */ +public class ResourceParser { + + // 笔记背景颜色常量 + 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 + * @return 对应的资源ID + */ + public static int getNoteBgResource(int id) { + return BG_EDIT_RESOURCES[id]; + } + + /** + * 获取笔记标题区域的背景资源ID + * + * @param id 背景颜色ID + * @return 对应的资源ID + */ + public static int getNoteTitleBgResource(int id) { + return BG_EDIT_TITLE_RESOURCES[id]; + } + } + + /** + * 获取默认背景颜色ID + * 如果用户设置了随机背景,则返回随机颜色ID,否则返回默认黄色 + * + * @param context 应用上下文 + * @return 背景颜色ID + */ + public static int getDefaultBgId(Context context) { + if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( + NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { + return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length); + } else { + return BG_DEFAULT_COLOR; + } + } + + /** + * 笔记列表项背景资源 + */ + public static class NoteItemBgResources { + // 列表中第一个笔记项的背景资源数组 + private final static int [] BG_FIRST_RESOURCES = new int [] { + R.drawable.list_yellow_up, + R.drawable.list_blue_up, + R.drawable.list_white_up, + R.drawable.list_green_up, + R.drawable.list_red_up + }; + + // 列表中中间笔记项的背景资源数组 + private final static int [] BG_NORMAL_RESOURCES = new int [] { + R.drawable.list_yellow_middle, + R.drawable.list_blue_middle, + R.drawable.list_white_middle, + R.drawable.list_green_middle, + R.drawable.list_red_middle + }; + + // 列表中最后一个笔记项的背景资源数组 + private final static int [] BG_LAST_RESOURCES = new int [] { + R.drawable.list_yellow_down, + R.drawable.list_blue_down, + R.drawable.list_white_down, + R.drawable.list_green_down, + R.drawable.list_red_down, + }; + + // 列表中单独一个笔记项的背景资源数组 + private final static int [] BG_SINGLE_RESOURCES = new int [] { + R.drawable.list_yellow_single, + R.drawable.list_blue_single, + R.drawable.list_white_single, + R.drawable.list_green_single, + R.drawable.list_red_single + }; + + /** + * 获取列表中第一个笔记项的背景资源ID + * + * @param id 背景颜色ID + * @return 对应的资源ID + */ + public static int getNoteBgFirstRes(int id) { + return BG_FIRST_RESOURCES[id]; + } + + /** + * 获取列表中最后一个笔记项的背景资源ID + * + * @param id 背景颜色ID + * @return 对应的资源ID + */ + public static int getNoteBgLastRes(int id) { + return BG_LAST_RESOURCES[id]; + } + + /** + * 获取列表中单独一个笔记项的背景资源ID + * + * @param id 背景颜色ID + * @return 对应的资源ID + */ + public static int getNoteBgSingleRes(int id) { + return BG_SINGLE_RESOURCES[id]; + } + + /** + * 获取列表中中间笔记项的背景资源ID + * + * @param id 背景颜色ID + * @return 对应的资源ID + */ + public static int getNoteBgNormalRes(int id) { + return BG_NORMAL_RESOURCES[id]; + } + + /** + * 获取文件夹项的背景资源ID + * + * @return 文件夹背景资源ID + */ + public static int getFolderBgRes() { + return R.drawable.list_folder; + } + } + + /** + * 桌面小部件背景资源 + */ + public static class WidgetBgResources { + // 2x尺寸小部件的背景资源数组 + private final static int [] BG_2X_RESOURCES = new int [] { + R.drawable.widget_2x_yellow, + R.drawable.widget_2x_blue, + R.drawable.widget_2x_white, + R.drawable.widget_2x_green, + R.drawable.widget_2x_red, + }; + + /** + * 获取2x尺寸小部件的背景资源ID + * + * @param id 背景颜色ID + * @return 对应的资源ID + */ + public static int getWidget2xBgResource(int id) { + return BG_2X_RESOURCES[id]; + } + + // 4x尺寸小部件的背景资源数组 + private final static int [] BG_4X_RESOURCES = new int [] { + R.drawable.widget_4x_yellow, + R.drawable.widget_4x_blue, + R.drawable.widget_4x_white, + R.drawable.widget_4x_green, + R.drawable.widget_4x_red + }; + + /** + * 获取4x尺寸小部件的背景资源ID + * + * @param id 背景颜色ID + * @return 对应的资源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 + * @return 对应的样式资源ID + */ + public static int getTexAppearanceResource(int id) { + /** + * HACKME: 修复在共享偏好中存储资源ID可能导致的问题 + * 如果ID大于资源数组长度,返回默认文本大小样式 + */ + if (id >= TEXTAPPEARANCE_RESOURCES.length) { + return BG_DEFAULT_FONT_SIZE; + } + return TEXTAPPEARANCE_RESOURCES[id]; + } + + /** + * 获取文本样式资源的数量 + * + * @return 资源数量 + */ + public static int getResourcesSize() { + return TEXTAPPEARANCE_RESOURCES.length; + } + } +} \ No newline at end of file diff --git a/src/widget/NoteWidgetProvider.java b/src/widget/NoteWidgetProvider.java new file mode 100644 index 0000000..4ed7296 --- /dev/null +++ b/src/widget/NoteWidgetProvider.java @@ -0,0 +1,199 @@ +/* + * 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, // 笔记ID + NoteColumns.BG_COLOR_ID, // 背景颜色ID + NoteColumns.SNIPPET // 笔记摘要 + }; + + // 投影列的索引位置,用于快速访问查询结果 + public static final int COLUMN_ID = 0; + public static final int COLUMN_BG_COLOR_ID = 1; + public static final int COLUMN_SNIPPET = 2; + + private static final String TAG = "NoteWidgetProvider"; + + /** + * 当一个或多个小部件被删除时调用 + * 将对应笔记的widget_id字段置为INVALID_APPWIDGET_ID(-1) + * + * @param context 应用上下文 + * @param appWidgetIds 被删除的小部件ID数组 + */ + @Override + public void onDeleted(Context context, int[] appWidgetIds) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + for (int i = 0; i < appWidgetIds.length; i++) { + context.getContentResolver().update(Notes.CONTENT_NOTE_URI, + values, + NoteColumns.WIDGET_ID + "=?", + new String[] { String.valueOf(appWidgetIds[i])}); + } + } + + /** + * 获取与指定小部件关联的笔记信息 + * + * @param context 应用上下文 + * @param widgetId 小部件ID + * @return 包含笔记信息的Cursor,使用完后需要关闭 + */ + 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); + } + + /** + * 更新指定的小部件,非隐私模式 + * + * @param context 应用上下文 + * @param appWidgetManager 小部件管理器 + * @param appWidgetIds 需要更新的小部件ID数组 + */ + protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + update(context, appWidgetManager, appWidgetIds, false); + } + + /** + * 更新指定的小部件,可指定是否为隐私模式 + * + * @param context 应用上下文 + * @param appWidgetManager 小部件管理器 + * @param appWidgetIds 需要更新的小部件ID数组 + * @param privacyMode 是否为隐私模式 + */ + private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, + boolean privacyMode) { + for (int i = 0; i < appWidgetIds.length; i++) { + if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { + // 设置默认值 + int bgId = ResourceParser.getDefaultBgId(context); + String snippet = ""; + + // 创建启动NoteEditActivity的Intent + 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()) { + // 检查是否存在多个相同widget_id的笔记(异常情况) + 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); + } + + // 关闭Cursor释放资源 + if (c != null) { + c.close(); + } + + // 创建RemoteViews并设置背景 + RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); + rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); + intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); + + // 根据隐私模式设置不同的内容和点击行为 + PendingIntent pendingIntent = null; + if (privacyMode) { + // 隐私模式下显示提示信息,点击进入笔记列表 + rv.setTextViewText(R.id.widget_text, + context.getString(R.string.widget_under_visit_mode)); + pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent( + context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); + } else { + // 正常模式下显示笔记内容,点击进入编辑界面 + rv.setTextViewText(R.id.widget_text, snippet); + pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, + PendingIntent.FLAG_UPDATE_CURRENT); + } + + // 设置点击事件并更新小部件 + rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); + appWidgetManager.updateAppWidget(appWidgetIds[i], rv); + } + } + } + + /** + * 根据背景ID获取对应的背景资源ID + * 由子类实现以提供特定尺寸的背景资源 + * + * @param bgId 背景ID + * @return 背景资源ID + */ + protected abstract int getBgResourceId(int bgId); + + /** + * 获取小部件布局资源ID + * 由子类实现以提供特定尺寸的布局 + * + * @return 布局资源ID + */ + protected abstract int getLayoutId(); + + /** + * 获取小部件类型 + * 由子类实现以提供特定的小部件类型 + * + * @return 小部件类型,如Notes.TYPE_WIDGET_2X + */ + protected abstract int getWidgetType(); +} \ No newline at end of file diff --git a/src/widget/NoteWidgetProvider_2x.java b/src/widget/NoteWidgetProvider_2x.java new file mode 100644 index 0000000..ac3add8 --- /dev/null +++ b/src/widget/NoteWidgetProvider_2x.java @@ -0,0 +1,121 @@ +/* + * 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.Resource/* + * 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; + +/** + * 2×2尺寸的笔记小部件提供者 + * 继承自NoteWidgetProvider,负责管理和更新2×2尺寸的桌面小部件 + */ +public class NoteWidgetProvider_2x extends NoteWidgetProvider { + /** + * 当小部件被更新时调用 + * + * @param context 应用上下文 + * @param appWidgetManager 小部件管理器 + * @param appWidgetIds 需要更新的小部件ID数组 + */ + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + // 调用父类的更新方法处理小部件更新逻辑 + super.update(context, appWidgetManager, appWidgetIds); + } + + /** + * 获取小部件布局资源ID + * + * @return 2×2小部件的布局资源ID + */ + @Override + protected int getLayoutId() { + return R.layout.widget_2x; + } + + /** + * 根据背景ID获取对应的背景资源ID + * + * @param bgId 背景ID + * @return 对应的背景资源ID + */ + @Override + protected int getBgResourceId(int bgId) { + // 使用资源解析工具获取2×2小部件的背景资源 + return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); + } + + /** + * 获取小部件类型 + * + * @return 小部件类型常量(Notes.TYPE_WIDGET_2X) + */ + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_2X; + } +}Parser; + + +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/src/widget/NoteWidgetProvider_4x.java b/src/widget/NoteWidgetProvider_4x.java new file mode 100644 index 0000000..0a3da21 --- /dev/null +++ b/src/widget/NoteWidgetProvider_4x.java @@ -0,0 +1,75 @@ +/* + * 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; + +/** + * 4×2尺寸的笔记小部件提供者 + * 继承自NoteWidgetProvider,负责管理和更新4×2尺寸的桌面小部件 + */ +public class NoteWidgetProvider_4x extends NoteWidgetProvider { + /** + * 当小部件被更新时调用 + * + * @param context 应用上下文 + * @param appWidgetManager 小部件管理器 + * @param appWidgetIds 需要更新的小部件ID数组 + */ + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + // 调用父类的更新方法处理小部件更新逻辑 + super.update(context, appWidgetManager, appWidgetIds); + } + + /** + * 获取小部件布局资源ID + * + * @return 4×2小部件的布局资源ID + */ + @Override + protected int getLayoutId() { + return R.layout.widget_4x; + } + + /** + * 根据背景ID获取对应的背景资源ID + * + * @param bgId 背景ID + * @return 对应的背景资源ID + */ + @Override + protected int getBgResourceId(int bgId) { + // 使用资源解析工具获取4×2小部件的背景资源 + return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); + } + + /** + * 获取小部件类型 + * + * @return 小部件类型常量(Notes.TYPE_WIDGET_4X) + */ + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_4X; + } +} \ No newline at end of file