diff --git a/cjwshiyan/doc/CS小米便签开源代码的泛读报告.docx b/cjwshiyan/doc/CS小米便签开源代码的泛读报告.docx new file mode 100644 index 0000000..b50963a Binary files /dev/null and b/cjwshiyan/doc/CS小米便签开源代码的泛读报告.docx differ diff --git a/cjwshiyan/doc/运行成功截图/3abce6bab5c31e773247a27a767a0b9.png b/cjwshiyan/doc/运行成功截图/3abce6bab5c31e773247a27a767a0b9.png new file mode 100644 index 0000000..ee3274c Binary files /dev/null and b/cjwshiyan/doc/运行成功截图/3abce6bab5c31e773247a27a767a0b9.png differ diff --git a/cjwshiyan/doc/运行成功截图/af4f3bdf7a52e258512c5cb6eb30637.png b/cjwshiyan/doc/运行成功截图/af4f3bdf7a52e258512c5cb6eb30637.png new file mode 100644 index 0000000..d846b47 Binary files /dev/null and b/cjwshiyan/doc/运行成功截图/af4f3bdf7a52e258512c5cb6eb30637.png differ diff --git a/cjwshiyan/src/data/Contact.java b/cjwshiyan/src/data/Contact.java new file mode 100644 index 0000000..bd81554 --- /dev/null +++ b/cjwshiyan/src/data/Contact.java @@ -0,0 +1,65 @@ +package net.micode.notes.data; // 定义包名 + +import android.content.Context; // 导入Context类,用于获取应用环境和资源 +import android.database.Cursor; // 导入Cursor类,用于数据库查询结果集的迭代 +import android.provider.ContactsContract.CommonDataKinds.Phone; // 导入Phone类,用于访问联系人电话数据 +import android.provider.ContactsContract.Data; // 导入Data类,用于访问联系人数据 +import android.telephony.PhoneNumberUtils; // 导入PhoneNumberUtils类,用于电话号码操作 +import android.util.Log; // 导入Log类,用于日志输出 + +import java.util.HashMap; // 导入HashMap类,用于缓存联系人数据 + +public class Contact { // 定义Contact类,用于处理联系人相关信息 + private static HashMap sContactCache; // 用于缓存联系人姓名的HashMap + private static final String TAG = "Contact"; // 日志标签 + + // 定义查询联系人的SQL选择语句 + 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 = '+')"; + + // 获取联系人姓名的方法 + public static String getContact(Context context, String phoneNumber) { + // 如果缓存为空,则初始化缓存 + if (sContactCache == null) { + sContactCache = new HashMap(); + } + + // 检查缓存中是否已有该电话号码对应的联系人姓名 + if (sContactCache.containsKey(phoneNumber)) { + return sContactCache.get(phoneNumber); // 返回缓存中的联系人姓名 + } + + // 替换SQL选择语句中的"+"符号为电话号码的最小匹配字符串 + 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; // 返回null表示未找到联系人 + } finally { + cursor.close(); // 关闭游标 + } + } else { + Log.d(TAG, "No contact matched with number:" + phoneNumber); // 输出调试日志 + return null; // 返回null表示未找到联系人 + } + } +} diff --git a/cjwshiyan/src/data/Notes.java b/cjwshiyan/src/data/Notes.java new file mode 100644 index 0000000..820295d --- /dev/null +++ b/cjwshiyan/src/data/Notes.java @@ -0,0 +1,100 @@ +package net.micode.notes.data; // 定义包名 + +import android.content.ContentUris; // 用于操作URI,如添加ID到URI中 +import android.net.Uri; // 用于表示URI的类 + +// Notes 类定义了与便签应用相关的常量,包括URI、类型、ID等 +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)中使用的额外数据键 + public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // 警告日期 + public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; // 背景颜色ID + public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // 小部件ID + public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // 小部件类型 + public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹ID + public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; // 电话日期 + + // 小部件类型的常量 + public static final int TYPE_WIDGET_INVALIDE = -1; // 无效的小部件类型 + public static final int TYPE_WIDGET_2X = 0; // 2x2小部件 + public static final int TYPE_WIDGET_4X = 1; // 4x4小部件 + + // 数据常量类,包含笔记和电话记录的MIME类型 + 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"); + + // NoteColumns接口定义了笔记相关字段 + public interface NoteColumns { + public static final String ID = "_id"; // 唯一ID + public static final String PARENT_ID = "parent_id"; // 父ID,用于文件夹结构 + public static final String CREATED_DATE = "created_date"; // 创建日期 + public static final String MODIFIED_DATE = "modified_date"; // 修改日期 + public static final String ALERTED_DATE = "alert_date"; // 警告日期 + public static final String SNIPPET = "snippet"; // 文件夹名或笔记内容摘要 + public static final String WIDGET_ID = "widget_id"; // 小部件ID + public static final String WIDGET_TYPE = "widget_type"; // 小部件类型 + public static final String BG_COLOR_ID = "bg_color_id"; // 背景颜色ID + public static final String HAS_ATTACHMENT = "has_attachment"; // 是否有附件 + public static final String NOTES_COUNT = "notes_count"; // 文件夹中的笔记数量 + public static final String TYPE = "type"; // 类型(笔记或文件夹) + public static final String SYNC_ID = "sync_id"; // 同步ID + public static final String LOCAL_MODIFIED = "local_modified"; // 本地修改标志 + public static final String ORIGIN_PARENT_ID = "origin_parent_id"; // 原始父ID + public static final String GTASK_ID = "gtask_id"; // Google任务ID + public static final String VERSION = "version"; // 版本号 + } + + // DataColumns接口定义了数据表相关字段 + public interface DataColumns { + public static final String ID = "_id"; // 唯一ID + public static final String MIME_TYPE = "mime_type"; // MIME类型 + public static final String NOTE_ID = "note_id"; // 对应的笔记ID + public static final String CREATED_DATE = "created_date"; // 创建日期 + public static final String MODIFIED_DATE = "modified_date"; // 修改日期 + public static final String CONTENT = "content"; // 数据内容 + public static final String DATA1 = "data1"; // 通用数据列1 + public static final String DATA2 = "data2"; // 通用数据列2 + public static final String DATA3 = "data3"; // 通用数据列3 + public static final String DATA4 = "data4"; // 通用数据列4 + public static final String DATA5 = "data5"; // 通用数据列5 + } + + // TextNote类定义了文本笔记相关的常量 + public static final class TextNote implements DataColumns { + 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"; // 目录MIME类型 + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; // 项目MIME类型 + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); // 文本笔记URI + } + + // CallNote类定义了电话记录相关的常量 + public static final class CallNote implements DataColumns { + public static final String CALL_DATE = DATA1; // 电话日期 + public static final String PHONE_NUMBER = DATA3; // 电话号码 + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; // 目录MIME类型 + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; // 项目MIME类型 + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); // 电话记录URI + } +} diff --git a/cjwshiyan/src/data/NotesDatabaseHelper.java b/cjwshiyan/src/data/NotesDatabaseHelper.java new file mode 100644 index 0000000..5f0c535 --- /dev/null +++ b/cjwshiyan/src/data/NotesDatabaseHelper.java @@ -0,0 +1,180 @@ +package net.micode.notes.data; // 定义包名 + +import android.content.ContentValues; // 用于存储数据的键值对,便于数据库操作 +import android.content.Context; // 用于访问应用环境和资源 +import android.database.sqlite.SQLiteDatabase; // 用于执行SQL语句和进行数据库操作 +import android.database.sqlite.SQLiteOpenHelper; // 管理数据库创建和版本控制的帮助类 +import android.util.Log; // 用于日志输出 + +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +// 导入相关类,用于定义数据库表格的列名和常量 + +public class NotesDatabaseHelper extends SQLiteOpenHelper { + private static final String DB_NAME = "note.db"; // 数据库名称 + private static final int DB_VERSION = 4; // 数据库版本号 + + public interface TABLE { + public static final String NOTE = "note"; // 笔记表名称 + public static final String DATA = "data"; // 数据表名称 + } + + private static final String TAG = "NotesDatabaseHelper"; // 日志标签 + private static NotesDatabaseHelper mInstance; // 单例模式中的实例 + + // 创建笔记表的SQL语句 + private static final String CREATE_NOTE_TABLE_SQL = "CREATE TABLE " + TABLE.NOTE + "(" + + // 定义各列及其数据类型和约束条件 + ")"; + + // 创建数据表的SQL语句 + private static final String CREATE_DATA_TABLE_SQL = "CREATE TABLE " + TABLE.DATA + "(" + + // 定义各列及其数据类型和约束条件 + ")"; + + // 创建索引以加快根据NOTE_ID查询的速度 + private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = "CREATE INDEX IF NOT EXISTS note_id_index ON " + + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; + + // 定义触发器,当笔记移动到文件夹时增加文件夹中的笔记计数 + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = "CREATE TRIGGER increase_folder_count_on_update " + + // 触发器定义及逻辑 + " END"; + + // 定义触发器,当笔记从文件夹中移出时减少文件夹中的笔记计数 + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = "CREATE TRIGGER decrease_folder_count_on_update " + + // 触发器定义及逻辑 + " END"; + + // 定义触发器,当向文件夹中插入新笔记时增加文件夹中的笔记计数 + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = "CREATE TRIGGER increase_folder_count_on_insert " + + // 触发器定义及逻辑 + " END"; + + // 定义触发器,当从文件夹中删除笔记时减少文件夹中的笔记计数 + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = "CREATE TRIGGER decrease_folder_count_on_delete " + + // 触发器定义及逻辑 + " END"; + + // 定义触发器,当插入新数据时更新笔记的内容摘要 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = "CREATE TRIGGER update_note_content_on_insert " + + // 触发器定义及逻辑 + " END"; + + // 定义触发器,当数据更新时更新笔记的内容摘要 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = "CREATE TRIGGER update_note_content_on_update " + + // 触发器定义及逻辑 + " END"; + + // 定义触发器,当数据删除时清除笔记的内容摘要 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = "CREATE TRIGGER update_note_content_on_delete " + + // 触发器定义及逻辑 + " END"; + + // 定义触发器,当删除笔记时同时删除相关的数据 + private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = "CREATE TRIGGER delete_data_on_delete " + + // 触发器定义及逻辑 + " END"; + + // 定义触发器,当删除文件夹时同时删除文件夹中的所有笔记 + private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = "CREATE TRIGGER folder_delete_notes_on_delete " + + // 触发器定义及逻辑 + " END"; + + // 定义触发器,当文件夹移动到垃圾桶时将文件夹中的所有笔记也移动到垃圾桶 + private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = "CREATE TRIGGER folder_move_notes_on_trash " + + // 触发器定义及逻辑 + " END"; + + public NotesDatabaseHelper(Context context) { + super(context, DB_NAME, null, DB_VERSION); // 调用父类构造函数 + } + + public void createNoteTable(SQLiteDatabase db) { + db.execSQL(CREATE_NOTE_TABLE_SQL); // 执行创建笔记表的SQL语句 + reCreateNoteTableTriggers(db); // 重新创建笔记表的触发器 + createSystemFolder(db); // 创建系统文件夹 + Log.d(TAG, "note table has been created"); // 输出日志 + } + + 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); + } + + private void createSystemFolder(SQLiteDatabase db) { + ContentValues values = new ContentValues(); + // 创建系统文件夹 + values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + // 创建其他系统文件夹 + // ... + } + + public void createDataTable(SQLiteDatabase db) { + db.execSQL(CREATE_DATA_TABLE_SQL); // 执行创建数据表的SQL语句 + reCreateDataTableTriggers(db); // 重新创建数据表的触发器 + db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); // 创建索引 + Log.d(TAG, "data table has been created"); // 输出日志 + } + + 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); + } + + static synchronized NotesDatabaseHelper getInstance(Context context) { + if (mInstance == null) { + mInstance = new NotesDatabaseHelper(context); + } + return mInstance; + } + + @Override + public void onCreate(SQLiteDatabase db) { + createNoteTable(db); // 创建笔记表 + createDataTable(db); // 创建数据表 + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + // 数据库版本升级逻辑 + } + + private void upgradeToV2(SQLiteDatabase db) { + // 升级到版本2的逻辑 + } + + private void upgradeToV3(SQLiteDatabase db) { + // 升级到版本3的逻辑 + } + + private void upgradeToV4(SQLiteDatabase db) { + // 升级到版本4的逻辑 + } +} diff --git a/cjwshiyan/src/data/NotesProvider.java b/cjwshiyan/src/data/NotesProvider.java new file mode 100644 index 0000000..cf445c0 --- /dev/null +++ b/cjwshiyan/src/data/NotesProvider.java @@ -0,0 +1,323 @@ +package net.micode.notes.data; // 定义包名 +import android.app.SearchManager; // 搜索管理器,用于处理搜索建议等 +import android.content.ContentProvider; // Android内容提供者基类 +import android.content.ContentUris; // 用于操作URI,如添加ID到URI中 +import android.content.ContentValues; // 用于存储数据的键值对,便于数据库操作 +import android.content.Intent; // 用于应用程序之间传递数据的意图 +import android.content.UriMatcher; // 用于匹配URI +import android.database.Cursor; // 用于数据库查询结果集的迭代 +import android.database.sqlite.SQLiteDatabase; // 用于执行SQL语句和进行数据库操作 +import android.net.Uri; // 用于表示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; // 数据表名称常量 + +// NotesProvider类继承自ContentProvider,用于提供数据共享接口 +public class NotesProvider extends ContentProvider { + // UriMatcher用于匹配URI + private static final UriMatcher mMatcher; + + private NotesDatabaseHelper mHelper; // 数据库帮助类实例 + + private static final String TAG = "NotesProvider"; // 日志标签 + + // 定义匹配URI的常量 + private static final int URI_NOTE = 1;//用于标识笔记资源 + private static final int URI_NOTE_ITEM = 2;//用于标识单个笔记资源 + private static final int URI_DATA = 3;//用于标识数据资源 + private static final int URI_DATA_ITEM = 4;//用于标识单个数据资源 + private static final int URI_SEARCH = 5;//搜索功能 + private static final int URI_SEARCH_SUGGEST = 6;//用于标识搜索功能 + + static { + // 创建UriMatcher时,调用UriMatcher(UriMatcher.NO_MATCH)表示不匹配任何路径的返回码 + mMatcher = new UriMatcher(UriMatcher.NO_MATCH); + // 把需要匹配URI路径全部给注册上 + mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);//笔记表 + mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);//笔记表中的某条记录 + mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);//数据表 + 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);//搜索建议 + } + + // 声明搜索结果的投影 + private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","//笔记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;//意图数据类型 + + // 声明搜索查询 + private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION//查询语句 + + " FROM " + TABLE.NOTE//表名 + + " WHERE " + NoteColumns.SNIPPET + " LIKE ?"//查询条件 + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER//排除回收站 + + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;//笔记类型 + + @Override + // Context只有在onCreate()中才被初始化,对mHelper进行实例化 + public boolean onCreate() { + mHelper = NotesDatabaseHelper.getInstance(getContext()); + return true; + } + + @Override + // 查询uri在数据库中对应的位置 + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + String sortOrder) { + Cursor c = null; + // 获取可读数据库 + SQLiteDatabase db = mHelper.getReadableDatabase(); + String id = null; + // 匹配查找uri + switch (mMatcher.match(uri)) { + // 对于不同的匹配值,在数据库中查找相应的条目 + case URI_NOTE: + c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_NOTE_ITEM: + id = uri.getPathSegments().get(1); + c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_DATA: + c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_DATA_ITEM: + id = uri.getPathSegments().get(1); + c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_SEARCH: + case URI_SEARCH_SUGGEST: + if (sortOrder != null || projection != null) { + // 不合法的参数异常 + throw new IllegalArgumentException( + "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); + } + + String searchString = null; + if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { + if (uri.getPathSegments().size() > 1) { + // getPathSegments()方法得到一个String的List, + // 在uri.getPathSegments().get(1)为第2个元素 + searchString = uri.getPathSegments().get(1); + } + } else { + searchString = uri.getQueryParameter("pattern"); + } + + if (TextUtils.isEmpty(searchString)) { + return null; + } + + try { + searchString = String.format("%%%s%%", searchString); + c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, + new String[] { searchString }); + } catch (IllegalStateException ex) { + Log.e(TAG, "got exception: " + ex.toString()); + } + break; + default: + // 抛出异常 + throw new IllegalArgumentException("Unknown URI " + uri); + } + if (c != null) { + c.setNotificationUri(getContext().getContentResolver(), uri); + } + return c; + } + + @Override + // 插入一个uri + 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; + // 如果存在,查找NOTE_ID + 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 + // notifyChange获得一个ContextResolver对象并且更新里面的内容 + if (noteId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); + } + + // Notify the data uri + if (dataId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); + } + + // 返回插入的uri的路径 + return ContentUris.withAppendedId(uri, insertedId); + } + + @Override + // 删除一个uri + public int delete(Uri uri, String selection, String[] selectionArgs) { + // Uri代表要操作的数据,Android上可用的每种资源 -包括 图像、视频片段、音频资源等都可以用Uri来表示。 + 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 = uri.getPathSegments().get(1); + /** + * ID that smaller than 0 is system folder which is not allowed to + * trash + */ + long noteId = Long.valueOf(id); + if (noteId <= 0) { + break; + } + count = db.delete(TABLE.NOTE, + NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + break; + case URI_DATA: + count = db.delete(TABLE.DATA, selection, selectionArgs); + deleteData = true; + break; + case URI_DATA_ITEM: + id = uri.getPathSegments().get(1); + count = db.delete(TABLE.DATA, + DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + deleteData = true; + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + if (count > 0) { + if (deleteData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } + + @Override +// 更新一个uri +public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + int count = 0; // 记录更新的行数 + String id = null; // 用于存储URI中的ID部分 + SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写的数据库实例 + boolean updateData = false; // 标记是否需要更新数据表 + + // 根据URI匹配不同的操作 + switch (mMatcher.match(uri)) { + case URI_NOTE: + // 更新笔记表中的多条记录 + increaseNoteVersion(-1, selection, selectionArgs); // 增加笔记版本号 + count = db.update(TABLE.NOTE, values, selection, selectionArgs); // 执行更新操作 + break; + case URI_NOTE_ITEM: + // 更新笔记表中的单条记录 + id = uri.getPathSegments().get(1); // 从URI中获取ID + 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; // 设置更新数据表的标记为true + break; + case URI_DATA_ITEM: + // 更新数据表中的单条记录 + id = uri.getPathSegments().get(1); // 从URI中获取ID + count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); // 执行更新操作 + updateData = true; // 设置更新数据表的标记为true + break; + default: + // 如果URI不匹配任何已知类型,则抛出异常 + throw new IllegalArgumentException("Unknown URI " + uri); + } + + // 如果有行被更新,则通知相关URI的监听器 + if (count > 0) { + if (updateData) { + // 如果更新了数据表,则通知笔记表的URI + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + // 通知当前URI的监听器 + getContext().getContentResolver().notifyChange(uri, null); + } + return count; // 返回更新的行数 +} + +/// 将字符串解析成规定格式 +private String parseSelection(String selection) { + // 如果传入的选择字符串不为空,则在 selection 前后添加 " AND (" 和 ")",否则返回空字符串 + return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); +} + +// 增加一个noteVersion +private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { + // 创建StringBuilder对象,用于构建SQL语句 + StringBuilder sql = new StringBuilder(120); + sql.append("UPDATE "); // 添加UPDATE关键字 + sql.append(TABLE.NOTE); // 添加表名NOTE + sql.append(" SET "); // 添加SET关键字 + sql.append(NoteColumns.VERSION); // 添加版本号列名 + sql.append("=" + NoteColumns.VERSION + "+1 "); // 版本号列值加1 + + // 如果ID大于0或者选择字符串不为空,则添加WHERE关键字 + if (id > 0 || !TextUtils.isEmpty(selection)) { + sql.append(" WHERE "); + } + // 如果ID大于0,则添加ID等于指定值的条件 + 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); + } + + // 使用execSQL方法执行构建的SQL语句 + mHelper.getWritableDatabase().execSQL(sql.toString()); +} + +@Override +public String getType(Uri uri) { + // TODO: 需要实现该方法来返回给定URI的MIME类型,暂时返回null + return null; +} diff --git a/cjwshiyan/src/widget/NoteWidgetProvider.java b/cjwshiyan/src/widget/NoteWidgetProvider.java new file mode 100644 index 0000000..f21ab85 --- /dev/null +++ b/cjwshiyan/src/widget/NoteWidgetProvider.java @@ -0,0 +1,151 @@ +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 { + // 定义查询投影,包括ID、背景颜色ID和片段 + 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对象,用于更新小部件ID + ContentValues values = new ContentValues(); + values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + // 遍历所有被删除的小部件ID + for (int i = 0; i < appWidgetIds.length; i++) { + // 更新数据库中对应的小部件ID为无效ID + context.getContentResolver().update(Notes.CONTENT_NOTE_URI, + values, + NoteColumns.WIDGET_ID + "=?", + new String[] { String.valueOf(appWidgetIds[i])}); + } + } + + // 获取小部件信息 + private Cursor getNoteWidgetInfo(Context context, int widgetId) { + // 查询数据库,获取指定小部件ID的信息 + 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) { + // 遍历所有小部件ID + for (int i = 0; i < appWidgetIds.length; i++) { + // 如果小部件ID有效 + if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { + // 获取默认背景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()) { + // 如果查询结果有多个记录,记录错误日志 + if (c.getCount() > 1) { + Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]); + c.close(); + return; + } + // 获取片段和背景ID + snippet = c.getString(COLUMN_SNIPPET); + bgId = c.getInt(COLUMN_BG_COLOR_ID); + // 设置Intent的UID + 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对象,用于更新小部件UI + 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 pendingIntent = null; + // 如果处于隐私模式 + if (privacyMode) { + // 设置文本为隐私模式提示 + rv.setTextViewText(R.id.widget_text, + context.getString(R.string.widget_under_visit_mode)); + // 创建启动NotesListActivity的PendingIntent + pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent( + context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); + } else { + // 设置文本为片段内容 + rv.setTextViewText(R.id.widget_text, snippet); + // 创建启动NoteEditActivity的PendingIntent + pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, + PendingIntent.FLAG_UPDATE_CURRENT); + } + + // 设置点击事件 + rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); + // 更新小部件 + appWidgetManager.updateAppWidget(appWidgetIds[i], rv); + } + } + } + + // 获取背景资源ID + protected abstract int getBgResourceId(int bgId); + + // 获取布局ID + protected abstract int getLayoutId(); + + // 获取小部件类型 + protected abstract int getWidgetType(); +} \ No newline at end of file diff --git a/cjwshiyan/src/widget/NoteWidgetProvider_2x.java b/cjwshiyan/src/widget/NoteWidgetProvider_2x.java new file mode 100644 index 0000000..17c7ceb --- /dev/null +++ b/cjwshiyan/src/widget/NoteWidgetProvider_2x.java @@ -0,0 +1,46 @@ +/* + * 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) { + // 调用父类的update方法 + super.update(context, appWidgetManager, appWidgetIds); + } + // 获取小部件布局ID + @Override + protected int getLayoutId() { + return R.layout.widget_2x; + } + // 获取小部件背景资源ID + @Override + protected int getBgResourceId(int bgId) { + // 调用ResourceParser获取2x小部件的背景资源ID + return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); + } + // 获取小部件类型 + @Override + protected int getWidgetType() { + // 返回2x小部件的类型 + return Notes.TYPE_WIDGET_2X; + } +} \ No newline at end of file diff --git a/cjwshiyan/src/widget/NoteWidgetProvider_4x.java b/cjwshiyan/src/widget/NoteWidgetProvider_4x.java new file mode 100644 index 0000000..7bd10a0 --- /dev/null +++ b/cjwshiyan/src/widget/NoteWidgetProvider_4x.java @@ -0,0 +1,57 @@ +/* + * 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. + */ +Java + + + + + 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) { + // 调用父类的update方法 + super.update(context, appWidgetManager, appWidgetIds); + } + + // 获取小部件布局ID + protected int getLayoutId() { + return R.layout.widget_4x; + } + + // 获取小部件背景资源ID + @Override + protected int getBgResourceId(int bgId) { + // 调用ResourceParser获取4x小部件的背景资源ID + return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); + } + + // 获取小部件类型 + @Override + protected int getWidgetType() { + // 返回4x小部件的类型 + return Notes.TYPE_WIDGET_4X; + } +}