diff --git a/doc/实践模板-开源软件的质量分析报告文档 (1).docx b/doc/实践模板-开源软件的质量分析报告文档 (1).docx new file mode 100644 index 0000000..0b153f4 Binary files /dev/null and b/doc/实践模板-开源软件的质量分析报告文档 (1).docx differ diff --git a/doc/实践模板-开源软件的质量分析报告文档.docx b/doc/实践模板-开源软件的质量分析报告文档.docx deleted file mode 100644 index 52a92e0..0000000 Binary files a/doc/实践模板-开源软件的质量分析报告文档.docx and /dev/null differ diff --git a/src/Contact.java b/src/Contact.java new file mode 100644 index 0000000..a1c23bb --- /dev/null +++ b/src/Contact.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.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 { + private static HashMap sContactCache; // 联系人缓存 + private static final String TAG = "Contact"; // 日志标签 + + // 呼叫者ID选择条件 + 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); // 从缓存中获取联系人 + } + + // 替换选择条件中的“+”符号 + 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 + } + } +} \ No newline at end of file diff --git a/src/Notes.java b/src/Notes.java new file mode 100644 index 0000000..c112c04 --- /dev/null +++ b/src/Notes.java @@ -0,0 +1,285 @@ +/* + * 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.net.Uri; // 导入URI类 + +// 笔记类 +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为系统文件夹的标识符 + * {@link Notes#ID_ROOT_FOLDER} 是默认文件夹 + * {@link Notes#ID_TEMPARAY_FOLDER} 是用于不属于任何文件夹的笔记 + * {@link Notes#ID_CALL_RECORD_FOLDER} 用于存储通话记录 + */ + public static final int ID_ROOT_FOLDER = 0; // 根文件夹ID + public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹ID + public static final int ID_CALL_RECORD_FOLDER = -2; // 通话记录夹ID + public static final int ID_TRASH_FOLER = -3; // 垃圾文件夹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; // 2x小部件类型 + public static final int TYPE_WIDGET_4X = 1; // 4x小部件类型 + + // 数据常量类 + public static class DataConstants { + public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 笔记类型 + public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; // 通话记录类型 + } + + /** + * 查询所有笔记和文件夹的URI + */ + public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); // 笔记URI + + /** + * 查询数据的URI + */ + public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); // 数据URI + + // 笔记列接口 + public interface NoteColumns { + /** + * 行的唯一ID + *

类型: INTEGER (long)

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

类型: INTEGER (long)

+ */ + public static final String PARENT_ID = "parent_id"; // 父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"; // 小部件ID列 + + /** + * 笔记的小部件类型 + *

类型: INTEGER (long)

+ */ + public static final String WIDGET_TYPE = "widget_type"; // 小部件类型列 + + /** + * 笔记背景颜色的ID + *

类型: INTEGER (long)

+ */ + public static final String BG_COLOR_ID = "bg_color_id"; // 背景颜色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"; // 同步ID列 + + /** + * 标记本地是否已修改 + *

类型: INTEGER

+ */ + public static final String LOCAL_MODIFIED = "local_modified"; // 本地修改标记列 + + /** + * 移动到临时文件夹之前的原父ID + *

类型: INTEGER

+ */ + public static final String ORIGIN_PARENT_ID = "origin_parent_id"; // 原父ID列 + + /** + * gtask ID + *

类型: TEXT

+ */ + public static final String GTASK_ID = "gtask_id"; // gtask ID列 + + /** + * 版本号 + *

类型: INTEGER (long)

+ */ + public static final String VERSION = "version"; // 版本列 + } + + // 数据列接口 + public interface DataColumns { + /** + * 行的唯一ID + *

类型: INTEGER (long)

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

类型: Text

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

类型: INTEGER (long)

+ */ + public static final String NOTE_ID = "note_id"; // 笔记ID列 + + /** + * 笔记或文件夹的创建日期 + *

类型: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; // 创建日期列 + + /** + * 最新修改日期 + *

类型: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; // 修改日期列 + + /** + * 数据的内容 + *

类型: TEXT

+ */ + public static final String CONTENT = "content"; // 内容列 + + /** + * 通用数据列,含义是 {@link #MIMETYPE} 特定,使用于 + * 整数数据类型 + *

类型: INTEGER

+ */ + public static final String DATA1 = "data1"; // 数据列1 + + /** + * 通用数据列,含义是 {@link #MIMETYPE} 特定,使用于 + * 整数数据类型 + *

类型: INTEGER

+ */ + public static final String DATA2 = "data2"; // 数据列2 + + /** + * 通用数据列,含义是 {@link #MIMETYPE} 特定,使用于 + * 文本数据类型 + *

类型: TEXT

+ */ + public static final String DATA3 = "data3"; // 数据列3 + + /** + * 通用数据列,含义是 {@link #MIMETYPE} 特定,使用于 + * 文本数据类型 + *

类型: TEXT

+ */ + public static final String DATA4 = "data4"; // 数据列4 + + /** + * 通用数据列,含义是 {@link #MIMETYPE} 特定,使用于 + * 文本数据类型 + *

类型: TEXT

+ */ + public static final String DATA5 = "data5"; // 数据列5 + } + + // 文本笔记类 + public static final class TextNote implements DataColumns { + /** + * 指示文本是否处于检查列表模式 + *

类型: Integer 1: 检查列表模式 0: 正常模式

+ */ + public static final String MODE = DATA1; // 模式列 + + public static final int MODE_CHECK_LIST = 1; // 检查列表模式标记 + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; // 内容类型 + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; // 项目内容类型 + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); // 文本笔记URI + } + + // 通话记录类 + public static final class CallNote implements DataColumns { + /** + * 此记录的通话日期 + *

类型: INTEGER (long)

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

类型: TEXT

+ */ + public static final String PHONE_NUMBER = DATA3; // 电话号码列 + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; // 内容类型 + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; // 项目内容类型 + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); // 通话记录URI + } +} \ No newline at end of file diff --git a/src/NotesDatabaseHelper.java b/src/NotesDatabaseHelper.java new file mode 100644 index 0000000..ef8f1d4 --- /dev/null +++ b/src/NotesDatabaseHelper.java @@ -0,0 +1,348 @@ +/* + * 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; // 导入SQLite数据库类 +import android.database.sqlite.SQLiteOpenHelper; // 导入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 + "(" + + 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 语句 + private static final String CREATE_DATA_TABLE_SQL = + "CREATE TABLE " + TABLE.DATA + "(" + + DataColumns.ID + " INTEGER PRIMARY KEY," + + DataColumns.MIME_TYPE + " TEXT NOT NULL," + + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA1 + " INTEGER," + + DataColumns.DATA2 + " INTEGER," + + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + + ")"; + + // 创建数据表的 NOTE_ID 索引的 SQL 语句 + private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = + "CREATE INDEX IF NOT EXISTS note_id_index ON " + + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; + + // 增加文件夹笔记计数的触发器 SQL 语句 + 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"; + + // 减少文件夹笔记计数的触发器 SQL 语句 + 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"; + + // 插入新笔记时增加文件夹笔记计数的触发器 SQL 语句 + 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"; + + // 从文件夹中删除笔记时减少文件夹笔记计数的触发器 SQL 语句 + 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"; + + // 插入数据时更新笔记内容的触发器 SQL 语句 + 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"; + + // 更新数据时更新笔记内容的触发器 SQL 语句 + 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"; + + // 删除数据时更新笔记内容的触发器 SQL 语句 + 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"; + + // 删除已删除笔记的数据的触发器 SQL 语句 + 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"; + + // 删除已删除文件夹中的笔记的触发器 SQL 语句 + 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"; + + // 移动到回收站文件夹的笔记的触发器 SQL 语句 + 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"; + + // 构造函数 + 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); // 插入到笔记表 + + // 默认根文件夹 + values.clear(); // 清空内容值对象 + values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 系统类型 + db.insert(TABLE.NOTE, null, values); // 插入到笔记表 + + // 临时文件夹用于移动笔记 + values.clear(); // 清空内容值对象 + values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 系统类型 + db.insert(TABLE.NOTE, null, values); // 插入到笔记表 + + // 创建回收站文件夹 + values.clear(); // 清空内容值对象 + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 系统类型 + db.insert(TABLE.NOTE, null, values); // 插入到笔记表 + } + + // 创建数据表 + 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) { + boolean reCreateTriggers = false; // 触发器是否需要重建 + boolean skipV2 = false; // 是否跳过 V2 升级 + + if (oldVersion == 1) { + upgradeToV2(db); // 升级到 V2 + skipV2 = true; // 标记为跳过 V2 升级 + oldVersion++; // 增加版本号 + } + + if (oldVersion == 2 && !skipV2) { + upgradeToV3(db); // 升级到 V3 + reCreateTriggers = true; // 标记为需要重建触发器 + oldVersion++; // 增加版本号 + } + + if (oldVersion == 3) { + upgradeToV4(db); // 升级到 V4 + oldVersion++; // 增加版本号 + } + + if (reCreateTriggers) { + reCreateNoteTableTriggers(db); // 重新创建笔记表触发器 + reCreateDataTableTriggers(db); // 重新创建数据表触发器 + } + + if (oldVersion != newVersion) { + throw new IllegalStateException("Upgrade notes database to version " + newVersion + + " fails"); // 抛出异常 + } + } + + // 升级到 V2 + private void upgradeToV2(SQLiteDatabase db) { + db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); // 删除笔记表 + db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); // 删除数据表 + createNoteTable(db); // 创建笔记表 + createDataTable(db); // 创建数据表 + } + + // 升级到 V3 + private void upgradeToV3(SQLiteDatabase db) { + // 删除未使用的触发器 + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); + // 添加 gtask id 列 + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID + + " TEXT NOT NULL DEFAULT ''"); + // 添加回收站系统文件夹 + ContentValues values = new ContentValues(); // 创建内容值对象 + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); // 设置文件夹 ID + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 系统类型 + db.insert(TABLE.NOTE, null, values); // 插入到笔记表 + } + + // 升级到 V4 + 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/NotesPreferenceActivity.java b/src/NotesPreferenceActivity.java new file mode 100644 index 0000000..3fca75a --- /dev/null +++ b/src/NotesPreferenceActivity.java @@ -0,0 +1,384 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.accounts.Account; // 导入账户类 +import android.accounts.AccountManager; // 导入账户管理类 +import android.app.ActionBar; // 导入动作栏类 +import android.app.AlertDialog; // 导入警告对话框类 +import android.content.BroadcastReceiver; // 导入广播接收器类 +import android.content.ContentValues; // 导入内容值类 +import android.content.Context; // 导入上下文类 +import android.content.DialogInterface; // 导入对话框接口类 +import android.content.Intent; // 导入意图类 +import android.content.IntentFilter; // 导入意图过滤器类 +import android.content.SharedPreferences; // 导入共享偏好类 +import android.os.Bundle; // 导入捆绑类 +import android.preference.Preference; // 导入偏好类 +import android.preference.Preference.OnPreferenceClickListener; // 导入偏好点击监听器 +import android.preference.PreferenceActivity; // 导入偏好活动类 +import android.preference.PreferenceCategory; // 导入偏好类别类 +import android.text.TextUtils; // 导入文本工具类 +import android.text.format.DateFormat; // 导入日期格式化类 +import android.view.LayoutInflater; // 导入布局填充器类 +import android.view.Menu; // 导入菜单类 +import android.view.MenuItem; // 导入菜单项类 +import android.view.View; // 导入视图类 +import android.widget.Button; // 导入按钮类 +import android.widget.TextView; // 导入文本视图类 +import android.widget.Toast; // 导入吐司类 + +import net.micode.notes.R; // 导入资源类 +import net.micode.notes.data.Notes; // 导入笔记数据类 +import net.micode.notes.data.Notes.NoteColumns; // 导入笔记列类 +import net.micode.notes.gtask.remote.GTaskSyncService; // 导入GTask同步服务类 + +public class NotesPreferenceActivity extends PreferenceActivity { + public static final String PREFERENCE_NAME = "notes_preferences"; // 偏好名称 + + public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; // 同步账户名称偏好键 + + public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; // 最后同步时间偏好键 + + public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; // 背景颜色偏好键 + + private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; // 同步账户偏好键 + + private static final String AUTHORITIES_FILTER_KEY = "authorities"; // 权限过滤键 + + private PreferenceCategory mAccountCategory; // 账户类别 + + private GTaskReceiver mReceiver; // GTask接收器 + + private Account[] mOriAccounts; // 原始账户数组 + + private boolean mHasAddedAccount; // 是否添加账户标志 + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + // 使用应用图标进行导航 + getActionBar().setDisplayHomeAsUpEnabled(true); + + addPreferencesFromResource(R.xml.preferences); // 从资源加载偏好设置 + mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); // 查找账户类别 + mReceiver = new GTaskReceiver(); // 初始化GTask接收器 + IntentFilter filter = new IntentFilter(); // 创建意图过滤器 + filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); // 添加GTask服务广播名称 + registerReceiver(mReceiver, filter); // 注册接收器 + + mOriAccounts = null; // 初始化原始账户 + View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); // 填充设置头部视图 + getListView().addHeaderView(header, null, true); // 添加头部视图 + } + + @Override + protected void onResume() { + super.onResume(); + + // 如果用户添加了新账户,则需要自动设置同步账户 + if (mHasAddedAccount) { + Account[] accounts = getGoogleAccounts(); // 获取Google账户 + if (mOriAccounts != null && accounts.length > mOriAccounts.length) { + for (Account accountNew : accounts) { + boolean found = false; // 标志账户是否找到 + for (Account accountOld : mOriAccounts) { + if (TextUtils.equals(accountOld.name, accountNew.name)) { + found = true; // 找到账户 + break; + } + } + if (!found) { + setSyncAccount(accountNew.name); // 设置同步账户 + break; // 退出循环 + } + } + } + } + + refreshUI(); // 刷新用户界面 + } + + @Override + protected void onDestroy() { + if (mReceiver != null) { + unregisterReceiver(mReceiver); // 注销接收器 + } + super.onDestroy(); + } + + private void loadAccountPreference() { + mAccountCategory.removeAll(); // 移除所有账户偏好设置 + + Preference accountPref = new Preference(this); // 创建账户偏好设置 + final String defaultAccount = getSyncAccountName(this); // 获取同步账户名称 + accountPref.setTitle(getString(R.string.preferences_account_title)); // 设置标题 + accountPref.setSummary(getString(R.string.preferences_account_summary)); // 设置摘要 + accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { // 设置点击监听器 + public boolean onPreferenceClick(Preference preference) { + if (!GTaskSyncService.isSyncing()) { // 如果没有正在同步 + if (TextUtils.isEmpty(defaultAccount)) { + // 第一次设置账户 + showSelectAccountAlertDialog(); // 显示选择账户对话框 + } else { + // 如果账户已经设置,需要提醒用户风险 + showChangeAccountConfirmAlertDialog(); // 显示更改账户确认对话框 + } + } else { + Toast.makeText(NotesPreferenceActivity.this, + R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) // 显示不能更改账户的提示 + .show(); + } + return true; // 返回true表示事件已处理 + } + }); + + mAccountCategory.addPreference(accountPref); // 添加账户偏好设置 + } + + private void loadSyncButton() { + Button syncButton = (Button) findViewById(R.id.preference_sync_button); // 获取同步按钮 + TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); // 获取最后同步时间视图 + + // 设置按钮状态 + if (GTaskSyncService.isSyncing()) { + syncButton.setText(getString(R.string.preferences_button_sync_cancel)); // 设置按钮文本为取消同步 + syncButton.setOnClickListener(new View.OnClickListener() { // 设置点击监听器 + public void onClick(View v) { + GTaskSyncService.cancelSync(NotesPreferenceActivity.this); // 取消同步 + } + }); + } else { + syncButton.setText(getString(R.string.preferences_button_sync_immediately)); // 设置按钮文本为立即同步 + syncButton.setOnClickListener(new View.OnClickListener() { // 设置点击监听器 + public void onClick(View v) { + GTaskSyncService.startSync(NotesPreferenceActivity.this); // 开始同步 + } + }); + } + syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); // 设置按钮是否可用 + + // 设置最后同步时间 + if (GTaskSyncService.isSyncing()) { + lastSyncTimeView.setText(GTaskSyncService.getProgressString()); // 显示同步状态 + lastSyncTimeView.setVisibility(View.VISIBLE); // 显示最后同步时间视图 + } else { + long lastSyncTime = getLastSyncTime(this); // 获取最后同步时间 + if (lastSyncTime != 0) { + lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, + DateFormat.format(getString(R.string.preferences_last_sync_time_format), + lastSyncTime))); // 显示格式化的最后同步时间 + lastSyncTimeView.setVisibility(View.VISIBLE); // 显示最后同步时间视图 + } else { + lastSyncTimeView.setVisibility(View.GONE); // 隐藏最后同步时间视图 + } + } + } + + private void refreshUI() { + loadAccountPreference(); // 加载账户偏好设置 + loadSyncButton(); // 加载同步按钮 + } + + private void showSelectAccountAlertDialog() { + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // 创建对话框构建器 + + View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); // 填充对话框标题视图 + TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); // 获取标题文本视图 + titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); // 设置标题文本 + TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); // 获取副标题文本视图 + subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); // 设置副标题文本 + + dialogBuilder.setCustomTitle(titleView); // 设置自定义标题 + dialogBuilder.setPositiveButton(null, null); // 设置正面按钮 + + Account[] accounts = getGoogleAccounts(); // 获取Google账户 + String defAccount = getSyncAccountName(this); // 获取同步账户名称 + + mOriAccounts = accounts; // 保存原始账户 + mHasAddedAccount = false; // 重置添加账户标志 + + if (accounts.length > 0) { + CharSequence[] items = new CharSequence[accounts.length]; // 创建账户名称数组 + final CharSequence[] itemMapping = items; // 保存账户名称映射 + int checkedItem = -1; // 选中项索引 + int index = 0; // 数组索引 + for (Account account : accounts) { + if (TextUtils.equals(account.name, defAccount)) { + checkedItem = index; // 如果是默认账户,设置checkedItem + } + items[index++] = account.name; // 添加账户名称 + } + dialogBuilder.setSingleChoiceItems(items, checkedItem, // 设置单选项 + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + setSyncAccount(itemMapping[which].toString()); // 设置同步账户 + dialog.dismiss(); // 关闭对话框 + refreshUI(); // 刷新用户界面 + } + }); + } + + View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); // 填充添加账户视图 + dialogBuilder.setView(addAccountView); // 设置对话框视图 + + final AlertDialog dialog = dialogBuilder.show(); // 显示对话框 + addAccountView.setOnClickListener(new View.OnClickListener() { // 设置点击监听器 + public void onClick(View v) { + mHasAddedAccount = true; // 设置添加账户标志 + Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); // 创建添加账户意图 + intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { + "gmail-ls" // 添加权限过滤 + }); + startActivityForResult(intent, -1); // 启动添加账户活动 + dialog.dismiss(); // 关闭对话框 + } + }); + } + + private void showChangeAccountConfirmAlertDialog() { + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // 创建对话框构建器 + + View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); // 填充对话框标题视图 + TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); // 获取标题文本视图 + titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, + getSyncAccountName(this))); // 设置标题文本 + TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); // 获取副标题文本视图 + subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); // 设置副标题文本 + dialogBuilder.setCustomTitle(titleView); // 设置自定义标题 + + CharSequence[] menuItemArray = new CharSequence[] { + getString(R.string.preferences_menu_change_account), // 更改账户 + getString(R.string.preferences_menu_remove_account), // 移除账户 + getString(R.string.preferences_menu_cancel) // 取消 + }; + dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { // 设置对话框项 + public void onClick(DialogInterface dialog, int which) { + if (which == 0) { + showSelectAccountAlertDialog(); // 显示选择账户对话框 + } else if (which == 1) { + removeSyncAccount(); // 移除同步账户 + refreshUI(); // 刷新用户界面 + } + } + }); + dialogBuilder.show(); // 显示对话框 + } + + private Account[] getGoogleAccounts() { + AccountManager accountManager = AccountManager.get(this); // 获取账户管理器 + return accountManager.getAccountsByType("com.google"); // 返回Google账户 + } + + private void setSyncAccount(String account) { + if (!getSyncAccountName(this).equals(account)) { + SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); // 获取共享偏好设置 + SharedPreferences.Editor editor = settings.edit(); // 创建编辑器 + if (account != null) { + editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); // 设置同步账户名称 + } else { + editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); // 清空同步账户名称 + } + editor.commit(); // 提交更改 + + // 清除最后同步时间 + setLastSyncTime(this, 0); + + // 清除本地GTask相关信息 + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); // 创建内容值 + values.put(NoteColumns.GTASK_ID, ""); // 清空GTASK_ID + values.put(NoteColumns.SYNC_ID, 0); // 清空SYNC_ID + getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); // 更新笔记内容 + } + }).start(); + + Toast.makeText(NotesPreferenceActivity.this, + getString(R.string.preferences_toast_success_set_accout, account), // 显示设置成功的提示 + Toast.LENGTH_SHORT).show(); + } + } + + private void removeSyncAccount() { + SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); // 获取共享偏好设置 + SharedPreferences.Editor editor = settings.edit(); // 创建编辑器 + if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { + editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); // 移除同步账户名称 + } + if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { + editor.remove(PREFERENCE_LAST_SYNC_TIME); // 移除最后同步时间 + } + editor.commit(); // 提交更改 + + // 清除本地GTask相关信息 + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); // 创建内容值 + values.put(NoteColumns.GTASK_ID, ""); // 清空GTASK_ID + values.put(NoteColumns.SYNC_ID, 0); // 清空SYNC_ID + getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); // 更新笔记内容 + } + }).start(); + } + + public static String getSyncAccountName(Context context) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); // 获取共享偏好设置 + return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); // 返回同步账户名称 + } + + public static void setLastSyncTime(Context context, long time) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); // 获取共享偏好设置 + SharedPreferences.Editor editor = settings.edit(); // 创建编辑器 + editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); // 设置最后同步时间 + editor.commit(); // 提交更改 + } + + public static long getLastSyncTime(Context context) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); // 获取共享偏好设置 + return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); // 返回最后同步时间 + } + + private class GTaskReceiver extends BroadcastReceiver { + + @Override + public void onReceive(Context context, Intent intent) { + refreshUI(); // 刷新用户界面 + if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { + TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); // 获取同步状态视图 + syncStatus.setText(intent + .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); // 显示同步进度信息 + } + } + } + + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + Intent intent = new Intent(this, NotesListActivity.class); // 创建返回笔记列表的意图 + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 清除顶部活动 + startActivity(intent); // 启动活动 + return true; // 返回true表示事件已处理 + default: + return false; // 返回false表示未处理事件 + } + } +} \ No newline at end of file diff --git a/src/NotesProvider.java b/src/NotesProvider.java new file mode 100644 index 0000000..c84269a --- /dev/null +++ b/src/NotesProvider.java @@ -0,0 +1,303 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.data; // 包声明 + +import android.app.SearchManager; // 导入搜索管理器 +import android.content.ContentProvider; // 导入内容提供者 +import android.content.ContentUris; // 导入内容URI +import android.content.ContentValues; // 导入内容值 +import android.content.Intent; // 导入意图 +import android.content.UriMatcher; // 导入URI匹配器 +import android.database.Cursor; // 导入游标 +import android.database.sqlite.SQLiteDatabase; // 导入SQLite数据库 +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; // 导入数据库表 + +// 笔记提供者类 +public class NotesProvider extends ContentProvider { + private static final UriMatcher mMatcher; // URI匹配器 + + private NotesDatabaseHelper mHelper; // 数据库助手 + + private static final String TAG = "NotesProvider"; // 日志标签 + + // URI常量 + private static final int URI_NOTE = 1; // 笔记URI + private static final int URI_NOTE_ITEM = 2; // 单个笔记URI + private static final int URI_DATA = 3; // 数据URI + private static final int URI_DATA_ITEM = 4; // 单个数据URI + + private static final int URI_SEARCH = 5; // 搜索URI + private static final int URI_SEARCH_SUGGEST = 6; // 搜索建议URI + + // 静态代码块,初始化URI匹配器 + static { + mMatcher = new UriMatcher(UriMatcher.NO_MATCH); // 创建URI匹配器 + mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); // 添加笔记URI + mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); // 添加单个笔记URI + mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); // 添加数据URI + mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); // 添加单个数据URI + mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); // 添加搜索URI + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); // 添加搜索建议URI + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); // 添加搜索建议URI + } + + // 搜索投影常量 + private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," + + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," + + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," + + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; // 搜索结果投影 + + // 笔记片段搜索查询 + 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 + public boolean onCreate() { + mHelper = NotesDatabaseHelper.getInstance(getContext()); // 获取数据库助手实例 + return true; // 返回创建成功 + } + + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + String sortOrder) { + Cursor c = null; // 游标 + SQLiteDatabase db = mHelper.getReadableDatabase(); // 获取可读数据库 + String id = null; // ID + switch (mMatcher.match(uri)) { // 根据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); // 获取笔记ID + 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); // 获取数据ID + 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) { + searchString = uri.getPathSegments().get(1); // 获取搜索字符串 + } + } else { + searchString = uri.getQueryParameter("pattern"); // 获取查询参数 + } + + if (TextUtils.isEmpty(searchString)) { + return null; // 如果搜索字符串为空,返回null + } + + try { + searchString = String.format("%%%s%%", searchString); // 格式化搜索字符串 + c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, + new String[] { searchString }); // 执行原始查询 + } catch (IllegalStateException ex) { + Log.e(TAG, "got exception: " + ex.toString()); // 处理异常 + } + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); // 处理未知URI + } + if (c != null) { + c.setNotificationUri(getContext().getContentResolver(), uri); // 设置通知URI + } + return c; // 返回游标 + } + + @Override + public Uri insert(Uri uri, ContentValues values) { + SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库 + long dataId = 0, noteId = 0, insertedId = 0; // 初始化ID + switch (mMatcher.match(uri)) { // 根据URI匹配 + case URI_NOTE: + insertedId = noteId = db.insert(TABLE.NOTE, null, values); // 插入笔记 + break; + case URI_DATA: + if (values.containsKey(DataColumns.NOTE_ID)) { + noteId = values.getAsLong(DataColumns.NOTE_ID); // 获取笔记ID + } else { + Log.d(TAG, "Wrong data format without note id:" + values.toString()); // 处理错误 + } + insertedId = dataId = db.insert(TABLE.DATA, null, values); // 插入数据 + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); // 处理未知URI + } + // 通知笔记URI + if (noteId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); // 通知更改 + } + + // 通知数据URI + if (dataId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); // 通知更改 + } + + return ContentUris.withAppendedId(uri, insertedId); // 返回插入的URI + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + int count = 0; // 删除计数 + String id = null; // ID + SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库 + boolean deleteData = false; // 是否删除数据 + switch (mMatcher.match(uri)) { // 根据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 + // ID小于0的系统文件夹不允许删除 + long noteId = Long.valueOf(id); // 转换ID + if (noteId <= 0) { + break; // 如果ID无效,跳过 + } + 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); // 获取数据ID + count = db.delete(TABLE.DATA, + DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); // 删除单个数据 + deleteData = true; // 标记为删除数据 + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); // 处理未知URI + } + if (count > 0) { + if (deleteData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); // 通知笔记URI更改 + } + getContext().getContentResolver().notifyChange(uri, null); // 通知URI更改 + } + return count; // 返回删除计数 + } + + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + int count = 0; // 更新计数 + String id = null; // ID + SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库 + boolean updateData = false; // 是否更新数据 + switch (mMatcher.match(uri)) { // 根据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); // 获取笔记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; // 标记为更新数据 + break; + case URI_DATA_ITEM: + id = uri.getPathSegments().get(1); // 获取数据ID + count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); // 更新单个数据 + updateData = true; // 标记为更新数据 + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); // 处理未知URI + } + + if (count > 0) { + if (updateData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); // 通知笔记URI更改 + } + getContext().getContentResolver().notifyChange(uri, null); // 通知URI更改 + } + return count; // 返回更新计数 + } + + // 解析选择条件 + private String parseSelection(String selection) { + return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); // 返回解析后的选择 + } + + // 增加笔记版本 + private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { + StringBuilder sql = new StringBuilder(120); // SQL构建器 + sql.append("UPDATE "); // 更新语句 + sql.append(TABLE.NOTE); // 指定表 + sql.append(" SET "); + sql.append(NoteColumns.VERSION); + sql.append("=" + NoteColumns.VERSION + "+1 "); // 增加版本 + + if (id > 0 || !TextUtils.isEmpty(selection)) { + sql.append(" WHERE "); // 添加WHERE条件 + } + if (id > 0) { + sql.append(NoteColumns.ID + "=" + String.valueOf(id)); // 指定ID + } + if (!TextUtils.isEmpty(selection)) { + String selectString = id > 0 ? parseSelection(selection) : selection; // 选择条件 + for (String args : selectionArgs) { + selectString = selectString.replaceFirst("\\?", args); // 替换参数 + } + sql.append(selectString); // 添加选择条件 + } + + mHelper.getWritableDatabase().execSQL(sql.toString()); // 执行SQL语句 + } + + @Override + public String getType(Uri uri) { + // TODO Auto-generated method stub + return null; // 返回null + } +} \ No newline at end of file