diff --git a/doc/开源软件的质量分析报告文档-李明阳,刘智龙组(2).docx b/doc/开源软件的质量分析报告文档-李明阳,刘智龙组(2).docx new file mode 100644 index 0000000..83e2bd4 Binary files /dev/null and b/doc/开源软件的质量分析报告文档-李明阳,刘智龙组(2).docx differ diff --git a/doc/文档模板-开源软件泛读、标注和维护报告文档(5).docx b/doc/文档模板-开源软件泛读、标注和维护报告文档(5).docx new file mode 100644 index 0000000..ff88e08 Binary files /dev/null and b/doc/文档模板-开源软件泛读、标注和维护报告文档(5).docx differ diff --git a/src/MainActivity.java b/src/MainActivity.java new file mode 100644 index 0000000..8091753 --- /dev/null +++ b/src/MainActivity.java @@ -0,0 +1,24 @@ +package net.micode.notes; + +import android.os.Bundle; + +import androidx.activity.EdgeToEdge; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.graphics.Insets; +import androidx.core.view.ViewCompat; +import androidx.core.view.WindowInsetsCompat; + +public class MainActivity extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + EdgeToEdge.enable(this); + setContentView(R.layout.activity_main); + ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { + Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); + v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); + return insets; + }); + } +} \ No newline at end of file diff --git a/src/data/Contact.java b/src/data/Contact.java deleted file mode 100644 index dc2478b..0000000 --- a/src/data/Contact.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * 版权所有信息,MiCode开源社区 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * 根据Apache License 2.0许可证授权 - * 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 - * Apache许可证2.0版本的URL - * - * 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; -// 定义包名:net.micode.notes.data,表示这是一个数据访问相关的类 - -import android.content.Context; -// 导入Android上下文类,用于访问应用资源和内容解析器 - -import android.database.Cursor; -// 导入数据库游标类,用于遍历查询结果 - -import android.provider.ContactsContract.CommonDataKinds.Phone; -// 导入联系人电话相关常量 - -import android.provider.ContactsContract.Data; -// 导入联系人数据相关常量 - -import android.telephony.PhoneNumberUtils; -// 导入电话号码工具类,用于电话号码处理 - -import android.util.Log; -// 导入Android日志工具类 - -import java.util.HashMap; -// 导入HashMap类,用于实现缓存功能 - -public class Contact { -// 定义公共类Contact,用于处理联系人相关操作 - - private static HashMap sContactCache; - // 声明静态HashMap,用于缓存电话号码到联系人姓名的映射 - // 键:电话号码,值:联系人姓名 - - private static final String TAG = "Contact"; - // 定义日志标签常量,用于日志输出时标识来源 - - 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 = '+')"; - // 构建SQL查询语句,用于根据电话号码查找联系人 - // PHONE_NUMBERS_EQUAL:电话号码相等比较函数 - // Phone.NUMBER:电话号码列 - // Data.MIMETYPE:数据类型列 - // Phone.CONTENT_ITEM_TYPE:电话数据类型 - // Data.RAW_CONTACT_ID:原始联系人ID - // phone_lookup:电话查询优化表 - // min_match:最小匹配位数(+是占位符) - - public static String getContact(Context context, String phoneNumber) { - // 公共静态方法:根据电话号码获取联系人姓名 - // 参数:context - Android上下文对象 - // phoneNumber - 要查询的电话号码 - // 返回值:联系人姓名,如果找不到返回null - - if(sContactCache == null) { - // 检查缓存是否已初始化 - sContactCache = new HashMap(); - // 如果缓存为null,创建一个新的HashMap实例 - } - - if(sContactCache.containsKey(phoneNumber)) { - // 检查缓存中是否已存在该电话号码 - return sContactCache.get(phoneNumber); - // 如果缓存中存在,直接从缓存中返回联系人姓名 - } - - String selection = CALLER_ID_SELECTION.replace("+", - PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); - // 构建完整的查询条件 - // 使用PhoneNumberUtils.toCallerIDMinMatch获取电话号码的最小匹配位数 - // 替换查询语句中的'+'占位符为实际的最小匹配位数 - - Cursor cursor = context.getContentResolver().query( - // 通过内容解析器执行查询,获取游标对象 - Data.CONTENT_URI, - // 查询的URI:联系人数据的内容URI - new String [] { Phone.DISPLAY_NAME }, - // 要查询的列:只查询显示姓名列 - selection, - // 查询条件:上面构建的selection字符串 - new String[] { phoneNumber }, - // 查询参数:电话号码作为参数传入 - null); - // 排序参数:null表示不排序 - - if (cursor != null && cursor.moveToFirst()) { - // 检查游标不为null且有数据(至少能移动到第一行) - try { - String name = cursor.getString(0); - // 从游标的第一列(索引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(); - // finally块确保无论是否发生异常都关闭游标 - // 避免资源泄漏 - } - } else { - // 游标为null或没有数据的情况 - Log.d(TAG, "No contact matched with number:" + phoneNumber); - // 记录调试日志:没有找到匹配的联系人 - return null; - // 返回null表示未找到联系人 - } - } -} diff --git a/src/data/Notes.java b/src/data/Notes.java deleted file mode 100644 index 6b9d880..0000000 --- a/src/data/Notes.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.data; -// 数据相关类包 - -import android.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; - // 笔记类型:系统文件夹 - - // 系统文件夹标识符说明 - - 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小部件 - - 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"); - // 详细数据查询URI - - 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"; - // 版本号 - } - - 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 - } - - 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"; - // 内容类型 - - 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 { - // 通话笔记类 - - 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"; - // 内容类型 - - 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/data/NotesDatabaseHelper.java b/src/data/NotesDatabaseHelper.java deleted file mode 100644 index 4df3b1e..0000000 --- a/src/data/NotesDatabaseHelper.java +++ /dev/null @@ -1,405 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import android.content.ContentValues; -// 导入ContentValues类,用于存储键值对数据 - -import android.content.Context; -// 导入Context类,获取应用上下文 - -import android.database.sqlite.SQLiteDatabase; -// 导入SQLiteDatabase类,数据库操作 - -import android.database.sqlite.SQLiteOpenHelper; -// 导入SQLiteOpenHelper类,数据库辅助类 - -import android.util.Log; -// 导入Log类,日志输出 - -import net.micode.notes.data.Notes.DataColumns; -// 导入DataColumns接口 - -import net.micode.notes.data.Notes.DataConstants; -// 导入DataConstants类 - -import net.micode.notes.data.Notes.NoteColumns; -// 导入NoteColumns接口 - - -public class NotesDatabaseHelper extends SQLiteOpenHelper { -// 数据库辅助类,继承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; - // 单例实例 - - private static final String CREATE_NOTE_TABLE_SQL = - // 创建笔记表SQL语句 - "CREATE TABLE " + TABLE.NOTE + "(" + - NoteColumns.ID + " INTEGER PRIMARY KEY," + // 主键ID - NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 父ID - NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + // 提醒日期 - NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + // 背景色ID - 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," + // 小部件ID - NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + // 小部件类型 - NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + // 同步ID - NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + // 本地修改标记 - NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 原始父ID - NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + // Google任务ID - NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 版本号 - ")"; - - private static final String CREATE_DATA_TABLE_SQL = - // 创建数据表SQL语句 - "CREATE TABLE " + TABLE.DATA + "(" + - DataColumns.ID + " INTEGER PRIMARY KEY," + // 主键ID - DataColumns.MIME_TYPE + " TEXT NOT NULL," + // MIME类型 - DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联笔记ID - 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," + // 数据列1 - DataColumns.DATA2 + " INTEGER," + // 数据列2 - DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + // 数据列3 - DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + // 数据列4 - DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + // 数据列5 - ")"; - - private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = - // 创建数据表索引SQL - "CREATE INDEX IF NOT EXISTS note_id_index ON " + - TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; - - // 笔记移动时增加文件夹计数触发器 - private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = - "CREATE TRIGGER increase_folder_count_on_update "+ - " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + - " END"; - - // 笔记移出时减少文件夹计数触发器 - private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = - "CREATE TRIGGER decrease_folder_count_on_update " + - " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + - " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + - " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + - " END"; - - // 插入笔记时增加文件夹计数触发器 - private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = - "CREATE TRIGGER increase_folder_count_on_insert " + - " AFTER INSERT ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + - " END"; - - // 删除笔记时减少文件夹计数触发器 - private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = - "CREATE TRIGGER decrease_folder_count_on_delete " + - " AFTER DELETE ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + - " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + - " AND " + NoteColumns.NOTES_COUNT + ">0;" + - " END"; - - // 插入数据时更新笔记内容触发器 - private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = - "CREATE TRIGGER update_note_content_on_insert " + - " AFTER INSERT ON " + TABLE.DATA + - " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + - " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + - " END"; - - // 更新数据时更新笔记内容触发器 - private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = - "CREATE TRIGGER update_note_content_on_update " + - " AFTER UPDATE ON " + TABLE.DATA + - " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + - " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + - " END"; - - // 删除数据时更新笔记内容触发器 - private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = - "CREATE TRIGGER update_note_content_on_delete " + - " AFTER delete ON " + TABLE.DATA + - " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.SNIPPET + "=''" + - " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + - " END"; - - // 删除笔记时删除关联数据触发器 - private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = - "CREATE TRIGGER delete_data_on_delete " + - " AFTER DELETE ON " + TABLE.NOTE + - " BEGIN" + - " DELETE FROM " + TABLE.DATA + - " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + - " END"; - - // 删除文件夹时删除子笔记触发器 - private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = - "CREATE TRIGGER folder_delete_notes_on_delete " + - " AFTER DELETE ON " + TABLE.NOTE + - " BEGIN" + - " DELETE FROM " + TABLE.NOTE + - " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + - " END"; - - // 文件夹移入垃圾箱时移动子笔记触发器 - private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = - "CREATE TRIGGER folder_move_notes_on_trash " + - " AFTER UPDATE ON " + TABLE.NOTE + - " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + - " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + - " END"; - - 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) { - // 从版本1升级 - upgradeToV2(db); - // 升级到V2 - skipV2 = true; // 包含V2到V3的升级 - oldVersion++; - } - - if (oldVersion == 2 && !skipV2) { - // 从版本2升级 - upgradeToV3(db); - // 升级到V3 - reCreateTriggers = true; - // 需要重建触发器 - oldVersion++; - } - - if (oldVersion == 3) { - // 从版本3升级 - upgradeToV4(db); - // 升级到V4 - oldVersion++; - } - - if (reCreateTriggers) { - // 如果需要重建触发器 - reCreateNoteTableTriggers(db); - // 重建笔记表触发器 - reCreateDataTableTriggers(db); - // 重建数据表触发器 - } - - if (oldVersion != newVersion) { - // 版本不匹配 - throw new IllegalStateException("Upgrade notes database to version " + newVersion - + "fails"); - // 抛出异常 - } - } - - private void upgradeToV2(SQLiteDatabase db) { - // 升级到V2方法 - db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); - // 删除笔记表 - db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); - // 删除数据表 - createNoteTable(db); - // 创建新笔记表 - createDataTable(db); - // 创建新数据表 - } - - private void upgradeToV3(SQLiteDatabase db) { - // 升级到V3方法 - // 删除无用的旧触发器 - 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"); - // 添加Google任务ID列 - db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID - + " TEXT NOT NULL DEFAULT ''"); - // 添加垃圾箱系统文件夹 - ContentValues values = new ContentValues(); - values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); - values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); - db.insert(TABLE.NOTE, null, values); - } - - private void upgradeToV4(SQLiteDatabase db) { - // 升级到V4方法 - 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 deleted file mode 100644 index 45bd04d..0000000 --- a/src/data/NotesProvider.java +++ /dev/null @@ -1,429 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.data; - - -import android.app.SearchManager; -// 搜索管理器,用于搜索功能 - -import android.content.ContentProvider; -// 内容提供者基类 - -import android.content.ContentUris; -// URI工具类 - -import android.content.ContentValues; -// 内容值存储类 - -import android.content.Intent; -// 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 { -// 笔记内容提供者类,继承ContentProvider - - private static final UriMatcher mMatcher; - // URI匹配器静态变量 - - 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 { - // 静态初始化块 - 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; - - // 搜索查询SQL语句 - private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION - + " FROM " + TABLE.NOTE - + " WHERE " + NoteColumns.SNIPPET + " LIKE ?" - + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER - + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; - - @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; - } - - 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 - 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)) { - // 检查是否包含笔记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); - } - // 发送内容变更通知 - if (noteId > 0) { - // 通知笔记URI变更 - getContext().getContentResolver().notifyChange( - ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); - } - - if (dataId > 0) { - // 通知数据URI变更 - 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 - 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); - // 获取数据ID - count = db.delete(TABLE.DATA, - DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); - deleteData = true; - break; - default: - throw new IllegalArgumentException("Unknown URI " + uri); - } - if (count > 0) { - // 如果删除了数据 - if (deleteData) { - // 如果是删除数据,通知笔记URI变更 - getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); - } - getContext().getContentResolver().notifyChange(uri, null); - // 通知当前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); - } - - if (count > 0) { - // 如果更新了数据 - if (updateData) { - // 如果是更新数据,通知笔记URI变更 - getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); - } - getContext().getContentResolver().notifyChange(uri, null); - // 通知当前URI变更 - } - return count; - // 返回更新计数 - } - - private String parseSelection(String selection) { - // 解析选择条件方法 - return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); - // 如果选择条件不为空,添加AND和括号 - } - - 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 "); - // 版本号加1 - - if (id > 0 || !TextUtils.isEmpty(selection)) { - // 如果有ID或选择条件 - sql.append(" WHERE "); - } - if (id > 0) { - // 如果有ID - sql.append(NoteColumns.ID + "=" + String.valueOf(id)); - } - if (!TextUtils.isEmpty(selection)) { - // 如果有选择条件 - String selectString = id > 0 ? parseSelection(selection) : selection; - // 获取选择字符串 - for (String args : selectionArgs) { - // 替换占位符 - selectString = selectString.replaceFirst("\\?", args); - } - sql.append(selectString); - } - - mHelper.getWritableDatabase().execSQL(sql.toString()); - // 执行SQL语句 - } - - @Override - public String getType(Uri uri) { - // 获取MIME类型方法 - // TODO Auto-generated method stub - // 待实现 - return null; - } - -} \ No newline at end of file diff --git a/src/gtask/data/MetaData.java b/src/gtask/data/MetaData.java deleted file mode 100644 index 4acaab7..0000000 --- a/src/gtask/data/MetaData.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.data; - -import android.database.Cursor; -import android.util.Log; - -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONException; -import org.json.JSONObject; - - -public class MetaData extends Task { -// MetaData类继承Task类,用于存储元数据 - - private final static String TAG = MetaData.class.getSimpleName(); - // 日志标签,使用类名 - - private String mRelatedGid = null; - // 关联的Google任务ID - - public void setMeta(String gid, JSONObject metaInfo) { - // 设置元数据方法 - try { - metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); - // 将Google任务ID添加到元信息中 - } catch (JSONException e) { - // 捕获JSON异常 - Log.e(TAG, "failed to put related gid"); - // 记录错误日志 - } - setNotes(metaInfo.toString()); - // 将JSON对象转为字符串并设置notes字段 - setName(GTaskStringUtils.META_NOTE_NAME); - // 设置任务名称为元数据笔记名称 - } - - public String getRelatedGid() { - // 获取关联的Google任务ID - return mRelatedGid; - // 返回关联的Google任务ID - } - - @Override - public boolean isWorthSaving() { - // 检查是否值得保存 - return getNotes() != null; - // 如果notes字段不为null则值得保存 - } - - @Override - public void setContentByRemoteJSON(JSONObject js) { - // 根据远程JSON设置内容 - super.setContentByRemoteJSON(js); - // 调用父类方法 - if (getNotes() != null) { - // 如果notes字段不为null - try { - JSONObject metaInfo = new JSONObject(getNotes().trim()); - // 解析notes字段为JSON对象 - mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); - // 从JSON中获取关联的Google任务ID - } catch (JSONException e) { - // 捕获JSON异常 - Log.w(TAG, "failed to get related gid"); - // 记录警告日志 - mRelatedGid = null; - // 将关联ID设为null - } - } - } - - @Override - public void setContentByLocalJSON(JSONObject js) { - // 根据本地JSON设置内容 - // this function should not be called - // 此方法不应被调用 - throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); - // 抛出非法访问错误 - } - - @Override - public JSONObject getLocalJSONFromContent() { - // 从内容获取本地JSON - throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); - // 抛出非法访问错误 - } - - @Override - public int getSyncAction(Cursor c) { - // 获取同步操作类型 - throw new IllegalAccessError("MetaData:getSyncAction should not be called"); - // 抛出非法访问错误 - } - -} \ No newline at end of file diff --git a/src/gtask/data/Node.java b/src/gtask/data/Node.java deleted file mode 100644 index 99487b1..0000000 --- a/src/gtask/data/Node.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.data; - -import android.database.Cursor; - -import org.json.JSONObject; - -public abstract class Node { -// 抽象节点类,定义同步相关功能 - - // 同步操作常量定义 - public static final int SYNC_ACTION_NONE = 0; - // 无同步操作 - - public static final int SYNC_ACTION_ADD_REMOTE = 1; - // 添加到远程 - - public static final int SYNC_ACTION_ADD_LOCAL = 2; - // 添加到本地 - - public static final int SYNC_ACTION_DEL_REMOTE = 3; - // 从远程删除 - - public static final int SYNC_ACTION_DEL_LOCAL = 4; - // 从本地删除 - - public static final int SYNC_ACTION_UPDATE_REMOTE = 5; - // 更新到远程 - - public static final int SYNC_ACTION_UPDATE_LOCAL = 6; - // 更新到本地 - - public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; - // 更新冲突 - - public static final int SYNC_ACTION_ERROR = 8; - // 同步错误 - - // 成员变量 - private String mGid; - // Google任务ID - - private String mName; - // 节点名称 - - private long mLastModified; - // 最后修改时间 - - private boolean mDeleted; - // 删除标志 - - public Node() { - // 构造方法 - mGid = null; - // 初始化GID为null - mName = ""; - // 初始化名称为空字符串 - mLastModified = 0; - // 初始化最后修改时间为0 - mDeleted = false; - // 初始化删除标志为false - } - - // 抽象方法定义 - public abstract JSONObject getCreateAction(int actionId); - // 获取创建操作的JSON对象 - - public abstract JSONObject getUpdateAction(int actionId); - // 获取更新操作的JSON对象 - - public abstract void setContentByRemoteJSON(JSONObject js); - // 根据远程JSON设置内容 - - public abstract void setContentByLocalJSON(JSONObject js); - // 根据本地JSON设置内容 - - public abstract JSONObject getLocalJSONFromContent(); - // 从内容获取本地JSON对象 - - public abstract int getSyncAction(Cursor c); - // 获取同步操作类型 - - // Getter和Setter方法 - public void setGid(String gid) { - // 设置Google任务ID - this.mGid = gid; - } - - public void setName(String name) { - // 设置节点名称 - this.mName = name; - } - - public void setLastModified(long lastModified) { - // 设置最后修改时间 - this.mLastModified = lastModified; - } - - public void setDeleted(boolean deleted) { - // 设置删除标志 - this.mDeleted = deleted; - } - - public String getGid() { - // 获取Google任务ID - return this.mGid; - } - - public String getName() { - // 获取节点名称 - return this.mName; - } - - public long getLastModified() { - // 获取最后修改时间 - return this.mLastModified; - } - - public boolean getDeleted() { - // 获取删除标志 - return this.mDeleted; - } - -} \ No newline at end of file diff --git a/src/gtask/data/SqlData.java b/src/gtask/data/SqlData.java deleted file mode 100644 index 9e60cd3..0000000 --- a/src/gtask/data/SqlData.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.data; - -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.DataConstants; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.data.NotesDatabaseHelper.TABLE; -import net.micode.notes.gtask.exception.ActionFailureException; - -import org.json.JSONException; -import org.json.JSONObject; - - -```java -public class SqlData { -// SQL数据类,用于处理数据库中的data表数据 - - private static final String TAG = SqlData.class.getSimpleName(); - // 日志标签,使用类名 - - private static final int INVALID_ID = -99999; - // 无效ID常量 - - // 数据表投影列数组 - public static final String[] PROJECTION_DATA = new String[] { - DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, - DataColumns.DATA3 - }; - - // 投影列索引常量 - public static final int DATA_ID_COLUMN = 0; - // ID列索引 - - public static final int DATA_MIME_TYPE_COLUMN = 1; - // MIME类型列索引 - - public static final int DATA_CONTENT_COLUMN = 2; - // 内容列索引 - - public static final int DATA_CONTENT_DATA_1_COLUMN = 3; - // DATA1列索引 - - public static final int DATA_CONTENT_DATA_3_COLUMN = 4; - // DATA3列索引 - - // 成员变量 - private ContentResolver mContentResolver; - // 内容解析器 - - private boolean mIsCreate; - // 是否为创建模式标志 - - private long mDataId; - // 数据ID - - private String mDataMimeType; - // 数据MIME类型 - - private String mDataContent; - // 数据内容 - - private long mDataContentData1; - // 数据DATA1字段 - - private String mDataContentData3; - // 数据DATA3字段 - - private ContentValues mDiffDataValues; - // 差异数据值 - - public SqlData(Context context) { - // 创建模式构造方法 - mContentResolver = context.getContentResolver(); - // 获取内容解析器 - mIsCreate = true; - // 设置为创建模式 - mDataId = INVALID_ID; - // 初始化数据ID为无效值 - mDataMimeType = DataConstants.NOTE; - // 初始化MIME类型为普通笔记 - mDataContent = ""; - // 初始化内容为空 - mDataContentData1 = 0; - // 初始化DATA1为0 - mDataContentData3 = ""; - // 初始化DATA3为空 - mDiffDataValues = new ContentValues(); - // 创建差异数据值对象 - } - - public SqlData(Context context, Cursor c) { - // 查询模式构造方法 - mContentResolver = context.getContentResolver(); - // 获取内容解析器 - mIsCreate = false; - // 设置为更新模式 - loadFromCursor(c); - // 从游标加载数据 - mDiffDataValues = new ContentValues(); - // 创建差异数据值对象 - } - - private void loadFromCursor(Cursor c) { - // 从游标加载数据方法 - mDataId = c.getLong(DATA_ID_COLUMN); - // 获取数据ID - mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); - // 获取MIME类型 - mDataContent = c.getString(DATA_CONTENT_COLUMN); - // 获取内容 - mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); - // 获取DATA1字段值 - mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); - // 获取DATA3字段值 - } - - public void setContent(JSONObject js) throws JSONException { - // 根据JSON设置内容 - long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; - // 从JSON获取ID,如果没有则为无效值 - if (mIsCreate || mDataId != dataId) { - // 如果是创建模式或ID不同 - mDiffDataValues.put(DataColumns.ID, dataId); - // 记录ID差异 - } - mDataId = dataId; - // 更新数据ID - - String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) - : DataConstants.NOTE; - // 获取MIME类型,默认为普通笔记 - if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { - // 如果是创建模式或MIME类型不同 - mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); - // 记录MIME类型差异 - } - mDataMimeType = dataMimeType; - // 更新MIME类型 - - String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; - // 获取内容,默认为空 - if (mIsCreate || !mDataContent.equals(dataContent)) { - // 如果是创建模式或内容不同 - mDiffDataValues.put(DataColumns.CONTENT, dataContent); - // 记录内容差异 - } - mDataContent = dataContent; - // 更新内容 - - long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; - // 获取DATA1,默认为0 - if (mIsCreate || mDataContentData1 != dataContentData1) { - // 如果是创建模式或DATA1不同 - mDiffDataValues.put(DataColumns.DATA1, dataContentData1); - // 记录DATA1差异 - } - mDataContentData1 = dataContentData1; - // 更新DATA1 - - String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; - // 获取DATA3,默认为空 - if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { - // 如果是创建模式或DATA3不同 - mDiffDataValues.put(DataColumns.DATA3, dataContentData3); - // 记录DATA3差异 - } - mDataContentData3 = dataContentData3; - // 更新DATA3 - } - - public JSONObject getContent() throws JSONException { - // 获取JSON格式内容 - if (mIsCreate) { - // 如果是创建模式 - Log.e(TAG, "it seems that we haven't created this in database yet"); - // 记录错误日志 - return null; - // 返回null - } - JSONObject js = new JSONObject(); - // 创建JSON对象 - js.put(DataColumns.ID, mDataId); - // 添加ID字段 - js.put(DataColumns.MIME_TYPE, mDataMimeType); - // 添加MIME类型字段 - js.put(DataColumns.CONTENT, mDataContent); - // 添加内容字段 - js.put(DataColumns.DATA1, mDataContentData1); - // 添加DATA1字段 - js.put(DataColumns.DATA3, mDataContentData3); - // 添加DATA3字段 - return js; - // 返回JSON对象 - } - - public void commit(long noteId, boolean validateVersion, long version) { - // 提交数据到数据库 - if (mIsCreate) { - // 如果是创建模式 - if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { - // 如果ID是无效值但差异值中包含ID - mDiffDataValues.remove(DataColumns.ID); - // 移除ID字段 - } - - mDiffDataValues.put(DataColumns.NOTE_ID, noteId); - // 添加笔记ID到差异值 - Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); - // 插入数据并获取URI - try { - mDataId = Long.valueOf(uri.getPathSegments().get(1)); - // 从URI获取新创建的数据ID - } catch (NumberFormatException e) { - // 捕获数字格式异常 - Log.e(TAG, "Get note id error :" + e.toString()); - // 记录错误日志 - throw new ActionFailureException("create note failed"); - // 抛出创建失败异常 - } - } else { - // 如果是更新模式 - if (mDiffDataValues.size() > 0) { - // 如果有差异值 - int result = 0; - // 更新结果 - if (!validateVersion) { - // 如果不验证版本 - result = mContentResolver.update(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); - // 更新数据 - } else { - // 如果验证版本 - result = mContentResolver.update(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, - " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE - + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { - String.valueOf(noteId), String.valueOf(version) - }); - // 带版本验证的更新 - } - if (result == 0) { - // 如果没有更新行 - Log.w(TAG, "there is no update. maybe user updates note when syncing"); - // 记录警告日志 - } - } - } - - mDiffDataValues.clear(); - // 清空差异值 - mIsCreate = false; - // 设置为非创建模式 - } - - public long getId() { - // 获取数据ID - return mDataId; - // 返回数据ID - } -} -``` \ No newline at end of file diff --git a/src/gtask/data/SqlNote.java b/src/gtask/data/SqlNote.java deleted file mode 100644 index 6ad1670..0000000 --- a/src/gtask/data/SqlNote.java +++ /dev/null @@ -1,580 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.data; - -import android.appwidget.AppWidgetManager; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.tool.GTaskStringUtils; -import net.micode.notes.tool.ResourceParser; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; - - -```java -public class SqlNote { -// SQL笔记类,用于处理数据库中的note表数据 - - private static final String TAG = SqlNote.class.getSimpleName(); - // 日志标签 - - private static final int INVALID_ID = -99999; - // 无效ID常量 - - // 笔记表投影列数组 - public static final String[] PROJECTION_NOTE = new String[] { - NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, - NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, - NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE, - NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID, - NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID, - NoteColumns.VERSION - }; - - // 投影列索引常量 - public static final int ID_COLUMN = 0; - // ID列索引 - - public static final int ALERTED_DATE_COLUMN = 1; - // 提醒日期列索引 - - public static final int BG_COLOR_ID_COLUMN = 2; - // 背景颜色ID列索引 - - public static final int CREATED_DATE_COLUMN = 3; - // 创建日期列索引 - - public static final int HAS_ATTACHMENT_COLUMN = 4; - // 是否有附件列索引 - - public static final int MODIFIED_DATE_COLUMN = 5; - // 修改日期列索引 - - public static final int NOTES_COUNT_COLUMN = 6; - // 笔记数量列索引 - - public static final int PARENT_ID_COLUMN = 7; - // 父ID列索引 - - public static final int SNIPPET_COLUMN = 8; - // 摘要列索引 - - public static final int TYPE_COLUMN = 9; - // 类型列索引 - - public static final int WIDGET_ID_COLUMN = 10; - // 小部件ID列索引 - - public static final int WIDGET_TYPE_COLUMN = 11; - // 小部件类型列索引 - - public static final int SYNC_ID_COLUMN = 12; - // 同步ID列索引 - - public static final int LOCAL_MODIFIED_COLUMN = 13; - // 本地修改标志列索引 - - public static final int ORIGIN_PARENT_ID_COLUMN = 14; - // 原始父ID列索引 - - public static final int GTASK_ID_COLUMN = 15; - // Google任务ID列索引 - - public static final int VERSION_COLUMN = 16; - // 版本号列索引 - - // 成员变量 - private Context mContext; - // 上下文对象 - - private ContentResolver mContentResolver; - // 内容解析器 - - private boolean mIsCreate; - // 是否为创建模式 - - private long mId; - // 笔记ID - - private long mAlertDate; - // 提醒日期 - - private int mBgColorId; - // 背景颜色ID - - private long mCreatedDate; - // 创建日期 - - private int mHasAttachment; - // 是否有附件 - - private long mModifiedDate; - // 修改日期 - - private long mParentId; - // 父文件夹ID - - private String mSnippet; - // 摘要内容 - - private int mType; - // 笔记类型 - - private int mWidgetId; - // 小部件ID - - private int mWidgetType; - // 小部件类型 - - private long mOriginParent; - // 原始父ID - - private long mVersion; - // 版本号 - - private ContentValues mDiffNoteValues; - // 差异数据值 - - private ArrayList mDataList; - // 关联的数据列表 - - public SqlNote(Context context) { - // 创建模式构造方法 - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = true; - mId = INVALID_ID; - mAlertDate = 0; - mBgColorId = ResourceParser.getDefaultBgId(context); - // 默认背景色 - mCreatedDate = System.currentTimeMillis(); - // 当前时间 - mHasAttachment = 0; - mModifiedDate = System.currentTimeMillis(); - mParentId = 0; - mSnippet = ""; - mType = Notes.TYPE_NOTE; - mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; - // 无效小部件ID - mWidgetType = Notes.TYPE_WIDGET_INVALIDE; - mOriginParent = 0; - mVersion = 0; - mDiffNoteValues = new ContentValues(); - mDataList = new ArrayList(); - } - - public SqlNote(Context context, Cursor c) { - // 从游标构造方法 - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(c); - // 从游标加载 - mDataList = new ArrayList(); - if (mType == Notes.TYPE_NOTE) - loadDataContent(); - // 如果是笔记类型,加载数据内容 - mDiffNoteValues = new ContentValues(); - } - - public SqlNote(Context context, long id) { - // 从ID构造方法 - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(id); - // 根据ID加载 - mDataList = new ArrayList(); - if (mType == Notes.TYPE_NOTE) - loadDataContent(); - mDiffNoteValues = new ContentValues(); - - } - - private void loadFromCursor(long id) { - // 根据ID从数据库加载 - Cursor c = null; - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", - new String[] { - String.valueOf(id) - }, null); - if (c != null) { - c.moveToNext(); - loadFromCursor(c); - } else { - Log.w(TAG, "loadFromCursor: cursor = null"); - } - } finally { - if (c != null) - c.close(); - } - } - - private void loadFromCursor(Cursor c) { - // 从游标加载数据 - mId = c.getLong(ID_COLUMN); - mAlertDate = c.getLong(ALERTED_DATE_COLUMN); - mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); - mCreatedDate = c.getLong(CREATED_DATE_COLUMN); - mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); - mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); - mParentId = c.getLong(PARENT_ID_COLUMN); - mSnippet = c.getString(SNIPPET_COLUMN); - mType = c.getInt(TYPE_COLUMN); - mWidgetId = c.getInt(WIDGET_ID_COLUMN); - mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); - mVersion = c.getLong(VERSION_COLUMN); - } - - private void loadDataContent() { - // 加载关联的数据内容 - Cursor c = null; - mDataList.clear(); - try { - c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, - "(note_id=?)", new String[] { - String.valueOf(mId) - }, null); - if (c != null) { - if (c.getCount() == 0) { - Log.w(TAG, "it seems that the note has not data"); - return; - } - while (c.moveToNext()) { - SqlData data = new SqlData(mContext, c); - mDataList.add(data); - } - } else { - Log.w(TAG, "loadDataContent: cursor = null"); - } - } finally { - if (c != null) - c.close(); - } - } - - public boolean setContent(JSONObject js) { - // 根据JSON设置内容 - try { - JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { - Log.w(TAG, "cannot set system folder"); - } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { - // 文件夹类型只能更新摘要和类型 - String snippet = note.has(NoteColumns.SNIPPET) ? note - .getString(NoteColumns.SNIPPET) : ""; - if (mIsCreate || !mSnippet.equals(snippet)) { - mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); - } - mSnippet = snippet; - - int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) - : Notes.TYPE_NOTE; - if (mIsCreate || mType != type) { - mDiffNoteValues.put(NoteColumns.TYPE, type); - } - mType = type; - } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { - // 笔记类型需要处理所有字段 - JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; - if (mIsCreate || mId != id) { - mDiffNoteValues.put(NoteColumns.ID, id); - } - mId = id; - - // 依次设置各个字段... - long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note - .getLong(NoteColumns.ALERTED_DATE) : 0; - if (mIsCreate || mAlertDate != alertDate) { - mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); - } - mAlertDate = alertDate; - - int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note - .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); - if (mIsCreate || mBgColorId != bgColorId) { - mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); - } - mBgColorId = bgColorId; - - long createDate = note.has(NoteColumns.CREATED_DATE) ? note - .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); - if (mIsCreate || mCreatedDate != createDate) { - mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); - } - mCreatedDate = createDate; - - int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note - .getInt(NoteColumns.HAS_ATTACHMENT) : 0; - if (mIsCreate || mHasAttachment != hasAttachment) { - mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); - } - mHasAttachment = hasAttachment; - - long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note - .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); - if (mIsCreate || mModifiedDate != modifiedDate) { - mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); - } - mModifiedDate = modifiedDate; - - long parentId = note.has(NoteColumns.PARENT_ID) ? note - .getLong(NoteColumns.PARENT_ID) : 0; - if (mIsCreate || mParentId != parentId) { - mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); - } - mParentId = parentId; - - String snippet = note.has(NoteColumns.SNIPPET) ? note - .getString(NoteColumns.SNIPPET) : ""; - if (mIsCreate || !mSnippet.equals(snippet)) { - mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); - } - mSnippet = snippet; - - int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) - : Notes.TYPE_NOTE; - if (mIsCreate || mType != type) { - mDiffNoteValues.put(NoteColumns.TYPE, type); - } - mType = type; - - int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) - : AppWidgetManager.INVALID_APPWIDGET_ID; - if (mIsCreate || mWidgetId != widgetId) { - mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); - } - mWidgetId = widgetId; - - int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note - .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; - if (mIsCreate || mWidgetType != widgetType) { - mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); - } - mWidgetType = widgetType; - - long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note - .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; - if (mIsCreate || mOriginParent != originParent) { - mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); - } - mOriginParent = originParent; - - // 处理关联的数据 - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - SqlData sqlData = null; - if (data.has(DataColumns.ID)) { - long dataId = data.getLong(DataColumns.ID); - for (SqlData temp : mDataList) { - if (dataId == temp.getId()) { - sqlData = temp; - } - } - } - - if (sqlData == null) { - sqlData = new SqlData(mContext); - mDataList.add(sqlData); - } - - sqlData.setContent(data); - } - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return false; - } - return true; - } - - public JSONObject getContent() { - // 获取JSON格式内容 - try { - JSONObject js = new JSONObject(); - - if (mIsCreate) { - Log.e(TAG, "it seems that we haven't created this in database yet"); - return null; - } - - JSONObject note = new JSONObject(); - if (mType == Notes.TYPE_NOTE) { - // 笔记类型包含所有字段 - note.put(NoteColumns.ID, mId); - note.put(NoteColumns.ALERTED_DATE, mAlertDate); - note.put(NoteColumns.BG_COLOR_ID, mBgColorId); - note.put(NoteColumns.CREATED_DATE, mCreatedDate); - note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); - note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); - note.put(NoteColumns.PARENT_ID, mParentId); - note.put(NoteColumns.SNIPPET, mSnippet); - note.put(NoteColumns.TYPE, mType); - note.put(NoteColumns.WIDGET_ID, mWidgetId); - note.put(NoteColumns.WIDGET_TYPE, mWidgetType); - note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); - js.put(GTaskStringUtils.META_HEAD_NOTE, note); - - // 添加关联数据 - JSONArray dataArray = new JSONArray(); - for (SqlData sqlData : mDataList) { - JSONObject data = sqlData.getContent(); - if (data != null) { - dataArray.put(data); - } - } - js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); - } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { - // 文件夹类型只包含基本字段 - note.put(NoteColumns.ID, mId); - note.put(NoteColumns.TYPE, mType); - note.put(NoteColumns.SNIPPET, mSnippet); - js.put(GTaskStringUtils.META_HEAD_NOTE, note); - } - - return js; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - return null; - } - - public void setParentId(long id) { - // 设置父ID - mParentId = id; - mDiffNoteValues.put(NoteColumns.PARENT_ID, id); - } - - public void setGtaskId(String gid) { - // 设置Google任务ID - mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); - } - - public void setSyncId(long syncId) { - // 设置同步ID - mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); - } - - public void resetLocalModified() { - // 重置本地修改标志 - mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); - } - - public long getId() { - // 获取笔记ID - return mId; - } - - public long getParentId() { - // 获取父ID - return mParentId; - } - - public String getSnippet() { - // 获取摘要 - return mSnippet; - } - - public boolean isNoteType() { - // 判断是否为笔记类型 - return mType == Notes.TYPE_NOTE; - } - - public void commit(boolean validateVersion) { - // 提交到数据库 - if (mIsCreate) { - // 创建模式 - if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { - mDiffNoteValues.remove(NoteColumns.ID); - } - - Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); - try { - mId = Long.valueOf(uri.getPathSegments().get(1)); - } catch (NumberFormatException e) { - Log.e(TAG, "Get note id error :" + e.toString()); - throw new ActionFailureException("create note failed"); - } - if (mId == 0) { - throw new IllegalStateException("Create thread id failed"); - } - - if (mType == Notes.TYPE_NOTE) { - for (SqlData sqlData : mDataList) { - sqlData.commit(mId, false, -1); - } - } - } else { - // 更新模式 - if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { - Log.e(TAG, "No such note"); - throw new IllegalStateException("Try to update note with invalid id"); - } - if (mDiffNoteValues.size() > 0) { - mVersion ++; - int result = 0; - if (!validateVersion) { - result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" - + NoteColumns.ID + "=?)", new String[] { - String.valueOf(mId) - }); - } else { - result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" - + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", - new String[] { - String.valueOf(mId), String.valueOf(mVersion) - }); - } - if (result == 0) { - Log.w(TAG, "there is no update. maybe user updates note when syncing"); - } - } - - if (mType == Notes.TYPE_NOTE) { - for (SqlData sqlData : mDataList) { - sqlData.commit(mId, validateVersion, mVersion); - } - } - } - - // 重新加载数据 - loadFromCursor(mId); - if (mType == Notes.TYPE_NOTE) - loadDataContent(); - - mDiffNoteValues.clear(); - mIsCreate = false; - } -} -``` \ No newline at end of file diff --git a/src/gtask/data/Task.java b/src/gtask/data/Task.java deleted file mode 100644 index 61f21c5..0000000 --- a/src/gtask/data/Task.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.data; - -import android.database.Cursor; -import android.text.TextUtils; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.DataConstants; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - - -```java -public class Task extends Node { -// Task类继承Node,表示Google任务中的任务项 - - private static final String TAG = Task.class.getSimpleName(); - // 日志标签 - - // 成员变量 - private boolean mCompleted; - // 是否已完成 - - private String mNotes; - // 任务备注 - - private JSONObject mMetaInfo; - // 元数据信息 - - private Task mPriorSibling; - // 前一个兄弟任务 - - private TaskList mParent; - // 父任务列表 - - public Task() { - // 构造方法 - super(); - // 调用父类构造方法 - mCompleted = false; - // 初始化为未完成 - mNotes = null; - // 备注为空 - mPriorSibling = null; - // 前兄弟任务为空 - mParent = null; - // 父任务列表为空 - mMetaInfo = null; - // 元信息为空 - } - - public JSONObject getCreateAction(int actionId) { - // 获取创建操作的JSON - JSONObject js = new JSONObject(); - - try { - // action_type - 操作类型 - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); - - // action_id - 操作ID - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // index - 在父列表中的索引 - js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); - - // entity_delta - 实体数据 - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务名称 - entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 创建者ID - entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, - GTaskStringUtils.GTASK_JSON_TYPE_TASK); // 实体类型为任务 - if (getNotes() != null) { - entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 任务备注 - } - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - // parent_id - 父ID - js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); - - // dest_parent_type - 目标父类型 - js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, - GTaskStringUtils.GTASK_JSON_TYPE_GROUP); - - // list_id - 列表ID - js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); - - // prior_sibling_id - 前兄弟任务ID - if (mPriorSibling != null) { - js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); - } - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate task-create jsonobject"); - } - - return js; - // 返回创建操作JSON - } - - public JSONObject getUpdateAction(int actionId) { - // 获取更新操作的JSON - JSONObject js = new JSONObject(); - - try { - // action_type - 操作类型为更新 - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); - - // action_id - 操作ID - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // id - 任务ID - js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); - - // entity_delta - 实体变更数据 - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务名称 - if (getNotes() != null) { - entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 任务备注 - } - entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 删除标志 - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate task-update jsonobject"); - } - - return js; - // 返回更新操作JSON - } - - public void setContentByRemoteJSON(JSONObject js) { - // 根据远程JSON设置内容 - if (js != null) { - try { - // id - 任务ID - if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { - setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); - } - - // last_modified - 最后修改时间 - if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { - setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); - } - - // name - 任务名称 - if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { - setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); - } - - // notes - 任务备注 - if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { - setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); - } - - // deleted - 删除标志 - if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { - setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); - } - - // completed - 完成状态 - if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { - setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to get task content from jsonobject"); - } - } - } - - public void setContentByLocalJSON(JSONObject js) { - // 根据本地JSON设置内容 - if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) - || !js.has(GTaskStringUtils.META_HEAD_DATA)) { - Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); - } - - try { - JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - - if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { - Log.e(TAG, "invalid type"); - return; - } - - // 从数据中查找笔记内容作为任务名称 - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { - setName(data.getString(DataColumns.CONTENT)); - break; - } - } - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - } - - public JSONObject getLocalJSONFromContent() { - // 从内容获取本地JSON - String name = getName(); - try { - if (mMetaInfo == null) { - // 来自web的新创建任务 - if (name == null) { - Log.w(TAG, "the note seems to be an empty one"); - return null; - } - - JSONObject js = new JSONObject(); - JSONObject note = new JSONObject(); - JSONArray dataArray = new JSONArray(); - JSONObject data = new JSONObject(); - data.put(DataColumns.CONTENT, name); // 将任务名称作为内容 - dataArray.put(data); - js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); // 数据部分 - note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 类型为笔记 - js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 笔记部分 - return js; - } else { - // 已同步的任务 - JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - - // 更新笔记内容 - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { - data.put(DataColumns.CONTENT, getName()); - break; - } - } - - note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); - return mMetaInfo; - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return null; - } - } - - public void setMetaInfo(MetaData metaData) { - // 设置元数据信息 - if (metaData != null && metaData.getNotes() != null) { - try { - mMetaInfo = new JSONObject(metaData.getNotes()); - // 解析元数据的notes字段为JSON - } catch (JSONException e) { - Log.w(TAG, e.toString()); - mMetaInfo = null; - } - } - } - - public int getSyncAction(Cursor c) { - // 获取同步操作类型 - try { - JSONObject noteInfo = null; - if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { - noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - } - - if (noteInfo == null) { - Log.w(TAG, "it seems that note meta has been deleted"); - return SYNC_ACTION_UPDATE_REMOTE; - } - - if (!noteInfo.has(NoteColumns.ID)) { - Log.w(TAG, "remote note id seems to be deleted"); - return SYNC_ACTION_UPDATE_LOCAL; - } - - // 验证笔记ID - if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { - Log.w(TAG, "note id doesn't match"); - return SYNC_ACTION_UPDATE_LOCAL; - } - - if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { - // 本地没有更新 - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // 双方都没有更新 - return SYNC_ACTION_NONE; - } else { - // 将远程更新应用到本地 - return SYNC_ACTION_UPDATE_LOCAL; - } - } else { - // 验证Google任务ID - if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { - Log.e(TAG, "gtask id doesn't match"); - return SYNC_ACTION_ERROR; - } - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // 只有本地有修改 - return SYNC_ACTION_UPDATE_REMOTE; - } else { - // 冲突:双方都有修改 - return SYNC_ACTION_UPDATE_CONFLICT; - } - } - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - - return SYNC_ACTION_ERROR; - } - - public boolean isWorthSaving() { - // 检查是否值得保存 - return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) - || (getNotes() != null && getNotes().trim().length() > 0); - // 有元信息、或名称非空、或备注非空 - } - - // Setter方法 - public void setCompleted(boolean completed) { - this.mCompleted = completed; - } - - public void setNotes(String notes) { - this.mNotes = notes; - } - - public void setPriorSibling(Task priorSibling) { - this.mPriorSibling = priorSibling; - } - - public void setParent(TaskList parent) { - this.mParent = parent; - } - - // Getter方法 - public boolean getCompleted() { - return this.mCompleted; - } - - public String getNotes() { - return this.mNotes; - } - - public Task getPriorSibling() { - return this.mPriorSibling; - } - - public TaskList getParent() { - return this.mParent; - } - -} -``` \ No newline at end of file diff --git a/src/gtask/data/TaskList.java b/src/gtask/data/TaskList.java deleted file mode 100644 index 32a3d37..0000000 --- a/src/gtask/data/TaskList.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.data; - -import android.database.Cursor; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; - - -public class TaskList extends Node { -// TaskList类继承Node,表示Google任务中的任务列表 - - private static final String TAG = TaskList.class.getSimpleName(); - // 日志标签 - - // 成员变量 - private int mIndex; - // 列表索引 - - private ArrayList mChildren; - // 子任务列表 - - public TaskList() { - // 构造方法 - super(); - // 调用父类构造方法 - mChildren = new ArrayList(); - // 初始化子任务列表 - mIndex = 1; - // 默认索引为1 - } - - public JSONObject getCreateAction(int actionId) { - // 获取创建操作的JSON - JSONObject js = new JSONObject(); - - try { - // action_type - 操作类型为创建 - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); - - // action_id - 操作ID - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // index - 列表索引 - js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); - - // entity_delta - 实体数据 - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 列表名称 - entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 创建者ID - entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, - GTaskStringUtils.GTASK_JSON_TYPE_GROUP); // 实体类型为分组 - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate tasklist-create jsonobject"); - } - - return js; - // 返回创建操作JSON - } - - public JSONObject getUpdateAction(int actionId) { - // 获取更新操作的JSON - JSONObject js = new JSONObject(); - - try { - // action_type - 操作类型为更新 - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); - - // action_id - 操作ID - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // id - 列表ID - js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); - - // entity_delta - 实体变更数据 - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 列表名称 - entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 删除标志 - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate tasklist-update jsonobject"); - } - - return js; - // 返回更新操作JSON - } - - public void setContentByRemoteJSON(JSONObject js) { - // 根据远程JSON设置内容 - if (js != null) { - try { - // id - 列表ID - if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { - setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); - } - - // last_modified - 最后修改时间 - if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { - setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); - } - - // name - 列表名称 - if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { - setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); - } - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to get tasklist content from jsonobject"); - } - } - } - - public void setContentByLocalJSON(JSONObject js) { - // 根据本地JSON设置内容 - if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { - Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); - } - - try { - JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - - if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { - // 普通文件夹类型 - String name = folder.getString(NoteColumns.SNIPPET); - setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); // 添加MIUI前缀 - } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { - // 系统文件夹类型 - if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) - setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); - else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) - setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_CALL_NOTE); // 通话记录文件夹 - else - Log.e(TAG, "invalid system folder"); - } else { - Log.e(TAG, "error type"); - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - } - - public JSONObject getLocalJSONFromContent() { - // 从内容获取本地JSON - try { - JSONObject js = new JSONObject(); - JSONObject folder = new JSONObject(); - - String folderName = getName(); - // 移除MIUI前缀 - if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) - folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), - folderName.length()); - folder.put(NoteColumns.SNIPPET, folderName); // 文件夹名称 - // 判断文件夹类型 - if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) - || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) - folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 系统文件夹 - else - folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); // 普通文件夹 - - js.put(GTaskStringUtils.META_HEAD_NOTE, folder); - - return js; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return null; - } - } - - public int getSyncAction(Cursor c) { - // 获取同步操作类型 - try { - if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { - // 本地没有更新 - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // 双方都没有更新 - return SYNC_ACTION_NONE; - } else { - // 将远程更新应用到本地 - return SYNC_ACTION_UPDATE_LOCAL; - } - } else { - // 验证Google任务ID - if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { - Log.e(TAG, "gtask id doesn't match"); - return SYNC_ACTION_ERROR; - } - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // 只有本地有修改 - return SYNC_ACTION_UPDATE_REMOTE; - } else { - // 对于文件夹冲突,直接应用本地修改 - return SYNC_ACTION_UPDATE_REMOTE; - } - } - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - - return SYNC_ACTION_ERROR; - } - - public int getChildTaskCount() { - // 获取子任务数量 - return mChildren.size(); - } - - public boolean addChildTask(Task task) { - // 添加子任务到末尾 - boolean ret = false; - if (task != null && !mChildren.contains(task)) { - ret = mChildren.add(task); - if (ret) { - // 设置前兄弟任务和父列表 - task.setPriorSibling(mChildren.isEmpty() ? null : mChildren - .get(mChildren.size() - 1)); - task.setParent(this); - } - } - return ret; - } - - public boolean addChildTask(Task task, int index) { - // 在指定位置添加子任务 - if (index < 0 || index > mChildren.size()) { - Log.e(TAG, "add child task: invalid index"); - return false; - } - - int pos = mChildren.indexOf(task); - if (task != null && pos == -1) { - mChildren.add(index, task); - - // 更新任务列表 - Task preTask = null; - Task afterTask = null; - if (index != 0) - preTask = mChildren.get(index - 1); // 前一个任务 - if (index != mChildren.size() - 1) - afterTask = mChildren.get(index + 1); // 后一个任务 - - task.setPriorSibling(preTask); // 设置前兄弟任务 - if (afterTask != null) - afterTask.setPriorSibling(task); // 更新后一个任务的前兄弟 - } - - return true; - } - - public boolean removeChildTask(Task task) { - // 移除子任务 - boolean ret = false; - int index = mChildren.indexOf(task); - if (index != -1) { - ret = mChildren.remove(task); - - if (ret) { - // 重置前兄弟任务和父列表 - task.setPriorSibling(null); - task.setParent(null); - - // 更新任务列表 - if (index != mChildren.size()) { - mChildren.get(index).setPriorSibling( - index == 0 ? null : mChildren.get(index - 1)); - } - } - } - return ret; - } - - public boolean moveChildTask(Task task, int index) { - // 移动子任务到新位置 - if (index < 0 || index >= mChildren.size()) { - Log.e(TAG, "move child task: invalid index"); - return false; - } - - int pos = mChildren.indexOf(task); - if (pos == -1) { - Log.e(TAG, "move child task: the task should in the list"); - return false; - } - - if (pos == index) - return true; // 位置相同,无需移动 - return (removeChildTask(task) && addChildTask(task, index)); - } - - public Task findChildTaskByGid(String gid) { - // 根据GID查找子任务 - for (int i = 0; i < mChildren.size(); i++) { - Task t = mChildren.get(i); - if (t.getGid().equals(gid)) { - return t; - } - } - return null; - } - - public int getChildTaskIndex(Task task) { - // 获取子任务索引 - return mChildren.indexOf(task); - } - - public Task getChildTaskByIndex(int index) { - // 根据索引获取子任务 - if (index < 0 || index >= mChildren.size()) { - Log.e(TAG, "getTaskByIndex: invalid index"); - return null; - } - return mChildren.get(index); - } - - public Task getChilTaskByGid(String gid) { - // 根据GID获取子任务(方法名拼写错误) - for (Task task : mChildren) { - if (task.getGid().equals(gid)) - return task; - } - return null; - } - - public ArrayList getChildTaskList() { - // 获取子任务列表 - return this.mChildren; - } - - public void setIndex(int index) { - // 设置列表索引 - this.mIndex = index; - } - - public int getIndex() { - // 获取列表索引 - return this.mIndex; - } -} \ No newline at end of file diff --git a/src/gtask/exception/ActionFailureException.java b/src/gtask/exception/ActionFailureException.java deleted file mode 100644 index 15504be..0000000 --- a/src/gtask/exception/ActionFailureException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.exception; - -public class ActionFailureException extends RuntimeException { - private static final long serialVersionUID = 4425249765923293627L; - - public ActionFailureException() { - super(); - } - - public ActionFailureException(String paramString) { - super(paramString); - } - - public ActionFailureException(String paramString, Throwable paramThrowable) { - super(paramString, paramThrowable); - } -} diff --git a/src/gtask/remote/GTaskASyncTask.java b/src/gtask/remote/GTaskASyncTask.java deleted file mode 100644 index 2313620..0000000 --- a/src/gtask/remote/GTaskASyncTask.java +++ /dev/null @@ -1,210 +0,0 @@ - -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.remote; -// 包名:Google任务同步相关的远程操作 - -import android.app.Notification; -// 导入通知类 - -import android.app.NotificationManager; -// 导入通知管理器 - -import android.app.PendingIntent; -// 导入延迟意图 - -import android.content.Context; -// 导入上下文 - -import android.content.Intent; -// 导入意图 - -import android.os.AsyncTask; -// 导入异步任务 - -import net.micode.notes.R; -// 导入资源类 - -import net.micode.notes.ui.NotesListActivity; -// 导入笔记列表活动 - -import net.micode.notes.ui.NotesPreferenceActivity; -// 导入设置活动 - - -public class GTaskASyncTask extends AsyncTask { -// Google任务异步任务类,继承AsyncTask - - private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; - // 同步通知ID常量 - - public interface OnCompleteListener { - // 完成监听器接口 - void onComplete(); - // 完成回调方法 - } - - // 成员变量 - private Context mContext; - // 上下文 - - private NotificationManager mNotifiManager; - // 通知管理器 - - private GTaskManager mTaskManager; - // 任务管理器 - - private OnCompleteListener mOnCompleteListener; - // 完成监听器 - - public GTaskASyncTask(Context context, OnCompleteListener listener) { - // 构造方法 - mContext = context; - // 保存上下文 - mOnCompleteListener = listener; - // 保存完成监听器 - mNotifiManager = (NotificationManager) mContext - .getSystemService(Context.NOTIFICATION_SERVICE); - // 获取通知管理器服务 - mTaskManager = GTaskManager.getInstance(); - // 获取任务管理器单例 - } - - public void cancelSync() { - // 取消同步方法 - mTaskManager.cancelSync(); - // 调用任务管理器取消同步 - } - - public void publishProgess(String message) { - // 发布进度方法(方法名拼写错误) - publishProgress(new String[] { - message - }); - // 调用父类的进度更新方法 - } - -// 注释掉的旧版本显示通知方法 -// private void showNotification(int tickerId, String content) { -// Notification notification = new Notification(R.drawable.notification, mContext -// .getString(tickerId), System.currentTimeMillis()); -// notification.defaults = Notification.DEFAULT_LIGHTS; -// notification.flags = Notification.FLAG_AUTO_CANCEL; -// PendingIntent pendingIntent; -// if (tickerId != R.string.ticker_success) { -// pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, -// NotesPreferenceActivity.class), 0); -// - // } else { -// pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, -// NotesListActivity.class), 0); -// } -// notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, -// pendingIntent); -// mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); -// } - - private void showNotification(int tickerId, String content) { -// 新版本显示通知方法 - PendingIntent pendingIntent; - // 延迟意图变量 - if (tickerId != R.string.ticker_success) { - // 如果不是成功提示 - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE); - // 跳转到设置页面的意图 - } else { - // 如果是成功提示 - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE); - // 跳转到笔记列表页面的意图 - } - // 使用Notification.Builder构建通知 - Notification.Builder builder = new Notification.Builder(mContext) - .setAutoCancel(true) // 点击后自动取消 - .setContentTitle(mContext.getString(R.string.app_name)) // 标题为应用名 - .setContentText(content) // 内容文本 - .setContentIntent(pendingIntent) // 点击意图 - .setWhen(System.currentTimeMillis()) // 通知时间 - .setOngoing(true); // 设置为持续通知 - Notification notification=builder.getNotification(); - // 获取通知对象 - mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); - // 显示通知 - } - - - @Override - protected Integer doInBackground(Void... unused) { - // 后台执行方法 - publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity - .getSyncAccountName(mContext))); - // 发布登录进度 - return mTaskManager.sync(mContext, this); - // 执行同步操作 - } - - @Override - protected void onProgressUpdate(String... progress) { - // 进度更新回调 - showNotification(R.string.ticker_syncing, progress[0]); - // 显示同步进行中的通知 - if (mContext instanceof GTaskSyncService) { - // 如果上下文是GTaskSyncService - ((GTaskSyncService) mContext).sendBroadcast(progress[0]); - // 发送进度广播 - } - } - - @Override - protected void onPostExecute(Integer result) { - // 执行完成回调 - if (result == GTaskManager.STATE_SUCCESS) { - // 同步成功 - showNotification(R.string.ticker_success, mContext.getString( - R.string.success_sync_account, mTaskManager.getSyncAccount())); - // 显示成功通知 - NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); - // 保存最后同步时间 - } else if (result == GTaskManager.STATE_NETWORK_ERROR) { - // 网络错误 - showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); - // 显示网络错误通知 - } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { - // 内部错误 - showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); - // 显示内部错误通知 - } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { - // 同步取消 - showNotification(R.string.ticker_cancel, mContext - .getString(R.string.error_sync_cancelled)); - // 显示取消通知 - } - // 执行完成回调 - if (mOnCompleteListener != null) { - // 如果有完成监听器 - new Thread(new Runnable() { - // 在新线程中执行 - - public void run() { - mOnCompleteListener.onComplete(); - // 调用完成回调 - } - }).start(); - } - } -} \ No newline at end of file diff --git a/src/gtask/remote/GTaskClient.java b/src/gtask/remote/GTaskClient.java deleted file mode 100644 index e757720..0000000 --- a/src/gtask/remote/GTaskClient.java +++ /dev/null @@ -1,752 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.remote; - -import android.accounts.Account; -import android.accounts.AccountManager; -import android.accounts.AccountManagerFuture; -import android.app.Activity; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; - -import net.micode.notes.gtask.data.Node; -import net.micode.notes.gtask.data.Task; -import net.micode.notes.gtask.data.TaskList; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.gtask.exception.NetworkFailureException; -import net.micode.notes.tool.GTaskStringUtils; -import net.micode.notes.ui.NotesPreferenceActivity; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.cookie.Cookie; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.LinkedList; -import java.util.List; -import java.util.zip.GZIPInputStream; -import java.util.zip.Inflater; -import java.util.zip.InflaterInputStream; - - -public class GTaskClient { -// Google任务客户端类,负责与Google Tasks API通信 - - private static final String TAG = GTaskClient.class.getSimpleName(); - // 日志标签 - - private static final String GTASK_URL = "https://mail.google.com/tasks/"; - // Google Tasks基础URL - - private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; - // GET请求URL - - private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; - // POST请求URL - - private static GTaskClient mInstance = null; - // 单例实例 - - private DefaultHttpClient mHttpClient; - // HTTP客户端 - - private String mGetUrl; - // 当前GET请求URL - - private String mPostUrl; - // 当前POST请求URL - - private long mClientVersion; - // 客户端版本号 - - private boolean mLoggedin; - // 登录状态 - - private long mLastLoginTime; - // 最后登录时间 - - private int mActionId; - // 操作ID计数器 - - private Account mAccount; - // Google账户 - - private JSONArray mUpdateArray; - // 待提交的更新操作数组 - - private GTaskClient() { - // 私有构造方法 - mHttpClient = null; - // HTTP客户端初始化为空 - mGetUrl = GTASK_GET_URL; - // 初始化GET URL - mPostUrl = GTASK_POST_URL; - // 初始化POST URL - mClientVersion = -1; - // 客户端版本初始化为-1 - mLoggedin = false; - // 登录状态初始化为false - mLastLoginTime = 0; - // 最后登录时间初始化为0 - mActionId = 1; - // 操作ID从1开始 - mAccount = null; - // 账户初始化为空 - mUpdateArray = null; - // 更新数组初始化为空 - } - - public static synchronized GTaskClient getInstance() { - // 获取单例实例 - if (mInstance == null) { - mInstance = new GTaskClient(); - // 创建新实例 - } - return mInstance; - // 返回实例 - } - - public boolean login(Activity activity) { - // 登录方法 - // 假设cookie在5分钟后过期,需要重新登录 - final long interval = 1000 * 60 * 5; - // 5分钟间隔 - if (mLastLoginTime + interval < System.currentTimeMillis()) { - mLoggedin = false; - // 如果超过5分钟,标记为未登录 - } - - // 账户切换后需要重新登录 - if (mLoggedin - && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity - .getSyncAccountName(activity))) { - mLoggedin = false; - // 如果账户名不匹配,标记为未登录 - } - - if (mLoggedin) { - Log.d(TAG, "already logged in"); - return true; - // 如果已登录,直接返回true - } - - mLastLoginTime = System.currentTimeMillis(); - // 更新最后登录时间 - String authToken = loginGoogleAccount(activity, false); - // 获取Google账户授权令牌 - if (authToken == null) { - Log.e(TAG, "login google account failed"); - return false; - // 获取令牌失败 - } - - // 如果需要,使用自定义域登录 - if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() - .endsWith("googlemail.com"))) { - // 如果不是gmail或googlemail账户 - StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); - // 构建自定义域URL - int index = mAccount.name.indexOf('@') + 1; - String suffix = mAccount.name.substring(index); - // 提取域名后缀 - url.append(suffix + "/"); - mGetUrl = url.toString() + "ig"; - // 设置GET URL - mPostUrl = url.toString() + "r/ig"; - // 设置POST URL - - if (tryToLoginGtask(activity, authToken)) { - mLoggedin = true; - // 尝试使用自定义域登录 - } - } - - // 尝试使用Google官方URL登录 - if (!mLoggedin) { - mGetUrl = GTASK_GET_URL; - // 重置为官方GET URL - mPostUrl = GTASK_POST_URL; - // 重置为官方POST URL - if (!tryToLoginGtask(activity, authToken)) { - return false; - // 登录失败 - } - } - - mLoggedin = true; - // 标记为已登录 - return true; - } - - private String loginGoogleAccount(Activity activity, boolean invalidateToken) { - // 登录Google账户 - String authToken; - // 授权令牌 - AccountManager accountManager = AccountManager.get(activity); - // 获取账户管理器 - Account[] accounts = accountManager.getAccountsByType("com.google"); - // 获取所有Google账户 - - if (accounts.length == 0) { - Log.e(TAG, "there is no available google account"); - return null; - // 没有可用Google账户 - } - - String accountName = NotesPreferenceActivity.getSyncAccountName(activity); - // 获取同步账户名 - Account account = null; - for (Account a : accounts) { - if (a.name.equals(accountName)) { - account = a; - break; - // 查找匹配的账户 - } - } - if (account != null) { - mAccount = account; - // 保存账户 - } else { - Log.e(TAG, "unable to get an account with the same name in the settings"); - return null; - // 没有找到匹配账户 - } - - // 获取授权令牌 - AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, - "goanna_mobile", null, activity, null, null); - // 请求授权令牌 - try { - Bundle authTokenBundle = accountManagerFuture.getResult(); - // 获取结果 - authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); - // 提取令牌 - if (invalidateToken) { - accountManager.invalidateAuthToken("com.google", authToken); - // 使令牌失效 - loginGoogleAccount(activity, false); - // 重新登录 - } - } catch (Exception e) { - Log.e(TAG, "get auth token failed"); - authToken = null; - // 获取令牌失败 - } - - return authToken; - // 返回令牌 - } - - private boolean tryToLoginGtask(Activity activity, String authToken) { - // 尝试登录Google Tasks - if (!loginGtask(authToken)) { - // 如果登录失败,可能是令牌过期,使令牌失效并重试 - authToken = loginGoogleAccount(activity, true); - // 重新获取令牌 - if (authToken == null) { - Log.e(TAG, "login google account failed"); - return false; - } - - if (!loginGtask(authToken)) { - Log.e(TAG, "login gtask failed"); - return false; - // 再次尝试登录 - } - } - return true; - } - - private boolean loginGtask(String authToken) { - // 登录Google Tasks - int timeoutConnection = 10000; - // 连接超时10秒 - int timeoutSocket = 15000; - // Socket超时15秒 - HttpParams httpParameters = new BasicHttpParams(); - // HTTP参数 - HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); - // 设置连接超时 - HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); - // 设置Socket超时 - mHttpClient = new DefaultHttpClient(httpParameters); - // 创建HTTP客户端 - BasicCookieStore localBasicCookieStore = new BasicCookieStore(); - // Cookie存储 - mHttpClient.setCookieStore(localBasicCookieStore); - // 设置Cookie存储 - HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); - // 禁用Expect: 100-continue - - // 登录Google Tasks - try { - String loginUrl = mGetUrl + "?auth=" + authToken; - // 构建登录URL - HttpGet httpGet = new HttpGet(loginUrl); - // 创建GET请求 - HttpResponse response = null; - response = mHttpClient.execute(httpGet); - // 执行请求 - - // 获取Cookie - List cookies = mHttpClient.getCookieStore().getCookies(); - // 获取所有Cookie - boolean hasAuthCookie = false; - for (Cookie cookie : cookies) { - if (cookie.getName().contains("GTL")) { - hasAuthCookie = true; - // 检查是否有GTL认证Cookie - } - } - if (!hasAuthCookie) { - Log.w(TAG, "it seems that there is no auth cookie"); - // 没有认证Cookie - } - - // 获取客户端版本 - String resString = getResponseContent(response.getEntity()); - // 获取响应内容 - String jsBegin = "_setup("; - // JavaScript开始标记 - String jsEnd = ")}"; - // JavaScript结束标记 - int begin = resString.indexOf(jsBegin); - int end = resString.lastIndexOf(jsEnd); - String jsString = null; - if (begin != -1 && end != -1 && begin < end) { - jsString = resString.substring(begin + jsBegin.length(), end); - // 提取JavaScript内容 - } - JSONObject js = new JSONObject(jsString); - // 解析为JSON对象 - mClientVersion = js.getLong("v"); - // 获取客户端版本 - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return false; - } catch (Exception e) { - // 捕获所有异常 - Log.e(TAG, "httpget gtask_url failed"); - return false; - } - - return true; - } - - private int getActionId() { - // 获取操作ID - return mActionId++; - // 返回当前ID并自增 - } - - private HttpPost createHttpPost() { - // 创建HTTP POST请求 - HttpPost httpPost = new HttpPost(mPostUrl); - // 创建POST请求 - httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); - // 设置Content-Type - httpPost.setHeader("AT", "1"); - // 设置AT头部 - return httpPost; - } - - private String getResponseContent(HttpEntity entity) throws IOException { - // 获取响应内容 - String contentEncoding = null; - // 内容编码 - if (entity.getContentEncoding() != null) { - contentEncoding = entity.getContentEncoding().getValue(); - Log.d(TAG, "encoding: " + contentEncoding); - // 获取编码方式 - } - - InputStream input = entity.getContent(); - // 获取输入流 - if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { - input = new GZIPInputStream(entity.getContent()); - // GZIP解压 - } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { - Inflater inflater = new Inflater(true); - // Inflater解压器 - input = new InflaterInputStream(entity.getContent(), inflater); - // Deflate解压 - } - - try { - InputStreamReader isr = new InputStreamReader(input); - // 输入流读取器 - BufferedReader br = new BufferedReader(isr); - // 缓冲读取器 - StringBuilder sb = new StringBuilder(); - - while (true) { - String buff = br.readLine(); - // 读取一行 - if (buff == null) { - return sb.toString(); - // 读取完毕 - } - sb = sb.append(buff); - // 添加到字符串构建器 - } - } finally { - input.close(); - // 关闭输入流 - } - } - - private JSONObject postRequest(JSONObject js) throws NetworkFailureException { - // 发送POST请求 - if (!mLoggedin) { - Log.e(TAG, "please login first"); - throw new ActionFailureException("not logged in"); - // 未登录异常 - } - - HttpPost httpPost = createHttpPost(); - // 创建POST请求 - try { - LinkedList list = new LinkedList(); - // 创建参数列表 - list.add(new BasicNameValuePair("r", js.toString())); - // 添加JSON参数 - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); - // 创建表单实体 - httpPost.setEntity(entity); - // 设置请求实体 - - // 执行POST请求 - HttpResponse response = mHttpClient.execute(httpPost); - // 执行请求 - String jsString = getResponseContent(response.getEntity()); - // 获取响应内容 - return new JSONObject(jsString); - // 解析为JSON对象 - - } catch (ClientProtocolException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); - // 网络失败异常 - } catch (IOException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("unable to convert response content to jsonobject"); - // 操作失败异常 - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("error occurs when posting request"); - } - } - - public void createTask(Task task) throws NetworkFailureException { - // 创建任务 - commitUpdate(); - // 提交之前的更新 - try { - JSONObject jsPost = new JSONObject(); - // 创建POST JSON - JSONArray actionList = new JSONArray(); - // 操作列表 - - // action_list - 操作列表 - actionList.put(task.getCreateAction(getActionId())); - // 添加创建任务操作 - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - 客户端版本 - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // post - 发送请求 - JSONObject jsResponse = postRequest(jsPost); - // 发送请求 - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - // 获取结果 - task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); - // 设置任务ID - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create task: handing jsonobject failed"); - } - } - - public void createTaskList(TaskList tasklist) throws NetworkFailureException { - // 创建任务列表 - commitUpdate(); - // 提交之前的更新 - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // action_list - actionList.put(tasklist.getCreateAction(getActionId())); - // 添加创建任务列表操作 - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // post - JSONObject jsResponse = postRequest(jsPost); - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); - // 设置任务列表ID - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create tasklist: handing jsonobject failed"); - } - } - - public void commitUpdate() throws NetworkFailureException { - // 提交更新 - if (mUpdateArray != null) { - // 如果有待提交的更新 - try { - JSONObject jsPost = new JSONObject(); - - // action_list - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); - // 设置操作列表 - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - postRequest(jsPost); - // 发送请求 - mUpdateArray = null; - // 清空更新数组 - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("commit update: handing jsonobject failed"); - } - } - } - - public void addUpdateNode(Node node) throws NetworkFailureException { - // 添加更新节点 - if (node != null) { - // 太多更新项可能导致错误,最多10项 - if (mUpdateArray != null && mUpdateArray.length() > 10) { - commitUpdate(); - // 如果超过10项,先提交 - } - - if (mUpdateArray == null) - mUpdateArray = new JSONArray(); - // 创建新数组 - mUpdateArray.put(node.getUpdateAction(getActionId())); - // 添加更新操作 - } - } - - public void moveTask(Task task, TaskList preParent, TaskList curParent) - throws NetworkFailureException { - // 移动任务 - commitUpdate(); - // 提交之前的更新 - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - JSONObject action = new JSONObject(); - - // action_list - action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); - // 操作类型为移动 - action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); - // 操作ID - action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); - // 任务ID - if (preParent == curParent && task.getPriorSibling() != null) { - // 只有同一任务列表内移动且不是第一个时才设置前兄弟ID - action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); - } - action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); - // 源列表ID - action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); - // 目标父ID - if (preParent != curParent) { - // 只有在不同任务列表间移动时才设置目标列表 - action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); - } - actionList.put(action); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - postRequest(jsPost); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("move task: handing jsonobject failed"); - } - } - - public void deleteNode(Node node) throws NetworkFailureException { - // 删除节点 - commitUpdate(); - // 提交之前的更新 - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // action_list - node.setDeleted(true); - // 标记为删除 - actionList.put(node.getUpdateAction(getActionId())); - // 添加更新操作 - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - postRequest(jsPost); - // 发送请求 - mUpdateArray = null; - // 清空更新数组 - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("delete node: handing jsonobject failed"); - } - } - - public JSONArray getTaskLists() throws NetworkFailureException { - // 获取任务列表 - if (!mLoggedin) { - Log.e(TAG, "please login first"); - throw new ActionFailureException("not logged in"); - } - - try { - HttpGet httpGet = new HttpGet(mGetUrl); - // 创建GET请求 - HttpResponse response = null; - response = mHttpClient.execute(httpGet); - // 执行请求 - - // 获取任务列表 - String resString = getResponseContent(response.getEntity()); - // 获取响应内容 - String jsBegin = "_setup("; - String jsEnd = ")}"; - int begin = resString.indexOf(jsBegin); - int end = resString.lastIndexOf(jsEnd); - String jsString = null; - if (begin != -1 && end != -1 && begin < end) { - jsString = resString.substring(begin + jsBegin.length(), end); - // 提取JavaScript内容 - } - JSONObject js = new JSONObject(jsString); - // 解析JSON - return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); - // 返回任务列表数组 - - } catch (ClientProtocolException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("gettasklists: httpget failed"); - } catch (IOException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("gettasklists: httpget failed"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("get task lists: handing jasonobject failed"); - } - } - - public JSONArray getTaskList(String listGid) throws NetworkFailureException { - // 获取指定任务列表 - commitUpdate(); - // 提交之前的更新 - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - JSONObject action = new JSONObject(); - - // action_list - action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); - // 操作类型为获取全部 - action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); - // 操作ID - action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); - // 列表ID - action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); - // 不获取已删除的 - actionList.put(action); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - JSONObject jsResponse = postRequest(jsPost); - // 发送请求 - return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); - // 返回任务数组 - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("get task list: handing jsonobject failed"); - } - } - - public Account getSyncAccount() { - // 获取同步账户 - return mAccount; - } - - public void resetUpdateArray() { - // 重置更新数组 - mUpdateArray = null; - } -} diff --git a/src/gtask/remote/GTaskManager.java b/src/gtask/remote/GTaskManager.java deleted file mode 100644 index 0b16fca..0000000 --- a/src/gtask/remote/GTaskManager.java +++ /dev/null @@ -1,1002 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.remote; - -import android.app.Activity; -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.util.Log; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.data.MetaData; -import net.micode.notes.gtask.data.Node; -import net.micode.notes.gtask.data.SqlNote; -import net.micode.notes.gtask.data.Task; -import net.micode.notes.gtask.data.TaskList; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.gtask.exception.NetworkFailureException; -import net.micode.notes.tool.DataUtils; -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; - - -public class GTaskManager { -// Google任务管理器类,负责同步逻辑 - - private static final String TAG = GTaskManager.class.getSimpleName(); - // 日志标签 - - // 同步状态常量 - public static final int STATE_SUCCESS = 0; - // 同步成功 - - public static final int STATE_NETWORK_ERROR = 1; - // 网络错误 - - public static final int STATE_INTERNAL_ERROR = 2; - // 内部错误 - - public static final int STATE_SYNC_IN_PROGRESS = 3; - // 同步进行中 - - public static final int STATE_SYNC_CANCELLED = 4; - // 同步被取消 - - private static GTaskManager mInstance = null; - // 单例实例 - - // 成员变量 - private Activity mActivity; - // 活动上下文,用于获取授权令牌 - - private Context mContext; - // 应用上下文 - - private ContentResolver mContentResolver; - // 内容解析器 - - private boolean mSyncing; - // 同步状态标志 - - private boolean mCancelled; - // 取消标志 - - private HashMap mGTaskListHashMap; - // GID到任务列表的映射 - - private HashMap mGTaskHashMap; - // GID到节点(任务/任务列表)的映射 - - private HashMap mMetaHashMap; - // GID到元数据的映射 - - private TaskList mMetaList; - // 元数据任务列表 - - private HashSet mLocalDeleteIdMap; - // 本地删除的笔记ID集合 - - private HashMap mGidToNid; - // Google任务ID到本地笔记ID的映射 - - private HashMap mNidToGid; - // 本地笔记ID到Google任务ID的映射 - - private GTaskManager() { - // 构造方法 - mSyncing = false; - // 初始未同步 - mCancelled = false; - // 初始未取消 - mGTaskListHashMap = new HashMap(); - // 初始化任务列表映射 - mGTaskHashMap = new HashMap(); - // 初始化节点映射 - mMetaHashMap = new HashMap(); - // 初始化元数据映射 - mMetaList = null; - // 元数据列表初始为空 - mLocalDeleteIdMap = new HashSet(); - // 初始化本地删除ID集合 - mGidToNid = new HashMap(); - // 初始化GID到NID映射 - mNidToGid = new HashMap(); - // 初始化NID到GID映射 - } - - public static synchronized GTaskManager getInstance() { - // 获取单例实例 - if (mInstance == null) { - mInstance = new GTaskManager(); - // 创建新实例 - } - return mInstance; - } - - public synchronized void setActivityContext(Activity activity) { - // 设置活动上下文 - // 用于获取授权令牌 - mActivity = activity; - } - - public int sync(Context context, GTaskASyncTask asyncTask) { - // 执行同步 - if (mSyncing) { - Log.d(TAG, "Sync is in progress"); - return STATE_SYNC_IN_PROGRESS; - // 如果正在同步,返回状态 - } - mContext = context; - // 保存上下文 - mContentResolver = mContext.getContentResolver(); - // 获取内容解析器 - mSyncing = true; - // 标记为同步中 - mCancelled = false; - // 重置取消标志 - mGTaskListHashMap.clear(); - // 清空任务列表映射 - mGTaskHashMap.clear(); - // 清空节点映射 - mMetaHashMap.clear(); - // 清空元数据映射 - mLocalDeleteIdMap.clear(); - // 清空本地删除集合 - mGidToNid.clear(); - // 清空GID到NID映射 - mNidToGid.clear(); - // 清空NID到GID映射 - - try { - GTaskClient client = GTaskClient.getInstance(); - // 获取Google任务客户端 - client.resetUpdateArray(); - // 重置更新数组 - - // 登录Google任务 - if (!mCancelled) { - if (!client.login(mActivity)) { - throw new NetworkFailureException("login google task failed"); - // 登录失败 - } - } - - // 从Google获取任务列表 - asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); - // 发布初始化列表进度 - initGTaskList(); - // 初始化Google任务列表 - - // 执行内容同步工作 - asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); - // 发布同步中进度 - syncContent(); - // 同步内容 - } catch (NetworkFailureException e) { - Log.e(TAG, e.toString()); - return STATE_NETWORK_ERROR; - // 网络错误 - } catch (ActionFailureException e) { - Log.e(TAG, e.toString()); - return STATE_INTERNAL_ERROR; - // 内部错误 - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return STATE_INTERNAL_ERROR; - // 其他异常 - } finally { - // 清理资源 - mGTaskListHashMap.clear(); - mGTaskHashMap.clear(); - mMetaHashMap.clear(); - mLocalDeleteIdMap.clear(); - mGidToNid.clear(); - mNidToGid.clear(); - mSyncing = false; - // 标记同步结束 - } - - return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; - // 返回同步结果 - } - - private void initGTaskList() throws NetworkFailureException { - // 初始化Google任务列表 - if (mCancelled) - return; - // 如果已取消,直接返回 - GTaskClient client = GTaskClient.getInstance(); - try { - JSONArray jsTaskLists = client.getTaskLists(); - // 获取任务列表 - - // 先初始化元数据列表 - mMetaList = null; - for (int i = 0; i < jsTaskLists.length(); i++) { - JSONObject object = jsTaskLists.getJSONObject(i); - String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - // 获取GID - String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); - // 获取名称 - - if (name - .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { - // 如果是元数据文件夹 - mMetaList = new TaskList(); - // 创建任务列表 - mMetaList.setContentByRemoteJSON(object); - // 根据远程JSON设置内容 - - // 加载元数据 - JSONArray jsMetas = client.getTaskList(gid); - // 获取元数据任务列表 - for (int j = 0; j < jsMetas.length(); j++) { - object = (JSONObject) jsMetas.getJSONObject(j); - MetaData metaData = new MetaData(); - // 创建元数据 - metaData.setContentByRemoteJSON(object); - // 设置内容 - if (metaData.isWorthSaving()) { - // 如果值得保存 - mMetaList.addChildTask(metaData); - // 添加到任务列表 - if (metaData.getGid() != null) { - mMetaHashMap.put(metaData.getRelatedGid(), metaData); - // 添加到元数据映射 - } - } - } - } - } - - // 如果不存在元数据列表,则创建 - if (mMetaList == null) { - mMetaList = new TaskList(); - mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META); - // 设置名称为元数据文件夹 - GTaskClient.getInstance().createTaskList(mMetaList); - // 创建任务列表 - } - - // 初始化任务列表 - for (int i = 0; i < jsTaskLists.length(); i++) { - JSONObject object = jsTaskLists.getJSONObject(i); - String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); - - if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) - && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META)) { - // 如果是MIUI文件夹且不是元数据文件夹 - TaskList tasklist = new TaskList(); - tasklist.setContentByRemoteJSON(object); - // 根据远程JSON设置内容 - mGTaskListHashMap.put(gid, tasklist); - // 添加到任务列表映射 - mGTaskHashMap.put(gid, tasklist); - // 添加到节点映射 - - // 加载任务 - JSONArray jsTasks = client.getTaskList(gid); - // 获取任务列表中的任务 - for (int j = 0; j < jsTasks.length(); j++) { - object = (JSONObject) jsTasks.getJSONObject(j); - gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - // 获取任务GID - Task task = new Task(); - // 创建任务 - task.setContentByRemoteJSON(object); - // 设置内容 - if (task.isWorthSaving()) { - // 如果值得保存 - task.setMetaInfo(mMetaHashMap.get(gid)); - // 设置元数据信息 - tasklist.addChildTask(task); - // 添加到任务列表 - mGTaskHashMap.put(gid, task); - // 添加到节点映射 - } - } - } - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("initGTaskList: handing JSONObject failed"); - // JSON处理失败 - } - } - - private void syncContent() throws NetworkFailureException { - // 同步内容 - int syncType; - // 同步类型 - Cursor c = null; - String gid; - Node node; - - mLocalDeleteIdMap.clear(); - // 清空本地删除ID集合 - - if (mCancelled) { - return; - // 如果已取消,直接返回 - } - - // 处理本地删除的笔记 - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type<>? AND parent_id=?)", new String[] { - String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) - }, null); - // 查询垃圾箱中的笔记(非系统类型) - if (c != null) { - while (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - // 获取Google任务ID - node = mGTaskHashMap.get(gid); - // 获取节点 - if (node != null) { - mGTaskHashMap.remove(gid); - // 从映射中移除 - doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); - // 执行删除远程操作 - } - - mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); - // 添加到本地删除集合 - } - } else { - Log.w(TAG, "failed to query trash folder"); - // 查询失败 - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // 先同步文件夹 - syncFolder(); - - // 处理数据库中已存在的笔记 - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type=? AND parent_id<>?)", new String[] { - String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) - }, NoteColumns.TYPE + " DESC"); - // 查询不在垃圾箱中的笔记 - if (c != null) { - while (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - // 获取Google任务ID - node = mGTaskHashMap.get(gid); - // 获取节点 - if (node != null) { - mGTaskHashMap.remove(gid); - // 从映射中移除 - mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); - // 添加GID到NID映射 - mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); - // 添加NID到GID映射 - syncType = node.getSyncAction(c); - // 获取同步类型 - } else { - if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { - // 本地添加(没有Google任务ID) - syncType = Node.SYNC_ACTION_ADD_REMOTE; - } else { - // 远程删除(有Google任务ID但不在远程) - syncType = Node.SYNC_ACTION_DEL_LOCAL; - } - } - doContentSync(syncType, node, c); - // 执行内容同步 - } - } else { - Log.w(TAG, "failed to query existing note in database"); - // 查询失败 - } - - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // 处理剩余的项(远程有但本地没有) - Iterator> iter = mGTaskHashMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - node = entry.getValue(); - doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); - // 添加本地节点 - } - - // mCancelled可以被另一个线程设置,所以需要逐个检查 - // 清理本地删除表 - if (!mCancelled) { - if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { - throw new ActionFailureException("failed to batch-delete local deleted notes"); - // 批量删除失败 - } - } - - // 刷新本地同步ID - if (!mCancelled) { - GTaskClient.getInstance().commitUpdate(); - // 提交更新 - refreshLocalSyncId(); - // 刷新本地同步ID - } - - } - - private void syncFolder() throws NetworkFailureException { - // 同步文件夹 - Cursor c = null; - String gid; - Node node; - int syncType; - - if (mCancelled) { - return; - } - - // 处理根文件夹 - try { - c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, - Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); - // 查询根文件夹 - if (c != null) { - c.moveToNext(); - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); - // 添加映射 - mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); - // 对于系统文件夹,只在必要时更新远程名称 - if (!node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) - doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); - // 更新远程 - } else { - doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); - // 添加远程 - } - } else { - Log.w(TAG, "failed to query root folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // 处理通话记录文件夹 - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", - new String[] { - String.valueOf(Notes.ID_CALL_RECORD_FOLDER) - }, null); - // 查询通话记录文件夹 - if (c != null) { - if (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); - mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); - // 对于系统文件夹,只在必要时更新远程名称 - if (!node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_CALL_NOTE)) - doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); - } else { - doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); - } - } - } else { - Log.w(TAG, "failed to query call note folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // 处理本地已存在的文件夹 - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type=? AND parent_id<>?)", new String[] { - String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) - }, NoteColumns.TYPE + " DESC"); - // 查询不在垃圾箱中的文件夹 - if (c != null) { - while (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); - mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); - syncType = node.getSyncAction(c); - // 获取同步类型 - } else { - if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { - // 本地添加 - syncType = Node.SYNC_ACTION_ADD_REMOTE; - } else { - // 远程删除 - syncType = Node.SYNC_ACTION_DEL_LOCAL; - } - } - doContentSync(syncType, node, c); - // 执行内容同步 - } - } else { - Log.w(TAG, "failed to query existing folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // 处理远程添加的文件夹 - Iterator> iter = mGTaskListHashMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - gid = entry.getKey(); - node = entry.getValue(); - if (mGTaskHashMap.containsKey(gid)) { - mGTaskHashMap.remove(gid); - doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); - // 添加本地文件夹 - } - } - - if (!mCancelled) - GTaskClient.getInstance().commitUpdate(); - // 提交更新 - } - - private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { - // 执行内容同步 - if (mCancelled) { - return; - } - - MetaData meta; - switch (syncType) { - case Node.SYNC_ACTION_ADD_LOCAL: - addLocalNode(node); - // 添加本地节点 - break; - case Node.SYNC_ACTION_ADD_REMOTE: - addRemoteNode(node, c); - // 添加远程节点 - break; - case Node.SYNC_ACTION_DEL_LOCAL: - meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN)); - if (meta != null) { - GTaskClient.getInstance().deleteNode(meta); - // 删除元数据 - } - mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); - // 添加到本地删除集合 - break; - case Node.SYNC_ACTION_DEL_REMOTE: - meta = mMetaHashMap.get(node.getGid()); - if (meta != null) { - GTaskClient.getInstance().deleteNode(meta); - // 删除元数据 - } - GTaskClient.getInstance().deleteNode(node); - // 删除节点 - break; - case Node.SYNC_ACTION_UPDATE_LOCAL: - updateLocalNode(node, c); - // 更新本地节点 - break; - case Node.SYNC_ACTION_UPDATE_REMOTE: - updateRemoteNode(node, c); - // 更新远程节点 - break; - case Node.SYNC_ACTION_UPDATE_CONFLICT: - // 合并双方的修改可能是个好主意 - // 目前只简单地使用本地更新 - updateRemoteNode(node, c); - // 更新远程节点 - break; - case Node.SYNC_ACTION_NONE: - break; - // 无操作 - case Node.SYNC_ACTION_ERROR: - default: - throw new ActionFailureException("unkown sync action type"); - // 未知同步类型 - } - } - - private void addLocalNode(Node node) throws NetworkFailureException { - // 添加本地节点 - if (mCancelled) { - return; - } - - SqlNote sqlNote; - if (node instanceof TaskList) { - // 如果是任务列表(文件夹) - if (node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { - sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); - // 根文件夹 - } else if (node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { - sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); - // 通话记录文件夹 - } else { - sqlNote = new SqlNote(mContext); - sqlNote.setContent(node.getLocalJSONFromContent()); - // 设置内容 - sqlNote.setParentId(Notes.ID_ROOT_FOLDER); - // 设置父ID为根文件夹 - } - } else { - // 如果是任务 - sqlNote = new SqlNote(mContext); - JSONObject js = node.getLocalJSONFromContent(); - try { - if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { - JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - if (note.has(NoteColumns.ID)) { - long id = note.getLong(NoteColumns.ID); - if (DataUtils.existInNoteDatabase(mContentResolver, id)) { - // ID不可用,需要创建新的 - note.remove(NoteColumns.ID); - // 移除ID - } - } - } - - if (js.has(GTaskStringUtils.META_HEAD_DATA)) { - JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - if (data.has(DataColumns.ID)) { - long dataId = data.getLong(DataColumns.ID); - if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { - // 数据ID不可用,需要创建新的 - data.remove(DataColumns.ID); - // 移除数据ID - } - } - } - - } - } catch (JSONException e) { - Log.w(TAG, e.toString()); - e.printStackTrace(); - } - sqlNote.setContent(js); - - Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); - // 获取父文件夹ID - if (parentId == null) { - Log.e(TAG, "cannot find task's parent id locally"); - throw new ActionFailureException("cannot add local node"); - } - sqlNote.setParentId(parentId.longValue()); - // 设置父ID - } - - // 创建本地节点 - sqlNote.setGtaskId(node.getGid()); - // 设置Google任务ID - sqlNote.commit(false); - // 提交 - - // 更新GID-NID映射 - mGidToNid.put(node.getGid(), sqlNote.getId()); - mNidToGid.put(sqlNote.getId(), node.getGid()); - - // 更新元数据 - updateRemoteMeta(node.getGid(), sqlNote); - } - - private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { - // 更新本地节点 - if (mCancelled) { - return; - } - - SqlNote sqlNote; - // 在本地更新笔记 - sqlNote = new SqlNote(mContext, c); - sqlNote.setContent(node.getLocalJSONFromContent()); - // 设置内容 - - Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) - : new Long(Notes.ID_ROOT_FOLDER); - // 获取父ID - if (parentId == null) { - Log.e(TAG, "cannot find task's parent id locally"); - throw new ActionFailureException("cannot update local node"); - } - sqlNote.setParentId(parentId.longValue()); - // 设置父ID - sqlNote.commit(true); - // 提交(验证版本) - - // 更新元数据信息 - updateRemoteMeta(node.getGid(), sqlNote); - } - - private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { - // 添加远程节点 - if (mCancelled) { - return; - } - - SqlNote sqlNote = new SqlNote(mContext, c); - Node n; - - // 远程更新 - if (sqlNote.isNoteType()) { - // 如果是笔记类型 - Task task = new Task(); - task.setContentByLocalJSON(sqlNote.getContent()); - // 根据本地JSON设置内容 - - String parentGid = mNidToGid.get(sqlNote.getParentId()); - // 获取父文件夹的GID - if (parentGid == null) { - Log.e(TAG, "cannot find task's parent tasklist"); - throw new ActionFailureException("cannot add remote task"); - } - mGTaskListHashMap.get(parentGid).addChildTask(task); - // 添加到父任务列表 - - GTaskClient.getInstance().createTask(task); - // 创建远程任务 - n = (Node) task; - - // 添加元数据 - updateRemoteMeta(task.getGid(), sqlNote); - } else { - // 如果是文件夹类型 - TaskList tasklist = null; - - // 如果文件夹已存在,需要跳过 - String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX; - // 构建文件夹名称 - if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) - folderName += GTaskStringUtils.FOLDER_DEFAULT; - // 根文件夹 - else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER) - folderName += GTaskStringUtils.FOLDER_CALL_NOTE; - // 通话记录文件夹 - else - folderName += sqlNote.getSnippet(); - // 普通文件夹 - - Iterator> iter = mGTaskListHashMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - String gid = entry.getKey(); - TaskList list = entry.getValue(); - - if (list.getName().equals(folderName)) { - tasklist = list; - if (mGTaskHashMap.containsKey(gid)) { - mGTaskHashMap.remove(gid); - // 从映射中移除 - } - break; - } - } - - // 没有匹配项,现在可以添加 - if (tasklist == null) { - tasklist = new TaskList(); - tasklist.setContentByLocalJSON(sqlNote.getContent()); - // 根据本地JSON设置内容 - GTaskClient.getInstance().createTaskList(tasklist); - // 创建远程任务列表 - mGTaskListHashMap.put(tasklist.getGid(), tasklist); - // 添加到映射 - } - n = (Node) tasklist; - } - - // 更新本地笔记 - sqlNote.setGtaskId(n.getGid()); - // 设置Google任务ID - sqlNote.commit(false); - // 提交 - sqlNote.resetLocalModified(); - // 重置本地修改标志 - sqlNote.commit(true); - // 提交(验证版本) - - // GID-ID映射 - mGidToNid.put(n.getGid(), sqlNote.getId()); - mNidToGid.put(sqlNote.getId(), n.getGid()); - } - - private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { - // 更新远程节点 - if (mCancelled) { - return; - } - - SqlNote sqlNote = new SqlNote(mContext, c); - - // 远程更新 - node.setContentByLocalJSON(sqlNote.getContent()); - // 根据本地JSON设置内容 - GTaskClient.getInstance().addUpdateNode(node); - // 添加更新节点 - - // 更新元数据 - updateRemoteMeta(node.getGid(), sqlNote); - - // 如果需要,移动任务 - if (sqlNote.isNoteType()) { - Task task = (Task) node; - TaskList preParentList = task.getParent(); - // 原来的父列表 - - String curParentGid = mNidToGid.get(sqlNote.getParentId()); - // 当前父文件夹的GID - if (curParentGid == null) { - Log.e(TAG, "cannot find task's parent tasklist"); - throw new ActionFailureException("cannot update remote task"); - } - TaskList curParentList = mGTaskListHashMap.get(curParentGid); - // 当前父列表 - - if (preParentList != curParentList) { - // 如果父文件夹发生了变化 - preParentList.removeChildTask(task); - // 从原父列表移除 - curParentList.addChildTask(task); - // 添加到新父列表 - GTaskClient.getInstance().moveTask(task, preParentList, curParentList); - // 移动任务 - } - } - - // 清除本地修改标志 - sqlNote.resetLocalModified(); - // 重置本地修改标志 - sqlNote.commit(true); - // 提交(验证版本) - } - - private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { - // 更新远程元数据 - if (sqlNote != null && sqlNote.isNoteType()) { - // 如果是笔记类型 - MetaData metaData = mMetaHashMap.get(gid); - // 获取元数据 - if (metaData != null) { - metaData.setMeta(gid, sqlNote.getContent()); - // 设置元数据 - GTaskClient.getInstance().addUpdateNode(metaData); - // 添加更新 - } else { - metaData = new MetaData(); - metaData.setMeta(gid, sqlNote.getContent()); - // 设置元数据 - mMetaList.addChildTask(metaData); - // 添加到元数据列表 - mMetaHashMap.put(gid, metaData); - // 添加到映射 - GTaskClient.getInstance().createTask(metaData); - // 创建远程元数据任务 - } - } - } - - private void refreshLocalSyncId() throws NetworkFailureException { - // 刷新本地同步ID - if (mCancelled) { - return; - } - - // 获取最新的Google任务列表 - mGTaskHashMap.clear(); - mGTaskListHashMap.clear(); - mMetaHashMap.clear(); - // 清空映射 - initGTaskList(); - // 重新初始化 - - Cursor c = null; - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type<>? AND parent_id<>?)", new String[] { - String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) - }, NoteColumns.TYPE + " DESC"); - // 查询不在垃圾箱中的非系统笔记和文件夹 - if (c != null) { - while (c.moveToNext()) { - String gid = c.getString(SqlNote.GTASK_ID_COLUMN); - Node node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - ContentValues values = new ContentValues(); - values.put(NoteColumns.SYNC_ID, node.getLastModified()); - // 设置同步ID为最后修改时间 - mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, - c.getLong(SqlNote.ID_COLUMN)), values, null, null); - // 更新数据库 - } else { - Log.e(TAG, "something is missed"); - throw new ActionFailureException( - "some local items don't have gid after sync"); - // 同步后某些本地项没有GID - } - } - } else { - Log.w(TAG, "failed to query local note to refresh sync id"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - } - - public String getSyncAccount() { - // 获取同步账户名 - return GTaskClient.getInstance().getSyncAccount().name; - } - - public void cancelSync() { - // 取消同步 - mCancelled = true; - // 设置取消标志 - } -} \ No newline at end of file diff --git a/src/gtask/remote/GTaskSyncService.java b/src/gtask/remote/GTaskSyncService.java deleted file mode 100644 index 92d703f..0000000 --- a/src/gtask/remote/GTaskSyncService.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.remote; - -import android.app.Activity; -import android.app.Service; -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.os.IBinder; - -public class GTaskSyncService extends Service { -// Google任务同步服务,继承Service - - // 动作字符串常量 - public final static String ACTION_STRING_NAME = "sync_action_type"; - // Intent中的动作键名 - - // 动作类型常量 - public final static int ACTION_START_SYNC = 0; - // 开始同步 - - public final static int ACTION_CANCEL_SYNC = 1; - // 取消同步 - - public final static int ACTION_INVALID = 2; - // 无效动作 - - // 广播相关常量 - public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; - // 广播名称 - - public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; - // 是否正在同步的广播键名 - - public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; - // 进度消息的广播键名 - - // 静态成员变量 - private static GTaskASyncTask mSyncTask = null; - // 同步任务实例(静态,确保只有一个同步任务) - - private static String mSyncProgress = ""; - // 同步进度消息 - - private void startSync() { - // 开始同步方法 - if (mSyncTask == null) { - // 如果当前没有同步任务 - mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { - // 创建异步任务,传入完成监听器 - public void onComplete() { - // 同步完成回调 - mSyncTask = null; - // 清空任务引用 - sendBroadcast(""); - // 发送空广播通知完成 - stopSelf(); - // 停止服务 - } - }); - sendBroadcast(""); - // 发送广播通知开始同步 - mSyncTask.execute(); - // 执行异步任务 - } - } - - private void cancelSync() { - // 取消同步方法 - if (mSyncTask != null) { - // 如果存在同步任务 - mSyncTask.cancelSync(); - // 取消同步 - } - } - - @Override - public void onCreate() { - // 服务创建时调用 - mSyncTask = null; - // 初始化同步任务为空 - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - // 服务启动命令处理 - Bundle bundle = intent.getExtras(); - // 获取Intent中的附加数据 - if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { - // 如果包含动作键 - switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { - // 根据动作类型处理 - case ACTION_START_SYNC: - startSync(); - // 开始同步 - break; - case ACTION_CANCEL_SYNC: - cancelSync(); - // 取消同步 - break; - default: - break; - } - return START_STICKY; - // 返回STICKY,表示服务被杀死后会重新创建 - } - return super.onStartCommand(intent, flags, startId); - // 调用父类方法 - } - - @Override - public void onLowMemory() { - // 低内存时调用 - if (mSyncTask != null) { - mSyncTask.cancelSync(); - // 低内存时取消同步 - } - } - - public IBinder onBind(Intent intent) { - // 绑定服务(此服务不需要绑定) - return null; - // 返回null,表示不支持绑定 - } - - public void sendBroadcast(String msg) { - // 发送广播方法 - mSyncProgress = msg; - // 保存进度消息 - Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); - // 创建广播Intent - intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); - // 添加是否正在同步的状态 - intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); - // 添加进度消息 - sendBroadcast(intent); - // 发送广播 - } - - // 静态工具方法 - public static void startSync(Activity activity) { - // 启动同步的静态方法(供外部调用) - GTaskManager.getInstance().setActivityContext(activity); - // 设置活动上下文到GTaskManager - Intent intent = new Intent(activity, GTaskSyncService.class); - // 创建服务Intent - intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); - // 添加开始同步动作 - activity.startService(intent); - // 启动服务 - } - - public static void cancelSync(Context context) { - // 取消同步的静态方法 - Intent intent = new Intent(context, GTaskSyncService.class); - intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); - context.startService(intent); - } - - public static boolean isSyncing() { - // 检查是否正在同步 - return mSyncTask != null; - // 通过判断同步任务是否存在 - } - - public static String getProgressString() { - // 获取进度字符串 - return mSyncProgress; - // 返回当前进度消息 - } -} \ No newline at end of file diff --git a/src/model/Note.java b/src/model/Note.java new file mode 100644 index 0000000..629c9b2 --- /dev/null +++ b/src/model/Note.java @@ -0,0 +1,377 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.model; +import android.content.ContentProviderOperation; +import android.content.ContentProviderResult; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.content.OperationApplicationException; +import android.net.Uri; +import android.os.RemoteException; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.Notes.TextNote; + +import java.util.ArrayList; + + + +public class Note { +// 笔记类,用于管理笔记的创建和更新 + + private ContentValues mNoteDiffValues; + // 笔记差异值,存储需要更新的笔记字段 + + private NoteData mNoteData; + // 笔记数据对象,管理文本和通话数据 + + private static final String TAG = "Note"; + // 日志标签 + + /** + * Create a new note id for adding a new note to databases + */ + // 创建新笔记ID,用于向数据库添加新笔记 + public static synchronized long getNewNoteId(Context context, long folderId) { + // 同步方法,确保线程安全 + // Create a new note in the database + // 在数据库中创建新笔记 + ContentValues values = new ContentValues(); + // 创建ContentValues存储数据 + long createdTime = System.currentTimeMillis(); + // 获取当前时间作为创建时间 + values.put(NoteColumns.CREATED_DATE, createdTime); + // 设置创建时间 + values.put(NoteColumns.MODIFIED_DATE, createdTime); + // 设置修改时间 + values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + // 设置类型为普通笔记 + values.put(NoteColumns.LOCAL_MODIFIED, 1); + // 设置本地修改标志为1 + values.put(NoteColumns.PARENT_ID, folderId); + // 设置父文件夹ID + Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); + // 插入数据库并获取URI + + long noteId = 0; + // 笔记ID初始化为0 + try { + noteId = Long.valueOf(uri.getPathSegments().get(1)); + // 从URI中提取笔记ID(第二个路径段) + } catch (NumberFormatException e) { + Log.e(TAG, "Get note id error :" + e.toString()); + // 记录错误日志 + noteId = 0; + } + if (noteId == -1) { + throw new IllegalStateException("Wrong note id:" + noteId); + // 如果笔记ID为-1,抛出异常 + } + return noteId; + // 返回笔记ID + } + + public Note() { + // 构造方法 + mNoteDiffValues = new ContentValues(); + // 初始化笔记差异值 + mNoteData = new NoteData(); + // 初始化笔记数据对象 + } + + public void setNoteValue(String key, String value) { + // 设置笔记值 + mNoteDiffValues.put(key, value); + // 将键值对存入差异值 + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + // 设置本地修改标志为1 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + // 设置修改时间为当前时间 + } + + public void setTextData(String key, String value) { + // 设置文本数据 + mNoteData.setTextData(key, value); + // 调用NoteData的setTextData方法 + } + + public void setTextDataId(long id) { + // 设置文本数据ID + mNoteData.setTextDataId(id); + // 调用NoteData的setTextDataId方法 + } + + public long getTextDataId() { + // 获取文本数据ID + return mNoteData.mTextDataId; + // 返回NoteData中的文本数据ID + } + + public void setCallDataId(long id) { + // 设置通话数据ID + mNoteData.setCallDataId(id); + // 调用NoteData的setCallDataId方法 + } + + public void setCallData(String key, String value) { + // 设置通话数据 + mNoteData.setCallData(key, value); + // 调用NoteData的setCallData方法 + } + + public boolean isLocalModified() { + // 检查是否有本地修改 + return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); + // 如果笔记差异值非空或NoteData有修改,返回true + } + + public boolean syncNote(Context context, long noteId) { + // 同步笔记到数据库 + if (noteId <= 0) { + throw new IllegalArgumentException("Wrong note id:" + noteId); + // 检查笔记ID是否有效 + } + + if (!isLocalModified()) { + return true; + // 如果没有本地修改,直接返回成功 + } + + /** + * In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and + * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the + * note data info + */ + // 理论上,数据改变后应该更新LOCAL_MODIFIED和MODIFIED_DATE字段 + // 为了数据安全,即使笔记更新失败,也更新笔记数据信息 + if (context.getContentResolver().update( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, + null) == 0) { + // 更新笔记表 + Log.e(TAG, "Update note error, should not happen"); + // 记录错误日志(理论上不应该发生) + // Do not return, fall through + // 不返回,继续执行 + } + mNoteDiffValues.clear(); + // 清空笔记差异值 + + if (mNoteData.isLocalModified() + && (mNoteData.pushIntoContentResolver(context, noteId) == null)) { + // 如果NoteData有修改且推送数据失败 + return false; + // 返回失败 + } + + return true; + // 返回成功 + } + + private class NoteData { + // 内部类NoteData,管理笔记的详细数据 + + private long mTextDataId; + // 文本数据ID + + private ContentValues mTextDataValues; + // 文本数据差异值 + + private long mCallDataId; + // 通话数据ID + + private ContentValues mCallDataValues; + // 通话数据差异值 + + private static final String TAG = "NoteData"; + // 日志标签 + + public NoteData() { + // 构造方法 + mTextDataValues = new ContentValues(); + // 初始化文本数据差异值 + mCallDataValues = new ContentValues(); + // 初始化通话数据差异值 + mTextDataId = 0; + // 文本数据ID初始为0 + mCallDataId = 0; + // 通话数据ID初始为0 + } + + boolean isLocalModified() { + // 检查是否有本地修改 + return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; + // 如果文本或通话数据差异值非空,返回true + } + + void setTextDataId(long id) { + // 设置文本数据ID + if(id <= 0) { + throw new IllegalArgumentException("Text data id should larger than 0"); + // 检查ID是否大于0 + } + mTextDataId = id; + // 设置文本数据ID + } + + void setCallDataId(long id) { + // 设置通话数据ID + if (id <= 0) { + throw new IllegalArgumentException("Call data id should larger than 0"); + // 检查ID是否大于0 + } + mCallDataId = id; + // 设置通话数据ID + } + + void setCallData(String key, String value) { + // 设置通话数据 + mCallDataValues.put(key, value); + // 将键值对存入通话数据差异值 + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + // 设置笔记的本地修改标志 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + // 设置笔记的修改时间 + } + + void setTextData(String key, String value) { + // 设置文本数据 + mTextDataValues.put(key, value); + // 将键值对存入文本数据差异值 + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + // 设置笔记的本地修改标志 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + // 设置笔记的修改时间 + } + + Uri pushIntoContentResolver(Context context, long noteId) { + // 将数据推送到内容解析器 + /** + * Check for safety + */ + // 安全检查 + if (noteId <= 0) { + throw new IllegalArgumentException("Wrong note id:" + noteId); + // 检查笔记ID是否有效 + } + + ArrayList operationList = new ArrayList(); + // 创建操作列表 + ContentProviderOperation.Builder builder = null; + // 操作构建器 + + if(mTextDataValues.size() > 0) { + // 如果有文本数据需要更新 + mTextDataValues.put(DataColumns.NOTE_ID, noteId); + // 设置笔记ID + if (mTextDataId == 0) { + // 如果文本数据ID为0,表示是新的文本数据 + mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); + // 设置MIME类型为文本笔记 + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, + mTextDataValues); + // 插入数据并获取URI + try { + setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); + // 从URI中提取数据ID并设置 + } catch (NumberFormatException e) { + Log.e(TAG, "Insert new text data fail with noteId" + noteId); + // 记录错误日志 + mTextDataValues.clear(); + // 清空文本数据差异值 + return null; + // 返回null表示失败 + } + } else { + // 如果文本数据ID已存在,表示是更新操作 + builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mTextDataId)); + // 创建更新操作 + builder.withValues(mTextDataValues); + // 设置更新值 + operationList.add(builder.build()); + // 添加到操作列表 + } + mTextDataValues.clear(); + // 清空文本数据差异值 + } + + if(mCallDataValues.size() > 0) { + // 如果有通话数据需要更新 + mCallDataValues.put(DataColumns.NOTE_ID, noteId); + // 设置笔记ID + if (mCallDataId == 0) { + // 如果通话数据ID为0,表示是新的通话数据 + mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); + // 设置MIME类型为通话笔记 + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, + mCallDataValues); + // 插入数据并获取URI + try { + setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); + // 从URI中提取数据ID并设置 + } catch (NumberFormatException e) { + Log.e(TAG, "Insert new call data fail with noteId" + noteId); + // 记录错误日志 + mCallDataValues.clear(); + // 清空通话数据差异值 + return null; + // 返回null表示失败 + } + } else { + // 如果通话数据ID已存在,表示是更新操作 + builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mCallDataId)); + // 创建更新操作 + builder.withValues(mCallDataValues); + // 设置更新值 + operationList.add(builder.build()); + // 添加到操作列表 + } + mCallDataValues.clear(); + // 清空通话数据差异值 + } + + if (operationList.size() > 0) { + // 如果操作列表非空 + try { + ContentProviderResult[] results = context.getContentResolver().applyBatch( + Notes.AUTHORITY, operationList); + // 批量执行操作 + return (results == null || results.length == 0 || results[0] == null) ? null + : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); + // 如果结果有效,返回笔记URI;否则返回null + } catch (RemoteException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + // 记录远程异常 + return null; + } catch (OperationApplicationException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + // 记录操作应用异常 + return null; + } + } + return null; + // 如果操作列表为空,返回null + } + } +} +``` \ No newline at end of file diff --git a/src/model/WorkingNote.java b/src/model/WorkingNote.java new file mode 100644 index 0000000..112f90d --- /dev/null +++ b/src/model/WorkingNote.java @@ -0,0 +1,530 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.model; + +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.database.Cursor; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.Notes.TextNote; +import net.micode.notes.tool.ResourceParser.NoteBgResources; + + +public class WorkingNote { +// 工作笔记类,处理笔记的创建、加载和修改 + + // Note for the working note + // 工作笔记的Note对象 + private Note mNote; + + // Note Id + // 笔记ID + private long mNoteId; + + // Note content + // 笔记内容 + private String mContent; + + // Note mode + // 笔记模式(普通模式或清单模式) + private int mMode; + + private long mAlertDate; + // 提醒日期 + + private long mModifiedDate; + // 修改日期 + + private int mBgColorId; + // 背景颜色ID + + private int mWidgetId; + // 小部件ID + + private int mWidgetType; + // 小部件类型 + + private long mFolderId; + // 文件夹ID + + private Context mContext; + // 上下文 + + private static final String TAG = "WorkingNote"; + // 日志标签 + + private boolean mIsDeleted; + // 删除标记 + + private NoteSettingChangedListener mNoteSettingStatusListener; + // 笔记设置变化监听器 + + // 数据表投影列数组 + public static final String[] DATA_PROJECTION = new String[] { + DataColumns.ID, // 数据ID + DataColumns.CONTENT, // 内容 + DataColumns.MIME_TYPE, // MIME类型 + DataColumns.DATA1, // 数据1 + DataColumns.DATA2, // 数据2 + DataColumns.DATA3, // 数据3 + DataColumns.DATA4, // 数据4 + }; + + // 笔记表投影列数组 + public static final String[] NOTE_PROJECTION = new String[] { + NoteColumns.PARENT_ID, // 父文件夹ID + NoteColumns.ALERTED_DATE, // 提醒日期 + NoteColumns.BG_COLOR_ID, // 背景颜色ID + NoteColumns.WIDGET_ID, // 小部件ID + NoteColumns.WIDGET_TYPE, // 小部件类型 + NoteColumns.MODIFIED_DATE // 修改日期 + }; + + // 数据投影列索引 + private static final int DATA_ID_COLUMN = 0; + // 数据ID列索引 + + private static final int DATA_CONTENT_COLUMN = 1; + // 内容列索引 + + private static final int DATA_MIME_TYPE_COLUMN = 2; + // MIME类型列索引 + + private static final int DATA_MODE_COLUMN = 3; + // 模式列索引(对应DATA1字段) + + // 笔记投影列索引 + private static final int NOTE_PARENT_ID_COLUMN = 0; + // 父ID列索引 + + private static final int NOTE_ALERTED_DATE_COLUMN = 1; + // 提醒日期列索引 + + private static final int NOTE_BG_COLOR_ID_COLUMN = 2; + // 背景颜色ID列索引 + + private static final int NOTE_WIDGET_ID_COLUMN = 3; + // 小部件ID列索引 + + private static final int NOTE_WIDGET_TYPE_COLUMN = 4; + // 小部件类型列索引 + + private static final int NOTE_MODIFIED_DATE_COLUMN = 5; + // 修改日期列索引 + + // New note construct + // 新建笔记构造方法 + private WorkingNote(Context context, long folderId) { + mContext = context; + // 保存上下文 + mAlertDate = 0; + // 提醒日期初始为0 + mModifiedDate = System.currentTimeMillis(); + // 修改日期为当前时间 + mFolderId = folderId; + // 设置文件夹ID + mNote = new Note(); + // 创建Note对象 + mNoteId = 0; + // 笔记ID初始为0(表示新笔记) + mIsDeleted = false; + // 未删除 + mMode = 0; + // 默认模式为普通模式 + mWidgetType = Notes.TYPE_WIDGET_INVALIDE; + // 小部件类型为无效 + } + + // Existing note construct + // 加载已存在笔记构造方法 + private WorkingNote(Context context, long noteId, long folderId) { + mContext = context; + // 保存上下文 + mNoteId = noteId; + // 设置笔记ID + mFolderId = folderId; + // 设置文件夹ID + mIsDeleted = false; + // 未删除 + mNote = new Note(); + // 创建Note对象 + loadNote(); + // 加载笔记数据 + } + + private void loadNote() { + // 加载笔记基本信息 + Cursor cursor = mContext.getContentResolver().query( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, + null, null); + // 查询笔记信息 + + if (cursor != null) { + if (cursor.moveToFirst()) { + // 获取笔记属性 + mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); + // 父文件夹ID + mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); + // 背景颜色ID + mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); + // 小部件ID + mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN); + // 小部件类型 + mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN); + // 提醒日期 + mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); + // 修改日期 + } + cursor.close(); + // 关闭游标 + } else { + Log.e(TAG, "No note with id:" + mNoteId); + // 记录错误日志 + throw new IllegalArgumentException("Unable to find note with id " + mNoteId); + // 抛出异常 + } + loadNoteData(); + // 加载笔记详细数据 + } + + private void loadNoteData() { + // 加载笔记详细数据 + Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, + DataColumns.NOTE_ID + "=?", new String[] { + String.valueOf(mNoteId) + }, null); + // 查询笔记数据 + + if (cursor != null) { + if (cursor.moveToFirst()) { + do { + // 遍历数据 + String type = cursor.getString(DATA_MIME_TYPE_COLUMN); + // 获取MIME类型 + if (DataConstants.NOTE.equals(type)) { + // 如果是文本笔记 + mContent = cursor.getString(DATA_CONTENT_COLUMN); + // 获取内容 + mMode = cursor.getInt(DATA_MODE_COLUMN); + // 获取模式 + mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); + // 设置文本数据ID + } else if (DataConstants.CALL_NOTE.equals(type)) { + // 如果是通话笔记 + mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); + // 设置通话数据ID + } else { + Log.d(TAG, "Wrong note type with type:" + type); + // 记录错误类型 + } + } while (cursor.moveToNext()); + // 继续处理下一行 + } + cursor.close(); + // 关闭游标 + } else { + Log.e(TAG, "No data with id:" + mNoteId); + // 记录错误日志 + throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); + // 抛出异常 + } + } + + public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, + int widgetType, int defaultBgColorId) { + // 创建空笔记的静态方法 + WorkingNote note = new WorkingNote(context, folderId); + // 创建新工作笔记 + note.setBgColorId(defaultBgColorId); + // 设置背景颜色 + note.setWidgetId(widgetId); + // 设置小部件ID + note.setWidgetType(widgetType); + // 设置小部件类型 + return note; + // 返回工作笔记 + } + + public static WorkingNote load(Context context, long id) { + // 加载已存在笔记的静态方法 + return new WorkingNote(context, id, 0); + // 创建并返回工作笔记 + } + + public synchronized boolean saveNote() { + // 保存笔记(同步方法,线程安全) + if (isWorthSaving()) { + // 如果值得保存 + if (!existInDatabase()) { + // 如果不存在于数据库中(新笔记) + if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { + // 获取新笔记ID失败 + Log.e(TAG, "Create new note fail with id:" + mNoteId); + return false; + } + } + + mNote.syncNote(mContext, mNoteId); + // 同步笔记到数据库 + + /** + * Update widget content if there exist any widget of this note + */ + // 如果存在该笔记的小部件,更新小部件内容 + if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && mWidgetType != Notes.TYPE_WIDGET_INVALIDE + && mNoteSettingStatusListener != null) { + // 检查小部件是否有效且监听器存在 + mNoteSettingStatusListener.onWidgetChanged(); + // 通知小部件变化 + } + return true; + // 保存成功 + } else { + return false; + // 不需要保存 + } + } + + public boolean existInDatabase() { + // 检查笔记是否已存在于数据库中 + return mNoteId > 0; + // 笔记ID大于0表示已存在 + } + + private boolean isWorthSaving() { + // 检查是否值得保存 + if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) + || (existInDatabase() && !mNote.isLocalModified())) { + // 如果已删除,或新笔记但内容为空,或已存在但无本地修改 + return false; + } else { + return true; + } + } + + public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { + // 设置笔记设置变化监听器 + mNoteSettingStatusListener = l; + } + + public void setAlertDate(long date, boolean set) { + // 设置提醒日期 + if (date != mAlertDate) { + // 如果日期发生变化 + mAlertDate = date; + // 更新提醒日期 + mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); + // 设置笔记值 + } + if (mNoteSettingStatusListener != null) { + // 如果监听器存在 + mNoteSettingStatusListener.onClockAlertChanged(date, set); + // 通知提醒变化 + } + } + + public void markDeleted(boolean mark) { + // 标记删除 + mIsDeleted = mark; + // 设置删除标记 + if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { + // 检查小部件是否有效且监听器存在 + mNoteSettingStatusListener.onWidgetChanged(); + // 通知小部件变化 + } + } + + public void setBgColorId(int id) { + // 设置背景颜色ID + if (id != mBgColorId) { + // 如果颜色ID发生变化 + mBgColorId = id; + // 更新背景颜色ID + if (mNoteSettingStatusListener != null) { + // 如果监听器存在 + mNoteSettingStatusListener.onBackgroundColorChanged(); + // 通知背景颜色变化 + } + mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); + // 设置笔记值 + } + } + + public void setCheckListMode(int mode) { + // 设置清单模式 + if (mMode != mode) { + // 如果模式发生变化 + if (mNoteSettingStatusListener != null) { + // 如果监听器存在 + mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); + // 通知清单模式变化 + } + mMode = mode; + // 更新模式 + mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); + // 设置文本数据 + } + } + + public void setWidgetType(int type) { + // 设置小部件类型 + if (type != mWidgetType) { + // 如果类型发生变化 + mWidgetType = type; + // 更新小部件类型 + mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); + // 设置笔记值 + } + } + + public void setWidgetId(int id) { + // 设置小部件ID + if (id != mWidgetId) { + // 如果ID发生变化 + mWidgetId = id; + // 更新小部件ID + mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); + // 设置笔记值 + } + } + + public void setWorkingText(String text) { + // 设置工作文本(笔记内容) + if (!TextUtils.equals(mContent, text)) { + // 如果内容发生变化 + mContent = text; + // 更新内容 + mNote.setTextData(DataColumns.CONTENT, mContent); + // 设置文本数据 + } + } + + public void convertToCallNote(String phoneNumber, long callDate) { + // 转换为通话笔记 + mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); + // 设置通话日期 + mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); + // 设置电话号码 + mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); + // 设置父文件夹为通话记录文件夹 + } + + public boolean hasClockAlert() { + // 检查是否有闹钟提醒 + return (mAlertDate > 0 ? true : false); + // 提醒日期大于0表示有提醒 + } + + // 以下为获取属性的方法 + public String getContent() { + // 获取内容 + return mContent; + } + + public long getAlertDate() { + // 获取提醒日期 + return mAlertDate; + } + + public long getModifiedDate() { + // 获取修改日期 + return mModifiedDate; + } + + public int getBgColorResId() { + // 获取背景颜色资源ID + return NoteBgResources.getNoteBgResource(mBgColorId); + // 通过资源工具类获取 + } + + public int getBgColorId() { + // 获取背景颜色ID + return mBgColorId; + } + + public int getTitleBgResId() { + // 获取标题背景颜色资源ID + return NoteBgResources.getNoteTitleBgResource(mBgColorId); + // 通过资源工具类获取 + } + + public int getCheckListMode() { + // 获取清单模式 + return mMode; + } + + public long getNoteId() { + // 获取笔记ID + return mNoteId; + } + + public long getFolderId() { + // 获取文件夹ID + return mFolderId; + } + + public int getWidgetId() { + // 获取小部件ID + return mWidgetId; + } + + public int getWidgetType() { + // 获取小部件类型 + return mWidgetType; + } + + public interface NoteSettingChangedListener { + // 笔记设置变化监听器接口 + /** + * Called when the background color of current note has just changed + */ + // 当前笔记背景颜色变化时调用 + void onBackgroundColorChanged(); + + /** + * Called when user set clock + */ + // 用户设置闹钟时调用 + void onClockAlertChanged(long date, boolean set); + + /** + * Call when user create note from widget + */ + // 用户从小部件创建笔记时调用 + void onWidgetChanged(); + + /** + * Call when switch between check list mode and normal mode + * @param oldMode is previous mode before change + * @param newMode is new mode + */ + // 在清单模式和普通模式之间切换时调用 + // oldMode是变化前的模式 + // newMode是新模式 + void onCheckListModeChanged(int oldMode, int newMode); + } +} \ No newline at end of file diff --git a/src/tool/BackupUtils.java b/src/tool/BackupUtils.java new file mode 100644 index 0000000..91d3850 --- /dev/null +++ b/src/tool/BackupUtils.java @@ -0,0 +1,481 @@ +/* + * 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"; + // 日志标签 + + // Singleton stuff + // 单例模式相关 + private static BackupUtils sInstance; + // 单例实例 + + public static synchronized BackupUtils getInstance(Context context) { + // 获取单例实例(同步方法) + if (sInstance == null) { + sInstance = new BackupUtils(context); + // 创建新实例 + } + return sInstance; + // 返回实例 + } + + /** + * Following states are signs to represents backup or restore + * status + */ + // 以下状态表示备份或恢复的状态 + // Currently, the sdcard is not mounted + // 当前SD卡未挂载 + public static final int STATE_SD_CARD_UNMOUONTED = 0; + // The backup file not exist + // 备份文件不存在 + public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; + // The data is not well formated, may be changed by other programs + // 数据格式错误,可能被其他程序修改 + public static final int STATE_DATA_DESTROIED = 2; + // Some run-time exception which causes restore or backup fails + // 运行时异常导致备份或恢复失败 + public static final int STATE_SYSTEM_ERROR = 3; + // Backup or restore success + // 备份或恢复成功 + public static final int STATE_SUCCESS = 4; + + private TextExport mTextExport; + // 文本导出对象 + + private BackupUtils(Context context) { + // 私有构造方法 + mTextExport = new TextExport(context); + // 创建文本导出对象 + } + + private static boolean externalStorageAvailable() { + // 检查外部存储是否可用 + return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); + // 检查存储状态是否为已挂载 + } + + public int exportToText() { + // 导出为文本 + return mTextExport.exportToText(); + // 调用文本导出方法 + } + + public String getExportedTextFileName() { + // 获取导出的文本文件名 + return mTextExport.mFileName; + } + + 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; + // ID列索引 + + 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; + // MIME类型列索引 + + private static final int DATA_COLUMN_CALL_DATE = 2; + // 通话日期列索引(对应DATA1) + + private static final int DATA_COLUMN_PHONE_NUMBER = 4; + // 电话号码列索引(对应DATA3) + + // 文本格式化数组 + 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 = ""; + // 初始化文件目录为空 + } + + private String getFormat(int id) { + // 获取指定格式的字符串 + return TEXT_FORMAT[id]; + // 返回格式字符串 + } + + /** + * Export the folder identified by folder id to text + */ + // 将指定文件夹导出为文本 + private void exportFolderToText(String folderId, PrintStream ps) { + // Query notes belong to this folder + // 查询属于该文件夹的笔记 + Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { + folderId + }, null); + // 查询父ID为folderId的笔记 + + if (notesCursor != null) { + if (notesCursor.moveToFirst()) { + do { + // Print note's last modified date + // 打印笔记的最后修改日期 + ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), + notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); + // 格式化并输出日期 + // Query data belong to this note + // 查询属于该笔记的数据 + String noteId = notesCursor.getString(NOTE_COLUMN_ID); + // 获取笔记ID + exportNoteToText(noteId, ps); + // 导出笔记内容 + } while (notesCursor.moveToNext()); + // 继续处理下一个笔记 + } + notesCursor.close(); + // 关闭游标 + } + } + + /** + * Export note identified by id to a print stream + */ + // 将指定笔记导出到打印流 + 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); + // 获取MIME类型 + if (DataConstants.CALL_NOTE.equals(mimeType)) { + // 如果是通话笔记 + // Print phone number + // 打印电话号码 + String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); + // 获取电话号码 + long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); + // 获取通话日期 + String location = dataCursor.getString(DATA_COLUMN_CONTENT); + // 获取内容(可能是位置信息) + + if (!TextUtils.isEmpty(phoneNumber)) { + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), + phoneNumber)); + // 输出电话号码 + } + // Print call date + // 打印通话日期 + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat + .format(mContext.getString(R.string.format_datetime_mdhm), + callDate))); + // 格式化并输出日期 + // Print call attachment location + // 打印通话附件位置 + if (!TextUtils.isEmpty(location)) { + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), + location)); + // 输出位置信息 + } + } else if (DataConstants.NOTE.equals(mimeType)) { + // 如果是普通笔记 + String content = dataCursor.getString(DATA_COLUMN_CONTENT); + // 获取内容 + if (!TextUtils.isEmpty(content)) { + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), + content)); + // 输出内容 + } + } + } while (dataCursor.moveToNext()); + // 继续处理下一个数据 + } + dataCursor.close(); + // 关闭游标 + } + // print a line separator between note + // 在笔记之间打印行分隔符 + try { + ps.write(new byte[] { + Character.LINE_SEPARATOR, Character.LETTER_NUMBER + // 写入行分隔符(注意:这里代码有误,应该是换行符) + }); + } catch (IOException e) { + Log.e(TAG, e.toString()); + // 记录异常 + } + } + + /** + * Note will be exported as text which is user readable + */ + // 笔记将被导出为用户可读的文本 + public int exportToText() { + if (!externalStorageAvailable()) { + // 检查外部存储是否可用 + Log.d(TAG, "Media was not mounted"); + return STATE_SD_CARD_UNMOUONTED; + // 返回SD卡未挂载状态 + } + + PrintStream ps = getExportToTextPrintStream(); + // 获取打印流 + if (ps == null) { + Log.e(TAG, "get print stream error"); + return STATE_SYSTEM_ERROR; + // 返回系统错误状态 + } + // First export folder and its notes + // 首先导出文件夹及其笔记 + Cursor folderCursor = mContext.getContentResolver().query( + Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, + "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " + + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " + + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null); + // 查询所有非垃圾箱的文件夹和通话记录文件夹 + + if (folderCursor != null) { + if (folderCursor.moveToFirst()) { + do { + // Print folder's name + // 打印文件夹名称 + String folderName = ""; + if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { + // 如果是通话记录文件夹 + folderName = mContext.getString(R.string.call_record_folder_name); + // 使用资源文件中的名称 + } else { + folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); + // 使用摘要作为文件夹名称 + } + if (!TextUtils.isEmpty(folderName)) { + ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); + // 输出文件夹名称 + } + String folderId = folderCursor.getString(NOTE_COLUMN_ID); + // 获取文件夹ID + exportFolderToText(folderId, ps); + // 导出文件夹内容 + } while (folderCursor.moveToNext()); + // 继续处理下一个文件夹 + } + folderCursor.close(); + // 关闭游标 + } + + // Export notes in root's folder + // 导出根文件夹中的笔记 + Cursor noteCursor = mContext.getContentResolver().query( + Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, + NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + + "=0", null, null); + // 查询根文件夹中的笔记(父ID为0) + + if (noteCursor != null) { + if (noteCursor.moveToFirst()) { + do { + ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), + noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); + // 输出笔记修改日期 + // Query data belong to this note + // 查询属于该笔记的数据 + String noteId = noteCursor.getString(NOTE_COLUMN_ID); + // 获取笔记ID + exportNoteToText(noteId, ps); + // 导出笔记内容 + } while (noteCursor.moveToNext()); + // 继续处理下一个笔记 + } + noteCursor.close(); + // 关闭游标 + } + ps.close(); + // 关闭打印流 + + return STATE_SUCCESS; + // 返回成功状态 + } + + /** + * Get a print stream pointed to the file {@generateExportedTextFile} + */ + // 获取指向文件的打印流 + private PrintStream getExportToTextPrintStream() { + File file = generateFileMountedOnSDcard(mContext, R.string.file_path, + R.string.file_name_txt_format); + // 生成SD卡上的文件 + 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; + // 返回打印流 + } + } + + /** + * Generate the text file to store imported data + */ + // 生成存储导入数据的文本文件 + private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { + StringBuilder sb = new StringBuilder(); + // 使用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(); + // IO异常 + } + + return null; + // 返回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..108fb61 --- /dev/null +++ b/src/tool/DataUtils.java @@ -0,0 +1,424 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.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; + + +```java +public class DataUtils { +// 数据工具类,提供笔记数据的各种操作方法 + + public static final String TAG = "DataUtils"; + // 日志标签 + + public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { + // 批量删除笔记 + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + // 如果ID集合为空,直接返回true + } + if (ids.size() == 0) { + Log.d(TAG, "no id is in the hashset"); + return true; + // 如果ID集合为空集,直接返回true + } + + ArrayList operationList = new ArrayList(); + // 创建操作列表 + for (long id : ids) { + // 遍历ID集合 + 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; + // 执行结果无效,返回false + } + return true; + // 批量删除成功 + } catch (RemoteException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + // 远程异常 + } catch (OperationApplicationException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + // 操作应用异常 + } + return false; + // 执行失败 + } + + public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { + // 移动笔记到文件夹(方法名拼写错误) + ContentValues values = new ContentValues(); + // 创建ContentValues + values.put(NoteColumns.PARENT_ID, desFolderId); + // 设置目标父文件夹ID + values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); + // 设置原始父文件夹ID + values.put(NoteColumns.LOCAL_MODIFIED, 1); + // 设置本地修改标志 + resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); + // 更新数据库 + } + + public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, + long folderId) { + // 批量移动到文件夹 + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + // ID集合为空,返回true + } + + ArrayList operationList = new ArrayList(); + // 创建操作列表 + for (long id : ids) { + // 遍历ID集合 + ContentProviderOperation.Builder builder = ContentProviderOperation + .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + // 创建更新操作构建器 + builder.withValue(NoteColumns.PARENT_ID, folderId); + // 设置父文件夹ID + 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; + // 执行结果无效,返回false + } + return true; + // 批量移动成功 + } catch (RemoteException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + // 远程异常 + } catch (OperationApplicationException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + // 操作应用异常 + } + return false; + // 执行失败 + } + + /** + * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} + */ + // 获取用户文件夹数量(排除系统文件夹) + 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; + // 数量初始化为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; + // 返回数量 + } + + public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { + // 检查笔记在数据库中是否可见(不在垃圾箱中) + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + // 查询指定笔记ID + null, + NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, + // 条件:指定类型且不在垃圾箱 + new String [] {String.valueOf(type)}, + null); + + boolean exist = false; + // 存在标志初始化为false + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + // 如果有数据,设置为true + } + cursor.close(); + // 关闭游标 + } + return exist; + // 返回存在标志 + } + + public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { + // 检查笔记是否存在于数据库中 + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + // 查询指定笔记ID + null, null, null, null); + // 无条件查询 + + boolean exist = false; + // 存在标志初始化为false + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + // 如果有数据,设置为true + } + cursor.close(); + // 关闭游标 + } + return exist; + // 返回存在标志 + } + + public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { + // 检查数据是否存在于数据表中 + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), + // 查询指定数据ID + null, null, null, null); + // 无条件查询 + + boolean exist = false; + // 存在标志初始化为false + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + // 如果有数据,设置为true + } + cursor.close(); + // 关闭游标 + } + return exist; + // 返回存在标志 + } + + 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; + // 存在标志初始化为false + if(cursor != null) { + if(cursor.getCount() > 0) { + exist = true; + // 如果有数据,设置为true + } + cursor.close(); + // 关闭游标 + } + return exist; + // 返回存在标志 + } + + public static HashSet getFolderNoteWidget(ContentResolver resolver, long folderId) { + // 获取文件夹中笔记的小部件属性 + Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, + // 查询笔记表 + new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, + // 查询小部件ID和类型 + NoteColumns.PARENT_ID + "=?", + // 父文件夹ID等于指定ID + new String[] { String.valueOf(folderId) }, + null); + + HashSet set = null; + // 集合初始化为null + if (c != null) { + if (c.moveToFirst()) { + // 移动到第一行 + set = new HashSet(); + // 创建集合 + do { + try { + AppWidgetAttribute widget = new AppWidgetAttribute(); + // 创建小部件属性对象 + widget.widgetId = c.getInt(0); + // 设置小部件ID + widget.widgetType = c.getInt(1); + // 设置小部件类型 + set.add(widget); + // 添加到集合 + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, e.toString()); + // 索引越界异常 + } + } while (c.moveToNext()); + // 继续处理下一行 + } + c.close(); + // 关闭游标 + } + return set; + // 返回集合 + } + + public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { + // 根据笔记ID获取通话号码 + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + // 查询数据表 + new String [] { CallNote.PHONE_NUMBER }, + // 只查询电话号码列 + CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", + // 条件:笔记ID匹配且MIME类型为通话笔记 + 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 ""; + // 返回空字符串 + } + + public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { + // 根据电话号码和通话日期获取笔记ID + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + // 查询数据表 + new String [] { CallNote.NOTE_ID }, + // 只查询笔记ID列 + CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" + + CallNote.PHONE_NUMBER + ",?)", + // 条件:通话日期匹配、MIME类型为通话笔记、电话号码相等 + new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, + null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + // 移动到第一行 + try { + return cursor.getLong(0); + // 返回第一列的值(笔记ID) + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "Get call note id fails " + e.toString()); + // 索引越界异常 + } + } + cursor.close(); + // 关闭游标 + } + return 0; + // 返回0表示未找到 + } + + public static String getSnippetById(ContentResolver resolver, long noteId) { + // 根据笔记ID获取摘要 + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, + // 查询笔记表 + new String [] { NoteColumns.SNIPPET }, + // 只查询摘要列 + NoteColumns.ID + "=?", + // 笔记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); + // 抛出异常:笔记未找到 + } + + 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..8d4f23d --- /dev/null +++ b/src/tool/GTaskStringUtils.java @@ -0,0 +1,165 @@ +/* + * 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; + +```java +public class GTaskStringUtils { +// Google任务字符串工具类,定义所有与Google Tasks API相关的常量 + + // 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_CLIENT_VERSION = "client_version"; + // 客户端版本键名 + + public final static String GTASK_JSON_COMPLETED = "completed"; + // 完成状态键名 + + 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_DELETED = "deleted"; + // 删除状态键名 + + public final static String GTASK_JSON_DEST_LIST = "dest_list"; + // 目标列表键名 + + public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; + // 目标父节点键名 + + public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; + // 目标父节点类型键名 + + public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; + // 实体增量键名 + + public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; + // 实体类型键名 + + public final static String GTASK_JSON_GET_DELETED = "get_deleted"; + // 获取删除项键名 + + 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_LIST_ID = "list_id"; + // 列表ID键名 + + public final static String GTASK_JSON_LISTS = "lists"; + // 列表集合键名 + + 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_RESULTS = "results"; + // 结果集合键名 + + public final static String GTASK_JSON_SOURCE_LIST = "source_list"; + // 源列表键名 + + public final static String GTASK_JSON_TASKS = "tasks"; + // 任务集合键名 + + public final static String GTASK_JSON_TYPE = "type"; + // 类型键名 + + public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; + // 分组类型值 + + public final static String GTASK_JSON_TYPE_TASK = "TASK"; + // 任务类型值 + + public final static String GTASK_JSON_USER = "user"; + // 用户键名 + + // MIUI特定常量 + public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; + // MIUI笔记文件夹前缀(拼写错误:PREFFIX应为PREFIX) + + // 文件夹名称常量 + 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任务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..6822705 --- /dev/null +++ b/src/tool/ResourceParser.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.tool; + +import android.content.Context; +import android.preference.PreferenceManager; + +import net.micode.notes.R; +import net.micode.notes.ui.NotesPreferenceActivity; + +public class ResourceParser { +// 资源解析器类,管理笔记应用的各种资源 + + // 背景颜色常量 + 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 // 红色标题背景 + }; + + public static int getNoteBgResource(int id) { + // 根据ID获取笔记编辑背景资源 + return BG_EDIT_RESOURCES[id]; + // 返回对应ID的资源 + } + + public static int getNoteTitleBgResource(int id) { + // 根据ID获取笔记标题背景资源 + return BG_EDIT_TITLE_RESOURCES[id]; + // 返回对应ID的资源 + } + } + + public static int getDefaultBgId(Context context) { + // 获取默认背景ID + if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( + NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { + // 检查是否启用了随机背景颜色设置 + return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length); + // 随机返回一个背景颜色ID + } 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 // 单一项红色背景 + }; + + public static int getNoteBgFirstRes(int id) { + // 获取列表第一项背景资源 + return BG_FIRST_RESOURCES[id]; + } + + public static int getNoteBgLastRes(int id) { + // 获取列表最后一项背景资源 + return BG_LAST_RESOURCES[id]; + } + + public static int getNoteBgSingleRes(int id) { + // 获取单一项背景资源 + return BG_SINGLE_RESOURCES[id]; + } + + public static int getNoteBgNormalRes(int id) { + // 获取列表中间项背景资源 + return BG_NORMAL_RESOURCES[id]; + } + + public static int getFolderBgRes() { + // 获取文件夹背景资源 + return R.drawable.list_folder; + // 返回文件夹专用背景 + } + } + + public static class WidgetBgResources { + // 小部件背景资源类 + private final static int [] BG_2X_RESOURCES = new int [] { + R.drawable.widget_2x_yellow, // 2x2小部件黄色背景 + R.drawable.widget_2x_blue, // 2x2小部件蓝色背景 + R.drawable.widget_2x_white, // 2x2小部件白色背景 + R.drawable.widget_2x_green, // 2x2小部件绿色背景 + R.drawable.widget_2x_red, // 2x2小部件红色背景 + }; + + public static int getWidget2xBgResource(int id) { + // 获取2x2小部件背景资源 + return BG_2X_RESOURCES[id]; + } + + private final static int [] BG_4X_RESOURCES = new int [] { + R.drawable.widget_4x_yellow, // 4x4小部件黄色背景 + R.drawable.widget_4x_blue, // 4x4小部件蓝色背景 + R.drawable.widget_4x_white, // 4x4小部件白色背景 + R.drawable.widget_4x_green, // 4x4小部件绿色背景 + R.drawable.widget_4x_red // 4x4小部件红色背景 + }; + + public static int getWidget4xBgResource(int id) { + // 获取4x4小部件背景资源 + 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 // 超大文本样式 + }; + + public static int getTexAppearanceResource(int id) { + // 获取文本外观资源(方法名拼写错误:Tex应为Text) + /** + * HACKME: Fix bug of store the resource id in shared preference. + * The id may larger than the length of resources, in this case, + * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} + */ + // 修复bug:存储在shared preference中的资源ID可能大于资源数组长度 + // 在这种情况下,返回默认字体大小 + if (id >= TEXTAPPEARANCE_RESOURCES.length) { + return BG_DEFAULT_FONT_SIZE; + // 返回默认字体大小 + } + return TEXTAPPEARANCE_RESOURCES[id]; + // 返回对应ID的资源 + } + + public static int getResourcesSize() { + // 获取资源数组大小 + return TEXTAPPEARANCE_RESOURCES.length; + } + } +} \ No newline at end of file diff --git a/src/ui/AlarmAlertActivity.java b/src/ui/AlarmAlertActivity.java new file mode 100644 index 0000000..5cd917e --- /dev/null +++ b/src/ui/AlarmAlertActivity.java @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.content.DialogInterface.OnDismissListener; +import android.content.Intent; +import android.media.AudioManager; +import android.media.MediaPlayer; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Bundle; +import android.os.PowerManager; +import android.provider.Settings; +import android.view.Window; +import android.view.WindowManager; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.DataUtils; + +import java.io.IOException; + + +public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { +// 闹钟提醒活动,继承Activity并实现点击和取消监听器接口 + + private long mNoteId; + // 笔记ID + + private String mSnippet; + // 笔记摘要 + + private static final int SNIPPET_PREW_MAX_LEN = 60; + // 摘要预览最大长度(注意:PREW应为PREVIEW) + + MediaPlayer mPlayer; + // 媒体播放器,用于播放闹钟声音 + + @Override + protected void onCreate(Bundle savedInstanceState) { + // 活动创建方法 + super.onCreate(savedInstanceState); + // 调用父类onCreate + requestWindowFeature(Window.FEATURE_NO_TITLE); + // 请求无标题栏 + + final Window win = getWindow(); + // 获取窗口对象 + win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); + // 添加标志:锁屏时仍显示 + + if (!isScreenOn()) { + // 如果屏幕关闭 + win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + // 保持屏幕常亮 + | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON + // 点亮屏幕 + | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON + // 允许屏幕亮时锁定 + | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); + // 布局插入装饰 + } + + Intent intent = getIntent(); + // 获取启动意图 + + try { + mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); + // 从URI路径中提取笔记ID(第二个路径段) + mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); + // 根据笔记ID获取摘要 + mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, + SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) + // 如果摘要过长,截断并添加省略号 + : mSnippet; + // 否则使用完整摘要 + } catch (IllegalArgumentException e) { + e.printStackTrace(); + return; + // 参数异常,直接返回 + } + + mPlayer = new MediaPlayer(); + // 创建媒体播放器实例 + if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { + // 如果笔记在数据库中可见(不在垃圾箱中) + showActionDialog(); + // 显示操作对话框 + playAlarmSound(); + // 播放闹钟声音 + } else { + finish(); + // 否则结束活动 + } + } + + private boolean isScreenOn() { + // 检查屏幕是否亮着 + PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); + // 获取电源管理器服务 + return pm.isScreenOn(); + // 返回屏幕状态 + } + + private void playAlarmSound() { + // 播放闹钟声音 + Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); + // 获取默认闹钟铃声URI + + int silentModeStreams = Settings.System.getInt(getContentResolver(), + Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); + // 获取静音模式影响的音频流设置 + + if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { + // 如果闹钟流受静音模式影响 + mPlayer.setAudioStreamType(silentModeStreams); + // 设置受影响的音频流类型 + } else { + mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); + // 设置闹钟音频流类型 + } + try { + mPlayer.setDataSource(this, url); + // 设置数据源 + mPlayer.prepare(); + // 准备播放器 + mPlayer.setLooping(true); + // 设置循环播放 + mPlayer.start(); + // 开始播放 + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + // 参数异常 + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + // 安全异常 + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + // 非法状态异常 + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + // IO异常 + } + } + + private void showActionDialog() { + // 显示操作对话框 + AlertDialog.Builder dialog = new AlertDialog.Builder(this); + // 创建对话框构建器 + dialog.setTitle(R.string.app_name); + // 设置标题为应用名称 + dialog.setMessage(mSnippet); + // 设置消息为笔记摘要 + dialog.setPositiveButton(R.string.notealert_ok, this); + // 设置确定按钮 + if (isScreenOn()) { + // 如果屏幕亮着 + dialog.setNegativeButton(R.string.notealert_enter, this); + // 设置进入按钮(查看笔记) + } + dialog.show().setOnDismissListener(this); + // 显示对话框并设置取消监听器 + } + + public void onClick(DialogInterface dialog, int which) { + // 对话框按钮点击回调 + switch (which) { + case DialogInterface.BUTTON_NEGATIVE: + // 如果是负按钮(进入按钮) + Intent intent = new Intent(this, NoteEditActivity.class); + // 创建编辑活动意图 + intent.setAction(Intent.ACTION_VIEW); + // 设置操作为查看 + intent.putExtra(Intent.EXTRA_UID, mNoteId); + // 添加笔记ID作为额外数据 + startActivity(intent); + // 启动编辑活动 + break; + default: + break; + } + } + + public void onDismiss(DialogInterface dialog) { + // 对话框取消回调 + stopAlarmSound(); + // 停止闹钟声音 + finish(); + // 结束活动 + } + + private void stopAlarmSound() { + // 停止闹钟声音 + if (mPlayer != null) { + mPlayer.stop(); + // 停止播放 + mPlayer.release(); + // 释放播放器资源 + mPlayer = null; + // 设为null + } + } +} \ No newline at end of file diff --git a/src/ui/AlarmInitReceiver.java b/src/ui/AlarmInitReceiver.java new file mode 100644 index 0000000..f3c38fd --- /dev/null +++ b/src/ui/AlarmInitReceiver.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.ContentUris; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +public class AlarmInitReceiver extends BroadcastReceiver { +// 闹钟初始化广播接收器,继承BroadcastReceiver + + // 查询投影列数组 + private static final String [] PROJECTION = new String [] { + NoteColumns.ID, // 笔记ID + NoteColumns.ALERTED_DATE // 提醒日期 + }; + + // 列索引常量 + private static final int COLUMN_ID = 0; + // ID列索引 + private static final int COLUMN_ALERTED_DATE = 1; + // 提醒日期列索引 + + @Override + public void onReceive(Context context, Intent intent) { + // 接收广播回调方法 + long currentDate = System.currentTimeMillis(); + // 获取当前时间戳 + + // 查询所有未来需要提醒的笔记 + Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, + // 查询笔记表 + PROJECTION, + // 查询的列 + NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, + // 条件:提醒日期大于当前时间且类型为普通笔记 + new String[] { String.valueOf(currentDate) }, + // 参数:当前时间 + null); + // 排序 + + if (c != null) { + if (c.moveToFirst()) { + // 如果有查询结果 + do { + // 遍历所有符合条件的笔记 + long alertDate = c.getLong(COLUMN_ALERTED_DATE); + // 获取提醒日期 + + // 创建广播Intent + Intent sender = new Intent(context, AlarmReceiver.class); + // 创建指向AlarmReceiver的Intent + sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); + // 设置数据URI为笔记URI + + // 创建延迟Intent + PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); + // 创建广播PendingIntent + + // 获取闹钟管理器 + AlarmManager alermManager = (AlarmManager) context + .getSystemService(Context.ALARM_SERVICE); + // 获取闹钟服务(注意:alermManager应为alarmManager) + + // 设置闹钟 + alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + // 设置实时时钟唤醒闹钟 + } while (c.moveToNext()); + // 继续处理下一行 + } + c.close(); + // 关闭游标 + } + } +} \ No newline at end of file diff --git a/src/gtask/exception/NetworkFailureException.java b/src/ui/AlarmReceiver.java similarity index 59% rename from src/gtask/exception/NetworkFailureException.java rename to src/ui/AlarmReceiver.java index b08cfb1..54e503b 100644 --- a/src/gtask/exception/NetworkFailureException.java +++ b/src/ui/AlarmReceiver.java @@ -14,20 +14,17 @@ * limitations under the License. */ -package net.micode.notes.gtask.exception; +package net.micode.notes.ui; -public class NetworkFailureException extends Exception { - private static final long serialVersionUID = 2107610287180234136L; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; - public NetworkFailureException() { - super(); - } - - public NetworkFailureException(String paramString) { - super(paramString); - } - - public NetworkFailureException(String paramString, Throwable paramThrowable) { - super(paramString, paramThrowable); +public class AlarmReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + intent.setClass(context, AlarmAlertActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); } } diff --git a/src/ui/DateTimePicker.java b/src/ui/DateTimePicker.java new file mode 100644 index 0000000..c712bbb --- /dev/null +++ b/src/ui/DateTimePicker.java @@ -0,0 +1,593 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import java.text.DateFormatSymbols; +import java.util.Calendar; + +import net.micode.notes.R; + + +import android.content.Context; +import android.text.format.DateFormat; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.NumberPicker; + +public class DateTimePicker extends FrameLayout { +// 日期时间选择器,继承FrameLayout + + private static final boolean DEFAULT_ENABLE_STATE = true; + // 默认启用状态 + + // 时间常量 + private static final int HOURS_IN_HALF_DAY = 12; + // 半天的小时数 + private static final int HOURS_IN_ALL_DAY = 24; + // 全天的小时数 + private static final int DAYS_IN_ALL_WEEK = 7; + // 一周的天数 + private static final int DATE_SPINNER_MIN_VAL = 0; + // 日期选择器最小值 + private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; + // 日期选择器最大值 + private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; + // 24小时制小时选择器最小值 + private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; + // 24小时制小时选择器最大值 + private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; + // 12小时制小时选择器最小值 + private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; + // 12小时制小时选择器最大值 + private static final int MINUT_SPINNER_MIN_VAL = 0; + // 分钟选择器最小值(拼写错误:MINUT应为MINUTE) + private static final int MINUT_SPINNER_MAX_VAL = 59; + // 分钟选择器最大值 + private static final int AMPM_SPINNER_MIN_VAL = 0; + // AM/PM选择器最小值 + private static final int AMPM_SPINNER_MAX_VAL = 1; + // AM/PM选择器最大值 + + // 组件 + private final NumberPicker mDateSpinner; + // 日期选择器 + private final NumberPicker mHourSpinner; + // 小时选择器 + private final NumberPicker mMinuteSpinner; + // 分钟选择器 + private final NumberPicker mAmPmSpinner; + // AM/PM选择器 + private Calendar mDate; + // 日期对象 + + private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; + // 日期显示值数组 + + private boolean mIsAm; + // 是否为上午 + + private boolean mIs24HourView; + // 是否为24小时制 + + private boolean mIsEnabled = DEFAULT_ENABLE_STATE; + // 启用状态 + + private boolean mInitialising; + // 初始化标志 + + private OnDateTimeChangedListener mOnDateTimeChangedListener; + // 日期时间变化监听器 + + // 日期变化监听器 + private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); + // 计算日期差并更新 + updateDateControl(); + // 更新日期控件显示 + onDateTimeChanged(); + // 触发日期时间变化事件 + } + }; + + // 小时变化监听器 + private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + boolean isDateChanged = false; + Calendar cal = Calendar.getInstance(); + if (!mIs24HourView) { + // 12小时制处理逻辑 + if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { + // 下午11点变12点,日期加1天 + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, 1); + isDateChanged = true; + } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { + // 上午12点变11点,日期减1天 + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -1); + isDateChanged = true; + } + if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY || + oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { + // 12点和11点切换时,改变AM/PM状态 + mIsAm = !mIsAm; + updateAmPmControl(); + } + } else { + // 24小时制处理逻辑 + if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { + // 23点变0点,日期加1天 + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, 1); + isDateChanged = true; + } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { + // 0点变23点,日期减1天 + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -1); + isDateChanged = true; + } + } + int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY); + // 计算24小时制的小时数 + mDate.set(Calendar.HOUR_OF_DAY, newHour); + onDateTimeChanged(); + if (isDateChanged) { + // 如果日期发生变化,更新年/月/日 + setCurrentYear(cal.get(Calendar.YEAR)); + setCurrentMonth(cal.get(Calendar.MONTH)); + setCurrentDay(cal.get(Calendar.DAY_OF_MONTH)); + } + } + }; + + // 分钟变化监听器 + private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + int minValue = mMinuteSpinner.getMinValue(); + int maxValue = mMinuteSpinner.getMaxValue(); + int offset = 0; + if (oldVal == maxValue && newVal == minValue) { + // 59分变0分,小时加1 + offset += 1; + } else if (oldVal == minValue && newVal == maxValue) { + // 0分变59分,小时减1 + offset -= 1; + } + if (offset != 0) { + mDate.add(Calendar.HOUR_OF_DAY, offset); + // 调整小时 + mHourSpinner.setValue(getCurrentHour()); + // 更新小时选择器 + updateDateControl(); + // 更新日期显示 + int newHour = getCurrentHourOfDay(); + if (newHour >= HOURS_IN_HALF_DAY) { + mIsAm = false; + updateAmPmControl(); + } else { + mIsAm = true; + updateAmPmControl(); + } + } + mDate.set(Calendar.MINUTE, newVal); + onDateTimeChanged(); + } + }; + + // AM/PM变化监听器 + private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mIsAm = !mIsAm; + if (mIsAm) { + // AM变PM,小时减12 + mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); + } else { + // PM变AM,小时加12 + mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); + } + updateAmPmControl(); + onDateTimeChanged(); + } + }; + + // 日期时间变化监听器接口 + public interface OnDateTimeChangedListener { + void onDateTimeChanged(DateTimePicker view, int year, int month, + int dayOfMonth, int hourOfDay, int minute); + } + + // 构造方法 + public DateTimePicker(Context context) { + this(context, System.currentTimeMillis()); + // 使用当前时间 + } + + public DateTimePicker(Context context, long date) { + this(context, date, DateFormat.is24HourFormat(context)); + // 使用系统设置判断是否为24小时制 + } + + public DateTimePicker(Context context, long date, boolean is24HourView) { + super(context); + mDate = Calendar.getInstance(); + // 创建日历实例 + mInitialising = true; + // 标记为初始化中 + mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; + // 根据当前小时判断AM/PM + inflate(context, R.layout.datetime_picker, this); + // 加载布局 + + // 初始化各组件 + mDateSpinner = (NumberPicker) findViewById(R.id.date); + mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); + mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); + mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); + + mHourSpinner = (NumberPicker) findViewById(R.id.hour); + mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); + mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); + mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL); + mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL); + mMinuteSpinner.setOnLongPressUpdateInterval(100); + // 长按更新间隔100ms + mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); + + String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); + // 获取AM/PM字符串(本地化) + mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); + mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); + mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL); + mAmPmSpinner.setDisplayedValues(stringsForAmPm); + // 设置显示值为AM/PM字符串 + mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); + + // 更新控件到初始状态 + updateDateControl(); + updateHourControl(); + updateAmPmControl(); + + set24HourView(is24HourView); + // 设置24小时制视图 + + // 设置为当前时间 + setCurrentDate(date); + + setEnabled(isEnabled()); + + // 设置内容描述 + mInitialising = false; + // 初始化完成 + } + + @Override + public void setEnabled(boolean enabled) { + // 设置启用状态 + if (mIsEnabled == enabled) { + return; + } + super.setEnabled(enabled); + // 设置父类启用状态 + mDateSpinner.setEnabled(enabled); + mMinuteSpinner.setEnabled(enabled); + mHourSpinner.setEnabled(enabled); + mAmPmSpinner.setEnabled(enabled); + // 设置各组件启用状态 + mIsEnabled = enabled; + // 更新启用状态标志 + } + + @Override + public boolean isEnabled() { + // 获取启用状态 + return mIsEnabled; + } + + /** + * Get the current date in millis + * + * @return the current date in millis + */ + // 获取当前时间的毫秒数 + public long getCurrentDateInTimeMillis() { + return mDate.getTimeInMillis(); + } + + /** + * Set the current date + * + * @param date The current date in millis + */ + // 设置当前日期(毫秒数) + public void setCurrentDate(long date) { + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(date); + setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), + cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)); + } + + /** + * Set the current date + * + * @param year The current year + * @param month The current month + * @param dayOfMonth The current dayOfMonth + * @param hourOfDay The current hourOfDay + * @param minute The current minute + */ + // 设置当前日期(具体参数) + public void setCurrentDate(int year, int month, + int dayOfMonth, int hourOfDay, int minute) { + setCurrentYear(year); + setCurrentMonth(month); + setCurrentDay(dayOfMonth); + setCurrentHour(hourOfDay); + setCurrentMinute(minute); + } + + /** + * Get current year + * + * @return The current year + */ + // 获取当前年 + public int getCurrentYear() { + return mDate.get(Calendar.YEAR); + } + + /** + * Set current year + * + * @param year The current year + */ + // 设置当前年 + public void setCurrentYear(int year) { + if (!mInitialising && year == getCurrentYear()) { + return; + // 如果非初始化且年份相同,直接返回 + } + mDate.set(Calendar.YEAR, year); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current month in the year + * + * @return The current month in the year + */ + // 获取当前月 + public int getCurrentMonth() { + return mDate.get(Calendar.MONTH); + } + + /** + * Set current month in the year + * + * @param month The month in the year + */ + // 设置当前月 + public void setCurrentMonth(int month) { + if (!mInitialising && month == getCurrentMonth()) { + return; + } + mDate.set(Calendar.MONTH, month); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current day of the month + * + * @return The day of the month + */ + // 获取当前日 + public int getCurrentDay() { + return mDate.get(Calendar.DAY_OF_MONTH); + } + + /** + * Set current day of the month + * + * @param dayOfMonth The day of the month + */ + // 设置当前日 + public void setCurrentDay(int dayOfMonth) { + if (!mInitialising && dayOfMonth == getCurrentDay()) { + return; + } + mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current hour in 24 hour mode, in the range (0~23) + * @return The current hour in 24 hour mode + */ + // 获取24小时制的小时(0-23) + public int getCurrentHourOfDay() { + return mDate.get(Calendar.HOUR_OF_DAY); + } + + // 获取当前小时(根据12/24小时制转换) + private int getCurrentHour() { + if (mIs24HourView){ + return getCurrentHourOfDay(); + // 24小时制直接返回 + } else { + int hour = getCurrentHourOfDay(); + if (hour > HOURS_IN_HALF_DAY) { + return hour - HOURS_IN_HALF_DAY; + // 下午:13-23转1-11 + } else { + return hour == 0 ? HOURS_IN_HALF_DAY : hour; + // 上午:0点转12点,其他不变 + } + } + } + + /** + * Set current hour in 24 hour mode, in the range (0~23) + * + * @param hourOfDay + */ + // 设置24小时制的小时 + public void setCurrentHour(int hourOfDay) { + if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { + return; + } + mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); + if (!mIs24HourView) { + // 12小时制额外处理 + if (hourOfDay >= HOURS_IN_HALF_DAY) { + mIsAm = false; + // 下午 + if (hourOfDay > HOURS_IN_HALF_DAY) { + hourOfDay -= HOURS_IN_HALF_DAY; + } + } else { + mIsAm = true; + // 上午 + if (hourOfDay == 0) { + hourOfDay = HOURS_IN_HALF_DAY; + // 0点转12点 + } + } + updateAmPmControl(); + } + mHourSpinner.setValue(hourOfDay); + onDateTimeChanged(); + } + + /** + * Get currentMinute + * + * @return The Current Minute + */ + // 获取当前分钟 + public int getCurrentMinute() { + return mDate.get(Calendar.MINUTE); + } + + /** + * Set current minute + */ + // 设置当前分钟 + public void setCurrentMinute(int minute) { + if (!mInitialising && minute == getCurrentMinute()) { + return; + } + mMinuteSpinner.setValue(minute); + mDate.set(Calendar.MINUTE, minute); + onDateTimeChanged(); + } + + /** + * @return true if this is in 24 hour view else false. + */ + // 判断是否为24小时制 + public boolean is24HourView () { + return mIs24HourView; + } + + /** + * Set whether in 24 hour or AM/PM mode. + * + * @param is24HourView True for 24 hour mode. False for AM/PM mode. + */ + // 设置24小时制视图 + public void set24HourView(boolean is24HourView) { + if (mIs24HourView == is24HourView) { + return; + } + mIs24HourView = is24HourView; + mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); + // 24小时制隐藏AM/PM选择器 + int hour = getCurrentHourOfDay(); + updateHourControl(); + setCurrentHour(hour); + updateAmPmControl(); + } + + // 更新日期控件 + private void updateDateControl() { + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); + // 从当前日期向前推4天 + mDateSpinner.setDisplayedValues(null); + for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) { + cal.add(Calendar.DAY_OF_YEAR, 1); + mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal); + // 格式:月.日 星期几 + } + mDateSpinner.setDisplayedValues(mDateDisplayValues); + mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); + // 设置当前为中间值(第4天) + mDateSpinner.invalidate(); + // 重绘 + } + + // 更新AM/PM控件 + private void updateAmPmControl() { + if (mIs24HourView) { + mAmPmSpinner.setVisibility(View.GONE); + // 24小时制隐藏 + } else { + int index = mIsAm ? Calendar.AM : Calendar.PM; + // AM对应0,PM对应1 + mAmPmSpinner.setValue(index); + mAmPmSpinner.setVisibility(View.VISIBLE); + } + } + + // 更新小时控件 + private void updateHourControl() { + if (mIs24HourView) { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW); + // 24小时制:0-23 + } else { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); + // 12小时制:1-12 + } + } + + /** + * Set the callback that indicates the 'Set' button has been pressed. + * @param callback the callback, if null will do nothing + */ + // 设置日期时间变化监听器 + public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { + mOnDateTimeChangedListener = callback; + } + + // 触发日期时间变化事件 + private void onDateTimeChanged() { + if (mOnDateTimeChangedListener != null) { + mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), + getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); + } + } +} \ No newline at end of file diff --git a/src/ui/DateTimePickerDialog.java b/src/ui/DateTimePickerDialog.java new file mode 100644 index 0000000..2a195ea --- /dev/null +++ b/src/ui/DateTimePickerDialog.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import java.util.Calendar; + +import net.micode.notes.R; +import net.micode.notes.ui.DateTimePicker; +import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.text.format.DateFormat; +import android.text.format.DateUtils; + +public class DateTimePickerDialog extends AlertDialog implements OnClickListener { +// 日期时间选择器对话框,继承AlertDialog并实现点击监听器 + + private Calendar mDate = Calendar.getInstance(); + // 日期日历对象 + private boolean mIs24HourView; + // 是否为24小时制标志 + private OnDateTimeSetListener mOnDateTimeSetListener; + // 日期时间设置监听器 + private DateTimePicker mDateTimePicker; + // 日期时间选择器组件 + + public interface OnDateTimeSetListener { + // 日期时间设置监听器接口 + void OnDateTimeSet(AlertDialog dialog, long date); + // 日期时间设置回调方法 + } + + public DateTimePickerDialog(Context context, long date) { + // 构造方法 + super(context); + mDateTimePicker = new DateTimePicker(context); + // 创建日期时间选择器 + setView(mDateTimePicker); + // 设置对话框视图 + mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { + // 设置日期时间变化监听器 + public void onDateTimeChanged(DateTimePicker view, int year, int month, + int dayOfMonth, int hourOfDay, int minute) { + // 当日期时间选择器改变时更新mDate对象 + mDate.set(Calendar.YEAR, year); + mDate.set(Calendar.MONTH, month); + mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); + mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); + mDate.set(Calendar.MINUTE, minute); + updateTitle(mDate.getTimeInMillis()); + // 更新对话框标题 + } + }); + mDate.setTimeInMillis(date); + // 设置初始日期时间 + mDate.set(Calendar.SECOND, 0); + // 设置秒数为0 + mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); + // 设置选择器的当前日期时间 + + // 设置对话框按钮 + setButton(context.getString(R.string.datetime_dialog_ok), this); + // 确定按钮 + setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); + // 取消按钮 + + set24HourView(DateFormat.is24HourFormat(this.getContext())); + // 根据系统设置决定是否为24小时制 + updateTitle(mDate.getTimeInMillis()); + // 初始化对话框标题 + } + + public void set24HourView(boolean is24HourView) { + // 设置24小时制视图 + mIs24HourView = is24HourView; + } + + public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { + // 设置日期时间设置监听器 + mOnDateTimeSetListener = callBack; + } + + private void updateTitle(long date) { + // 更新对话框标题 + int flag = + DateUtils.FORMAT_SHOW_YEAR | // 显示年份 + DateUtils.FORMAT_SHOW_DATE | // 显示日期 + DateUtils.FORMAT_SHOW_TIME; // 显示时间 + flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; + // 这里有个bug:两边都是DateUtils.FORMAT_24HOUR,应该是三目运算符写错了 + // 应该为:flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR; + + setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); + // 设置格式化后的标题 + } + + public void onClick(DialogInterface arg0, int arg1) { + // 点击按钮回调 + if (mOnDateTimeSetListener != null) { + mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); + // 调用日期时间设置回调 + } + } + +} \ No newline at end of file diff --git a/src/ui/DropdownMenu.java b/src/ui/DropdownMenu.java new file mode 100644 index 0000000..755d073 --- /dev/null +++ b/src/ui/DropdownMenu.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.PopupMenu; +import android.widget.PopupMenu.OnMenuItemClickListener; + +import net.micode.notes.R; + +// 下拉菜单控件封装类 +public class DropdownMenu { + // 触发下拉的按钮控件 + private Button mButton; + // Android原生弹出菜单 + private PopupMenu mPopupMenu; + // 菜单项容器 + private Menu mMenu; + + // 构造方法:传入上下文、按钮和菜单资源ID + public DropdownMenu(Context context, Button button, int menuId) { + mButton = button; + // 设置按钮下拉图标样式 + mButton.setBackgroundResource(R.drawable.dropdown_icon); + // 创建弹出菜单(以按钮为锚点) + mPopupMenu = new PopupMenu(context, mButton); + // 获取菜单对象 + mMenu = mPopupMenu.getMenu(); + // 加载菜单布局 + mPopupMenu.getMenuInflater().inflate(menuId, mMenu); + // 点击按钮显示下拉菜单 + mButton.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + mPopupMenu.show(); + } + }); + } + + // 设置菜单项点击监听器 + public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { + if (mPopupMenu != null) { + mPopupMenu.setOnMenuItemClickListener(listener); + } + } + + // 根据ID查找菜单项 + public MenuItem findItem(int id) { + return mMenu.findItem(id); + } + + // 设置按钮显示文本 + public void setTitle(CharSequence title) { + mButton.setText(title); + } +} \ No newline at end of file diff --git a/src/ui/FoldersListAdapter.java b/src/ui/FoldersListAdapter.java new file mode 100644 index 0000000..785e53b --- /dev/null +++ b/src/ui/FoldersListAdapter.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +```java +// 文件夹列表适配器,继承CursorAdapter用于数据库游标数据展示 +public class FoldersListAdapter extends CursorAdapter { + // 数据库查询投影字段(需要查询的列) + public static final String [] PROJECTION = { + NoteColumns.ID, // 文件夹ID列 + NoteColumns.SNIPPET // 文件夹名称列(使用SNIPPET字段存储名称) + }; + + // 列索引常量,提高代码可读性 + public static final int ID_COLUMN = 0; // ID列索引 + public static final int NAME_COLUMN = 1; // 名称列索引 + + // 构造方法:初始化适配器 + public FoldersListAdapter(Context context, Cursor c) { + super(context, c); // 调用父类构造方法 + // TODO: 待补充初始化代码 + } + + // 创建新视图项(列表项) + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new FolderListItem(context); // 创建自定义列表项视图 + } + + // 绑定数据到视图项 + @Override + public void bindView(View view, Context context, Cursor cursor) { + if (view instanceof FolderListItem) { + // 判断是否为根文件夹:根文件夹显示特殊名称,否则显示文件夹名称 + String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context + .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + ((FolderListItem) view).bind(folderName); // 绑定名称到视图 + } + } + + // 根据位置获取文件夹名称(供外部调用) + public String getFolderName(Context context, int position) { + Cursor cursor = (Cursor) getItem(position); // 获取当前位置的游标 + // 同样的根文件夹判断逻辑 + return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context + .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + } + + // 自定义文件夹列表项视图(内部类) + private class FolderListItem extends LinearLayout { + private TextView mName; // 文件夹名称显示控件 + + // 构造方法:初始化列表项布局 + public FolderListItem(Context context) { + super(context); + inflate(context, R.layout.folder_list_item, this); // 加载布局文件 + mName = (TextView) findViewById(R.id.tv_folder_name); // 获取文本控件引用 + } + + // 绑定文件夹名称到文本控件 + public void bind(String name) { + mName.setText(name); + } + } +} +``` \ No newline at end of file diff --git a/src/ui/NoteEditActivity.java b/src/ui/NoteEditActivity.java new file mode 100644 index 0000000..7bb2e52 --- /dev/null +++ b/src/ui/NoteEditActivity.java @@ -0,0 +1,896 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlarmManager; +import android.app.AlertDialog; +import android.app.PendingIntent; +import android.app.SearchManager; +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Paint; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.format.DateUtils; +import android.text.style.BackgroundColorSpan; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.WindowManager; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.TextNote; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.model.WorkingNote.NoteSettingChangedListener; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.tool.ResourceParser.TextAppearanceResources; +import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener; +import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +```java +// 便签编辑活动,实现多种监听器接口 +public class NoteEditActivity extends Activity implements OnClickListener, + NoteSettingChangedListener, OnTextViewChangeListener { + + // 头部视图持有者,用于缓存视图引用 + private class HeadViewHolder { + public TextView tvModified; // 修改时间显示 + public ImageView ivAlertIcon; // 提醒图标 + public TextView tvAlertDate; // 提醒日期显示 + public ImageView ibSetBgColor; // 设置背景颜色按钮 + } + + // 背景颜色选择器按钮ID与颜色ID的映射 + private static final Map sBgSelectorBtnsMap = new HashMap(); + static { + sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); + sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); + sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); + sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); + sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); + } + + // 背景颜色ID与选中状态视图ID的映射 + private static final Map sBgSelectorSelectionMap = new HashMap(); + static { + sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); + sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); + sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); + sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); + sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); + } + + // 字体大小选择器视图ID与字体大小ID的映射 + private static final Map sFontSizeBtnsMap = new HashMap(); + static { + sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); + sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); + sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); + sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); + } + + // 字体大小ID与选中状态视图ID的映射 + private static final Map sFontSelectorSelectionMap = new HashMap(); + static { + sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); + } + + private static final String TAG = "NoteEditActivity"; // 日志标签 + + // 视图引用 + private HeadViewHolder mNoteHeaderHolder; // 头部视图持有者 + private View mHeadViewPanel; // 头部面板 + private View mNoteBgColorSelector; // 背景颜色选择器 + private View mFontSizeSelector; // 字体大小选择器 + private EditText mNoteEditor; // 便签编辑框 + private View mNoteEditorPanel; // 编辑面板 + private WorkingNote mWorkingNote; // 当前操作的便签对象 + + // 偏好设置相关 + private SharedPreferences mSharedPrefs; // 共享偏好设置 + private int mFontSizeId; // 当前字体大小ID + private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; // 字体大小偏好键 + + // 常量定义 + private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; // 快捷方式标题最大长度 + public static final String TAG_CHECKED = String.valueOf('\u221A'); // 复选框选中符号(√) + public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); // 复选框未选中符号(□) + + // 列表模式相关 + private LinearLayout mEditTextList; // 列表模式编辑容器 + private String mUserQuery; // 用户搜索查询词 + private Pattern mPattern; // 搜索高亮模式 + + // 创建活动 + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + this.setContentView(R.layout.note_edit); // 设置布局 + + // 初始化活动状态,失败则结束 + if (savedInstanceState == null && !initActivityState(getIntent())) { + finish(); + return; + } + initResources(); // 初始化资源 + } + + // 恢复实例状态(内存不足时可能被杀死) + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + // 从保存的状态中恢复便签ID + if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); + if (!initActivityState(intent)) { + finish(); + return; + } + Log.d(TAG, "Restoring from killed activity"); + } + } + + // 初始化活动状态 + private boolean initActivityState(Intent intent) { + mWorkingNote = null; + + // 处理查看便签的请求 + if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { + long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); + mUserQuery = ""; + + // 处理从搜索结果进入的情况 + if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) { + noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); + mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); + } + + // 检查便签是否存在 + if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { + Intent jump = new Intent(this, NotesListActivity.class); + startActivity(jump); + showToast(R.string.error_note_not_exist); + finish(); + return false; + } else { + mWorkingNote = WorkingNote.load(this, noteId); // 加载便签 + if (mWorkingNote == null) { + Log.e(TAG, "load note failed with note id" + noteId); + finish(); + return false; + } + } + // 隐藏软键盘 + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN + | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + + } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) { + // 新建或编辑便签 + long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); + int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID); + int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, + Notes.TYPE_WIDGET_INVALIDE); + int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, + ResourceParser.getDefaultBgId(this)); + + // 解析通话记录便签 + String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); + long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0); + if (callDate != 0 && phoneNumber != null) { + if (TextUtils.isEmpty(phoneNumber)) { + Log.w(TAG, "The call record number is null"); + } + long noteId = 0; + // 查找已存在的通话记录便签 + if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(), + phoneNumber, callDate)) > 0) { + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + Log.e(TAG, "load call note failed with note id" + noteId); + finish(); + return false; + } + } else { + // 创建新的通话记录便签 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, + widgetType, bgResId); + mWorkingNote.convertToCallNote(phoneNumber, callDate); + } + } else { + // 创建普通便签 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, + bgResId); + } + + // 显示软键盘 + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + } else { + Log.e(TAG, "Intent not specified action, should not support"); + finish(); + return false; + } + mWorkingNote.setOnSettingStatusChangedListener(this); // 设置监听器 + return true; + } + + // 活动恢复时调用 + @Override + protected void onResume() { + super.onResume(); + initNoteScreen(); // 初始化便签界面 + } + + // 初始化便签界面显示 + private void initNoteScreen() { + // 设置字体大小 + mNoteEditor.setTextAppearance(this, TextAppearanceResources + .getTexAppearanceResource(mFontSizeId)); + + // 根据模式初始化界面 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + switchToListMode(mWorkingNote.getContent()); // 切换到列表模式 + } else { + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); + mNoteEditor.setSelection(mNoteEditor.getText().length()); // 光标移至末尾 + } + + // 隐藏所有背景选择器选中状态 + for (Integer id : sBgSelectorSelectionMap.keySet()) { + findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); + } + + // 设置背景 + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + + // 设置修改时间 + mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, + mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE + | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME + | DateUtils.FORMAT_SHOW_YEAR)); + + showAlertHeader(); // 显示提醒头部 + } + + // 显示提醒头部信息 + private void showAlertHeader() { + if (mWorkingNote.hasClockAlert()) { + long time = System.currentTimeMillis(); + if (time > mWorkingNote.getAlertDate()) { + mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); // 提醒已过期 + } else { + mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( + mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS)); // 相对时间 + } + mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); + } else { + mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); + }; + } + + // 处理新Intent(例如从搜索进入) + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + initActivityState(intent); // 重新初始化活动状态 + } + + // 保存实例状态 + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + // 新便签需要先保存以生成ID + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); // 保存便签ID + Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); + } + + // 分发触摸事件,用于隐藏选择器 + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + // 点击背景颜色选择器外部时隐藏 + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE + && !inRangeOfView(mNoteBgColorSelector, ev)) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } + + // 点击字体大小选择器外部时隐藏 + if (mFontSizeSelector.getVisibility() == View.VISIBLE + && !inRangeOfView(mFontSizeSelector, ev)) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return super.dispatchTouchEvent(ev); + } + + // 判断触摸点是否在视图范围内 + private boolean inRangeOfView(View view, MotionEvent ev) { + int []location = new int[2]; + view.getLocationOnScreen(location); + int x = location[0]; + int y = location[1]; + if (ev.getX() < x + || ev.getX() > (x + view.getWidth()) + || ev.getY() < y + || ev.getY() > (y + view.getHeight())) { + return false; + } + return true; + } + + // 初始化资源(视图绑定等) + private void initResources() { + // 绑定头部视图 + mHeadViewPanel = findViewById(R.id.note_title); + mNoteHeaderHolder = new HeadViewHolder(); + mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); + mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); + mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); + mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color); + mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); // 设置点击监听 + + // 绑定编辑相关视图 + mNoteEditor = (EditText) findViewById(R.id.note_edit_view); + mNoteEditorPanel = findViewById(R.id.sv_note_edit); + + // 绑定背景颜色选择器并设置点击监听 + mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector); + for (int id : sBgSelectorBtnsMap.keySet()) { + ImageView iv = (ImageView) findViewById(id); + iv.setOnClickListener(this); + } + + // 绑定字体大小选择器并设置点击监听 + mFontSizeSelector = findViewById(R.id.font_size_selector); + for (int id : sFontSizeBtnsMap.keySet()) { + View view = findViewById(id); + view.setOnClickListener(this); + }; + + // 初始化偏好设置 + mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); + mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); + // 修复字体大小ID超出范围的bug + if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { + mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; + } + + mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); // 列表模式容器 + } + + // 活动暂停时保存便签 + @Override + protected void onPause() { + super.onPause(); + if(saveNote()) { + Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length()); + } + clearSettingState(); // 清理设置状态 + } + + // 更新桌面小部件 + private void updateWidget() { + Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + // 根据小部件类型设置对应的接收器 + if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { + intent.setClass(this, NoteWidgetProvider_2x.class); + } else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) { + intent.setClass(this, NoteWidgetProvider_4x.class); + } else { + Log.e(TAG, "Unspported widget type"); + return; + } + + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { + mWorkingNote.getWidgetId() // 小部件ID + }); + + sendBroadcast(intent); + setResult(RESULT_OK, intent); + } + + // 点击事件处理 + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.btn_set_bg_color) { + // 显示背景颜色选择器 + mNoteBgColorSelector.setVisibility(View.VISIBLE); + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.VISIBLE); + } else if (sBgSelectorBtnsMap.containsKey(id)) { + // 背景颜色选择 + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.GONE); + mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); // 设置新背景颜色 + mNoteBgColorSelector.setVisibility(View.GONE); // 隐藏选择器 + } else if (sFontSizeBtnsMap.containsKey(id)) { + // 字体大小选择 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); + mFontSizeId = sFontSizeBtnsMap.get(id); // 设置新字体大小 + mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); // 保存偏好 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); + // 根据模式更新字体显示 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + getWorkingText(); + switchToListMode(mWorkingNote.getContent()); + } else { + mNoteEditor.setTextAppearance(this, + TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + } + mFontSizeSelector.setVisibility(View.GONE); // 隐藏选择器 + } + } + + // 返回键处理 + @Override + public void onBackPressed() { + if(clearSettingState()) { // 如果隐藏了选择器,则不退出 + return; + } + + saveNote(); // 保存便签 + super.onBackPressed(); // 执行默认返回 + } + + // 清理设置状态(隐藏选择器) + private boolean clearSettingState() { + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return false; + } + + // 背景颜色改变回调 + public void onBackgroundColorChanged() { + // 显示新背景颜色的选中状态 + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.VISIBLE); + // 更新背景 + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + } + + // 准备选项菜单 + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + if (isFinishing()) { + return true; + } + clearSettingState(); // 清理设置状态 + menu.clear(); // 清除旧菜单 + + // 根据便签类型加载不同菜单 + if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { + getMenuInflater().inflate(R.menu.call_note_edit, menu); // 通话记录菜单 + } else { + getMenuInflater().inflate(R.menu.note_edit, menu); // 普通便签菜单 + } + + // 根据列表模式设置菜单项文本 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); + } else { + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); + } + + // 根据是否有提醒显示/隐藏菜单项 + if (mWorkingNote.hasClockAlert()) { + menu.findItem(R.id.menu_alert).setVisible(false); + } else { + menu.findItem(R.id.menu_delete_remind).setVisible(false); + } + return true; + } + + // 菜单项选择处理 + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_new_note: + createNewNote(); // 新建便签 + break; + case R.id.menu_delete: + // 删除确认对话框 + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(getString(R.string.alert_title_delete)); + builder.setIcon(android.R.drawable.ic_dialog_alert); + builder.setMessage(getString(R.string.alert_message_delete_note)); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteCurrentNote(); // 删除当前便签 + finish(); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case R.id.menu_font_size: + // 显示字体大小选择器 + mFontSizeSelector.setVisibility(View.VISIBLE); + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); + break; + case R.id.menu_list_mode: + // 切换列表模式 + mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ? + TextNote.MODE_CHECK_LIST : 0); + break; + case R.id.menu_share: + // 分享便签 + getWorkingText(); + sendTo(this, mWorkingNote.getContent()); + break; + case R.id.menu_send_to_desktop: + // 发送到桌面快捷方式 + sendToDesktop(); + break; + case R.id.menu_alert: + // 设置提醒 + setReminder(); + break; + case R.id.menu_delete_remind: + // 删除提醒 + mWorkingNote.setAlertDate(0, false); + break; + default: + break; + } + return true; + } + + // 设置提醒时间 + private void setReminder() { + DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); + d.setOnDateTimeSetListener(new OnDateTimeSetListener() { + public void OnDateTimeSet(AlertDialog dialog, long date) { + mWorkingNote.setAlertDate(date, true); // 设置提醒日期 + } + }); + d.show(); + } + + // 分享便签内容 + private void sendTo(Context context, String info) { + Intent intent = new Intent(Intent.ACTION_SEND); + intent.putExtra(Intent.EXTRA_TEXT, info); + intent.setType("text/plain"); // 纯文本类型 + context.startActivity(intent); + } + + // 创建新便签 + private void createNewNote() { + saveNote(); // 先保存当前便签 + finish(); // 结束当前活动 + // 启动新的便签编辑活动 + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); + startActivity(intent); + } + + // 删除当前便签 + private void deleteCurrentNote() { + if (mWorkingNote.existInDatabase()) { + HashSet ids = new HashSet(); + long id = mWorkingNote.getNoteId(); + if (id != Notes.ID_ROOT_FOLDER) { + ids.add(id); + } else { + Log.d(TAG, "Wrong note id, should not happen"); + } + // 根据同步模式选择删除方式 + if (!isSyncMode()) { + if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) { + Log.e(TAG, "Delete Note error"); + } + } else { + if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) { + Log.e(TAG, "Move notes to trash folder error, should not happens"); + } + } + } + mWorkingNote.markDeleted(true); // 标记为已删除 + } + + // 检查是否为同步模式 + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + // 提醒时间改变回调 + public void onClockAlertChanged(long date, boolean set) { + // 未保存的便签需要先保存 + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + if (mWorkingNote.getNoteId() > 0) { + // 设置闹钟提醒 + Intent intent = new Intent(this, AlarmReceiver.class); + intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId())); + PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); + AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE)); + showAlertHeader(); // 更新提醒显示 + if(!set) { + alarmManager.cancel(pendingIntent); // 取消提醒 + } else { + alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); // 设置提醒 + } + } else { + // 空便签不能设置提醒 + Log.e(TAG, "Clock alert setting error"); + showToast(R.string.error_note_empty_for_clock); + } + } + + // 小部件改变回调 + public void onWidgetChanged() { + updateWidget(); // 更新小部件 + } + + // 列表模式:删除文本项回调 + public void onEditTextDelete(int index, String text) { + int childCount = mEditTextList.getChildCount(); + if (childCount == 1) { // 至少保留一项 + return; + } + + // 更新后续项的索引 + for (int i = index + 1; i < childCount; i++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i - 1); + } + + mEditTextList.removeViewAt(index); // 删除视图 + NoteEditText edit = null; + // 确定焦点位置 + if(index == 0) { + edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById( + R.id.et_edit_text); + } else { + edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById( + R.id.et_edit_text); + } + int length = edit.length(); + edit.append(text); // 将删除的文本追加到前一项 + edit.requestFocus(); + edit.setSelection(length); + } + + // 列表模式:回车换行回调 + public void onEditTextEnter(int index, String text) { + if(index > mEditTextList.getChildCount()) { + Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); + } + + View view = getListItem(text, index); // 创建新列表项 + mEditTextList.addView(view, index); // 插入视图 + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.requestFocus(); + edit.setSelection(0); + // 更新后续项的索引 + for (int i = index + 1; i < mEditTextList.getChildCount(); i++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i); + } + } + + // 切换到列表模式 + private void switchToListMode(String text) { + mEditTextList.removeAllViews(); // 清除旧视图 + String[] items = text.split("\n"); // 按换行符分割 + int index = 0; + for (String item : items) { + if(!TextUtils.isEmpty(item)) { + mEditTextList.addView(getListItem(item, index)); // 添加列表项 + index++; + } + } + mEditTextList.addView(getListItem("", index)); // 添加空项用于输入 + mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); // 聚焦 + + mNoteEditor.setVisibility(View.GONE); // 隐藏普通编辑器 + mEditTextList.setVisibility(View.VISIBLE); // 显示列表容器 + } + + // 获取搜索高亮结果 + private Spannable getHighlightQueryResult(String fullText, String userQuery) { + SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); + if (!TextUtils.isEmpty(userQuery)) { + mPattern = Pattern.compile(userQuery); // 编译搜索模式 + Matcher m = mPattern.matcher(fullText); + int start = 0; + // 为所有匹配项添加高亮背景 + while (m.find(start)) { + spannable.setSpan( + new BackgroundColorSpan(this.getResources().getColor( + R.color.user_query_highlight)), m.start(), m.end(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + start = m.end(); + } + } + return spannable; + } + + // 获取列表项视图 + private View getListItem(String item, int index) { + View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); + final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); + // 复选框状态改变监听 + cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); // 添加删除线 + } else { + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); // 恢复正常 + } + } + }); + + // 解析复选框状态标记 + if (item.startsWith(TAG_CHECKED)) { + cb.setChecked(true); + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + item = item.substring(TAG_CHECKED.length(), item.length()).trim(); // 移除标记 + } else if (item.startsWith(TAG_UNCHECKED)) { + cb.setChecked(false); + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); + item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); // 移除标记 + } + + edit.setOnTextViewChangeListener(this); // 设置文本变化监听 + edit.setIndex(index); // 设置索引 + edit.setText(getHighlightQueryResult(item, mUserQuery)); // 设置文本(带高亮) + return view; + } + + // 文本变化回调(列表模式) + public void onTextChange(int index, boolean hasText) { + if (index >= mEditTextList.getChildCount()) { + Log.e(TAG, "Wrong index, should not happen"); + return; + } + // 根据是否有文本显示/隐藏复选框 + if(hasText) { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE); + } else { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE); + } + } + + // 列表模式改变回调 + public void onCheckListModeChanged(int oldMode, int newMode) { + if (newMode == TextNote.MODE_CHECK_LIST) { + // 切换到列表模式 + switchToListMode(mNoteEditor.getText().toString()); + } else { + // 切换到普通模式 + if (!getWorkingText()) { + // 移除未选中标记 + mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ", + "")); + } + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); + mEditTextList.setVisibility(View.GONE); // 隐藏列表 + mNoteEditor.setVisibility(View.VISIBLE); // 显示编辑器 + } + } + + // 获取工作文本(当前编辑内容) + private boolean getWorkingText() { + boolean hasChecked = false; + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + // 列表模式:拼接所有项 + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < mEditTextList.getChildCount(); i++) { + View view = mEditTextList.getChildAt(i); + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + if (!TextUtils.isEmpty(edit.getText())) { + if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) { + sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n"); + hasChecked = true; + } else { + sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n"); + } + } + } + mWorkingNote.setWorkingText(sb.toString()); + } else { + // 普通模式:直接获取编辑器文本 + mWorkingNote.setWorkingText(mNoteEditor.getText().toString()); + } + return hasChecked; + } + + // 保存便签 + private boolean saveNote() { + getWorkingText(); // 获取当前文本 + boolean saved = mWorkingNote.saveNote(); // 保存到数据库 + if (saved) { + setResult(RESULT_OK); // 设置返回结果 + } + return saved; + } + + // 发送到桌面快捷方式 + private void sendToDesktop() { + // 确保便签已保存 + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + + if (mWorkingNote.getNoteId() > 0) { + // 创建快捷方式Intent + Intent sender = new Intent(); + Intent shortcutIntent = new Intent(this, NoteEditActivity.class); + shortcutIntent.setAction(Intent.ACTION_VIEW); + shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); + sender.putExtra(Intent.EXTRA_SHORTCUT_NAME, + makeShortcutIconTitle(mWorkingNote.getContent())); // 快捷方式名称 + sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, + Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app)); // 图标 + sender.putExtra("duplicate", true); // 允许 \ No newline at end of file diff --git a/src/ui/NoteEditText.java b/src/ui/NoteEditText.java new file mode 100644 index 0000000..c880f99 --- /dev/null +++ b/src/ui/NoteEditText.java @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.graphics.Rect; +import android.text.Layout; +import android.text.Selection; +import android.text.Spanned; +import android.text.TextUtils; +import android.text.style.URLSpan; +import android.util.AttributeSet; +import android.util.Log; +import android.view.ContextMenu; +import android.view.KeyEvent; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.widget.EditText; + +import net.micode.notes.R; + +import java.util.HashMap; +import java.util.Map; + +```java +// 自定义便签编辑文本控件,扩展EditText功能 +public class NoteEditText extends EditText { + private static final String TAG = "NoteEditText"; // 日志标签 + + private int mIndex; // 当前编辑框在列表中的索引 + private int mSelectionStartBeforeDelete; // 删除前的光标起始位置 + + // URL协议常量 + private static final String SCHEME_TEL = "tel:" ; // 电话协议 + private static final String SCHEME_HTTP = "http:" ; // HTTP协议 + private static final String SCHEME_EMAIL = "mailto:" ; // 邮件协议 + + // 协议与操作字符串资源的映射 + private static final Map sSchemaActionResMap = new HashMap(); + static { + sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); // 电话链接 + sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); // 网页链接 + sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); // 邮件链接 + } + + // 文本变化监听器接口,由NoteEditActivity实现 + public interface OnTextViewChangeListener { + /** + * 删除当前编辑框(当按删除键且文本为空时) + */ + void onEditTextDelete(int index, String text); + + /** + * 在当前编辑框后添加新编辑框(当按回车键时) + */ + void onEditTextEnter(int index, String text); + + /** + * 文本变化时显示/隐藏选项 + */ + void onTextChange(int index, boolean hasText); + } + + private OnTextViewChangeListener mOnTextViewChangeListener; // 监听器引用 + + // 构造方法1:简单构造 + public NoteEditText(Context context) { + super(context, null); + mIndex = 0; // 默认索引为0 + } + + // 设置当前索引 + public void setIndex(int index) { + mIndex = index; + } + + // 设置文本变化监听器 + public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { + mOnTextViewChangeListener = listener; + } + + // 构造方法2:带属性集 + public NoteEditText(Context context, AttributeSet attrs) { + super(context, attrs, android.R.attr.editTextStyle); + } + + // 构造方法3:带属性集和样式 + public NoteEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + // TODO: 待补充初始化代码 + } + + // 触摸事件处理:实现精确点击定位 + @Override + public boolean onTouchEvent(MotionEvent event) { + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: // 按下事件 + // 计算触摸点对应的文本偏移量 + int x = (int) event.getX(); + int y = (int) event.getY(); + x -= getTotalPaddingLeft(); // 减去内边距 + y -= getTotalPaddingTop(); + x += getScrollX(); // 加上滚动偏移 + y += getScrollY(); + + Layout layout = getLayout(); + int line = layout.getLineForVertical(y); // 获取垂直方向行号 + int off = layout.getOffsetForHorizontal(line, x); // 获取水平方向偏移 + Selection.setSelection(getText(), off); // 设置选中位置 + break; + } + + return super.onTouchEvent(event); // 调用父类处理 + } + + // 按键按下事件 + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + switch (keyCode) { + case KeyEvent.KEYCODE_ENTER: // 回车键 + if (mOnTextViewChangeListener != null) { + return false; // 由监听器处理 + } + break; + case KeyEvent.KEYCODE_DEL: // 删除键 + mSelectionStartBeforeDelete = getSelectionStart(); // 保存删除前位置 + break; + default: + break; + } + return super.onKeyDown(keyCode, event); + } + + // 按键释放事件 + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) { + switch(keyCode) { + case KeyEvent.KEYCODE_DEL: // 删除键释放 + if (mOnTextViewChangeListener != null) { + // 如果在开头删除且不是第一个编辑框,则删除整个编辑框 + if (0 == mSelectionStartBeforeDelete && mIndex != 0) { + mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); + return true; // 已处理 + } + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + case KeyEvent.KEYCODE_ENTER: // 回车键释放 + if (mOnTextViewChangeListener != null) { + int selectionStart = getSelectionStart(); // 获取光标位置 + // 分割文本:光标后部分作为新编辑框内容 + String text = getText().subSequence(selectionStart, length()).toString(); + setText(getText().subSequence(0, selectionStart)); // 保留光标前部分 + mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); // 插入新编辑框 + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + default: + break; + } + return super.onKeyUp(keyCode, event); + } + + // 焦点变化回调 + @Override + protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { + if (mOnTextViewChangeListener != null) { + // 失去焦点且文本为空时隐藏选项,否则显示选项 + if (!focused && TextUtils.isEmpty(getText())) { + mOnTextViewChangeListener.onTextChange(mIndex, false); + } else { + mOnTextViewChangeListener.onTextChange(mIndex, true); + } + } + super.onFocusChanged(focused, direction, previouslyFocusedRect); + } + + // 创建上下文菜单(长按菜单) + @Override + protected void onCreateContextMenu(ContextMenu menu) { + if (getText() instanceof Spanned) { // 检查是否为富文本 + int selStart = getSelectionStart(); // 选择起始位置 + int selEnd = getSelectionEnd(); // 选择结束位置 + + int min = Math.min(selStart, selEnd); // 获取较小值 + int max = Math.max(selStart, selEnd); // 获取较大值 + + // 获取选中范围内的URL链接 + final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); + if (urls.length == 1) { // 只有一个链接时 + int defaultResId = 0; + // 根据URL协议类型确定菜单项文本 + for(String schema: sSchemaActionResMap.keySet()) { + if(urls[0].getURL().indexOf(schema) >= 0) { + defaultResId = sSchemaActionResMap.get(schema); + break; + } + } + + if (defaultResId == 0) { + defaultResId = R.string.note_link_other; // 其他类型链接 + } + + // 添加上下文菜单项 + menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( + new OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) { + // 点击后打开链接 + urls[0].onClick(NoteEditText.this); + return true; + } + }); + } + } + super.onCreateContextMenu(menu); // 调用父类创建默认菜单 + } +} +``` \ No newline at end of file diff --git a/src/ui/NoteItemData.java b/src/ui/NoteItemData.java new file mode 100644 index 0000000..4f65dd1 --- /dev/null +++ b/src/ui/NoteItemData.java @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.text.TextUtils; + +import net.micode.notes.data.Contact; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.tool.DataUtils; + + +```java +// 便签项数据类,封装便签的数据库记录信息 +public class NoteItemData { + // 数据库查询投影字段(需要查询的列) + static final String [] PROJECTION = new String [] { + NoteColumns.ID, // 便签ID + NoteColumns.ALERTED_DATE, // 提醒日期 + NoteColumns.BG_COLOR_ID, // 背景颜色ID + NoteColumns.CREATED_DATE, // 创建日期 + NoteColumns.HAS_ATTACHMENT, // 是否有附件 + NoteColumns.MODIFIED_DATE, // 修改日期 + NoteColumns.NOTES_COUNT, // 子项数量(针对文件夹) + NoteColumns.PARENT_ID, // 父文件夹ID + NoteColumns.SNIPPET, // 便签内容摘要 + NoteColumns.TYPE, // 类型(便签/文件夹) + NoteColumns.WIDGET_ID, // 桌面小部件ID + NoteColumns.WIDGET_TYPE, // 桌面小部件类型 + }; + + // 列索引常量,提高代码可读性 + private static final int ID_COLUMN = 0; // ID列索引 + private static final int ALERTED_DATE_COLUMN = 1; // 提醒日期列索引 + private static final int BG_COLOR_ID_COLUMN = 2; // 背景颜色ID列索引 + private static final int CREATED_DATE_COLUMN = 3; // 创建日期列索引 + private static final int HAS_ATTACHMENT_COLUMN = 4; // 附件标志列索引 + private static final int MODIFIED_DATE_COLUMN = 5; // 修改日期列索引 + private static final int NOTES_COUNT_COLUMN = 6; // 便签数量列索引 + private static final int PARENT_ID_COLUMN = 7; // 父ID列索引 + private static final int SNIPPET_COLUMN = 8; // 摘要列索引 + private static final int TYPE_COLUMN = 9; // 类型列索引 + private static final int WIDGET_ID_COLUMN = 10; // 小部件ID列索引 + private static final int WIDGET_TYPE_COLUMN = 11; // 小部件类型列索引 + + // 数据字段 + private long mId; // 便签ID + private long mAlertDate; // 提醒日期 + private int mBgColorId; // 背景颜色ID + private long mCreatedDate; // 创建日期 + private boolean mHasAttachment; // 是否有附件 + private long mModifiedDate; // 修改日期 + private int mNotesCount; // 子便签数量(文件夹用) + private long mParentId; // 父文件夹ID + private String mSnippet; // 内容摘要 + private int mType; // 类型:便签/文件夹 + private int mWidgetId; // 桌面小部件ID + private int mWidgetType; // 桌面小部件类型 + private String mName; // 联系人姓名(通话记录用) + private String mPhoneNumber; // 电话号码(通话记录用) + + // 位置状态标志 + private boolean mIsLastItem; // 是否为最后一项 + private boolean mIsFirstItem; // 是否为第一项 + private boolean mIsOnlyOneItem; // 是否只有一项 + private boolean mIsOneNoteFollowingFolder; // 是否是一个便签跟在文件夹后面 + private boolean mIsMultiNotesFollowingFolder;// 是否是多个便签跟在文件夹后面 + + // 构造方法:从Cursor解析数据 + public NoteItemData(Context context, Cursor cursor) { + // 从游标中读取各字段数据 + mId = cursor.getLong(ID_COLUMN); + mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); + mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); + mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); + mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; + mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); + mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); + mParentId = cursor.getLong(PARENT_ID_COLUMN); + mSnippet = cursor.getString(SNIPPET_COLUMN); + // 移除便签中的复选框标记符号 + mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( + NoteEditActivity.TAG_UNCHECKED, ""); + mType = cursor.getInt(TYPE_COLUMN); + mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); + mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); + + mPhoneNumber = ""; + // 如果是通话记录文件夹中的便签 + if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { + // 获取电话号码 + mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); + if (!TextUtils.isEmpty(mPhoneNumber)) { + // 根据电话号码查询联系人姓名 + mName = Contact.getContact(context, mPhoneNumber); + if (mName == null) { + mName = mPhoneNumber; // 无联系人则显示电话号码 + } + } + } + + if (mName == null) { + mName = ""; + } + checkPostion(cursor); // 检查当前位置状态 + } + + // 检查当前项在列表中的位置状态 + private void checkPostion(Cursor cursor) { + mIsLastItem = cursor.isLast() ? true : false; // 是否为最后一项 + mIsFirstItem = cursor.isFirst() ? true : false; // 是否为第一项 + mIsOnlyOneItem = (cursor.getCount() == 1); // 是否只有一项 + + mIsMultiNotesFollowingFolder = false; + mIsOneNoteFollowingFolder = false; + + // 检查是否是一个/多个便签跟在文件夹后面(用于UI分隔线显示) + if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { + int position = cursor.getPosition(); + if (cursor.moveToPrevious()) { // 移动到前一项 + // 如果前一项是文件夹类型 + if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER + || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { + if (cursor.getCount() > (position + 1)) { + mIsMultiNotesFollowingFolder = true; // 多个便签在文件夹后 + } else { + mIsOneNoteFollowingFolder = true; // 单个便签在文件夹后 + } + } + // 移回当前位置 + if (!cursor.moveToNext()) { + throw new IllegalStateException("cursor move to previous but can't move back"); + } + } + } + } + + // 位置状态判断方法 + public boolean isOneFollowingFolder() { + return mIsOneNoteFollowingFolder; // 是否是单个便签跟在文件夹后 + } + + public boolean isMultiFollowingFolder() { + return mIsMultiNotesFollowingFolder; // 是否是多个便签跟在文件夹后 + } + + public boolean isLast() { + return mIsLastItem; // 是否为最后一项 + } + + public String getCallName() { + return mName; // 获取联系人姓名(通话记录用) + } + + public boolean isFirst() { + return mIsFirstItem; // 是否为第一项 + } + + public boolean isSingle() { + return mIsOnlyOneItem; // 是否只有一项 + } + + // Getter方法:获取便签ID + public long getId() { + return mId; + } + + // Getter方法:获取提醒日期 + public long getAlertDate() { + return mAlertDate; + } + + // Getter方法:获取创建日期 + public long getCreatedDate() { + return mCreatedDate; + } + + // Getter方法:检查是否有附件 + public boolean hasAttachment() { + return mHasAttachment; + } + + // Getter方法:获取修改日期 + public long getModifiedDate() { + return mModifiedDate; + } + + // Getter方法:获取背景颜色ID + public int getBgColorId() { + return mBgColorId; + } + + // Getter方法:获取父文件夹ID + public long getParentId() { + return mParentId; + } + + // Getter方法:获取子便签数量 + public int getNotesCount() { + return mNotesCount; + } + + // Getter方法:获取文件夹ID(与getParentId相同) + public long getFolderId () { + return mParentId; + } + + // Getter方法:获取类型(便签/文件夹) + public int getType() { + return mType; + } + + // Getter方法:获取桌面小部件类型 + public int getWidgetType() { + return mWidgetType; + } + + // Getter方法:获取桌面小部件ID + public int getWidgetId() { + return mWidgetId; + } + + // Getter方法:获取内容摘要 + public String getSnippet() { + return mSnippet; + } + + // 判断方法:是否有提醒设置 + public boolean hasAlert() { + return (mAlertDate > 0); + } + + // 判断方法:是否为通话记录 + public boolean isCallRecord() { + return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); + } + + // 静态方法:从游标获取便签类型 + public static int getNoteType(Cursor cursor) { + return cursor.getInt(TYPE_COLUMN); + } +} +``` \ No newline at end of file diff --git a/src/ui/NotesListActivity.java b/src/ui/NotesListActivity.java new file mode 100644 index 0000000..d1ff8ab --- /dev/null +++ b/src/ui/NotesListActivity.java @@ -0,0 +1,982 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.appwidget.AppWidgetManager; +import android.content.AsyncQueryHandler; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.os.AsyncTask; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.util.Log; +import android.view.ActionMode; +import android.view.ContextMenu; +import android.view.ContextMenu.ContextMenuInfo; +import android.view.Display; +import android.view.HapticFeedbackConstants; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.View.OnCreateContextMenuListener; +import android.view.View.OnTouchListener; +import android.view.inputmethod.InputMethodManager; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.AdapterView.OnItemLongClickListener; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ListView; +import android.widget.PopupMenu; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.remote.GTaskSyncService; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.tool.BackupUtils; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.HashSet; + +```java +// 便签列表活动,负责显示和管理便签/文件夹列表 +// 便签列表活动,负责显示和管理便签/文件夹列表 +public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { + // 查询令牌常量 + private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; // 文件夹便签列表查询 + private static final int FOLDER_LIST_QUERY_TOKEN = 1; // 文件夹列表查询 + + // 上下文菜单项ID + private static final int MENU_FOLDER_DELETE = 0; // 删除文件夹 + private static final int MENU_FOLDER_VIEW = 1; // 查看文件夹 + private static final int MENU_FOLDER_CHANGE_NAME = 2; // 重命名文件夹 + + // 偏好设置键:是否已添加介绍便签 + private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; + + // 列表编辑状态枚举 + private enum ListEditState { + NOTE_LIST, // 根目录列表 + SUB_FOLDER, // 子文件夹 + CALL_RECORD_FOLDER // 通话记录文件夹 + }; + + private ListEditState mState; // 当前状态 + private BackgroundQueryHandler mBackgroundQueryHandler; // 后台查询处理器 + private NotesListAdapter mNotesListAdapter; // 列表适配器 + private ListView mNotesListView; // 列表视图 + private Button mAddNewNote; // 添加新便签按钮 + private boolean mDispatch; // 是否分发触摸事件标志 + private int mOriginY; // 触摸起始Y坐标 + private int mDispatchY; // 分发事件的Y坐标 + private TextView mTitleBar; // 标题栏 + private long mCurrentFolderId; // 当前文件夹ID + private ContentResolver mContentResolver; // 内容解析器 + private ModeCallback mModeCallBack; // 多选模式回调 + private static final String TAG = "NotesListActivity"; // 日志标签 + public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; // 列表滚动速率 + + private NoteItemData mFocusNoteDataItem; // 当前焦点便签数据项 + + // SQL查询条件 + private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; // 普通查询 + private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" + + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" + + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + + NoteColumns.NOTES_COUNT + ">0)"; // 根文件夹查询 + + // 请求码常量 + private final static int REQUEST_CODE_OPEN_NODE = 102; // 打开便签请求码 + private final static int REQUEST_CODE_NEW_NODE = 103; // 新建便签请求码 + + // 创建活动 + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.note_list); // 设置布局 + initResources(); // 初始化资源 + + // 首次使用时添加介绍便签 + setAppInfoFromRawRes(); + } + + // 活动结果回调 + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode == RESULT_OK + && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { + mNotesListAdapter.changeCursor(null); // 清空游标,触发重新查询 + } else { + super.onActivityResult(requestCode, resultCode, data); + } + } + + // 从资源文件设置应用介绍便签 + private void setAppInfoFromRawRes() { + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); + // 检查是否已添加介绍便签 + if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { + StringBuilder sb = new StringBuilder(); + InputStream in = null; + try { + in = getResources().openRawResource(R.raw.introduction); // 读取原始资源 + if (in != null) { + InputStreamReader isr = new InputStreamReader(in); + BufferedReader br = new BufferedReader(isr); + char [] buf = new char[1024]; + int len = 0; + while ((len = br.read(buf)) > 0) { + sb.append(buf, 0, len); // 读取文件内容 + } + } else { + Log.e(TAG, "Read introduction file error"); + return; + } + } catch (IOException e) { + e.printStackTrace(); + return; + } finally { + if(in != null) { + try { + in.close(); // 关闭输入流 + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + // 创建介绍便签 + WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, + AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, + ResourceParser.RED); + note.setWorkingText(sb.toString()); // 设置内容 + if (note.saveNote()) { // 保存便签 + sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); // 更新偏好设置 + } else { + Log.e(TAG, "Save introduction note error"); + return; + } + } + } + + // 活动启动时开始异步查询 + @Override + protected void onStart() { + super.onStart(); + startAsyncNotesListQuery(); // 开始异步查询便签列表 + } + + // 初始化资源 + private void initResources() { + mContentResolver = this.getContentResolver(); // 获取内容解析器 + mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); // 创建后台查询处理器 + mCurrentFolderId = Notes.ID_ROOT_FOLDER; // 初始化为根文件夹 + mNotesListView = (ListView) findViewById(R.id.notes_list); // 获取列表视图 + // 添加列表脚部视图 + mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), + null, false); + mNotesListView.setOnItemClickListener(new OnListItemClickListener()); // 设置列表项点击监听 + mNotesListView.setOnItemLongClickListener(this); // 设置列表项长按监听 + mNotesListAdapter = new NotesListAdapter(this); // 创建适配器 + mNotesListView.setAdapter(mNotesListAdapter); // 设置适配器 + mAddNewNote = (Button) findViewById(R.id.btn_new_note); // 获取添加按钮 + mAddNewNote.setOnClickListener(this); // 设置点击监听 + mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); // 设置触摸监听 + mDispatch = false; // 初始化事件分发标志 + mDispatchY = 0; // 初始化分发Y坐标 + mOriginY = 0; // 初始化原始Y坐标 + mTitleBar = (TextView) findViewById(R.id.tv_title_bar); // 获取标题栏 + mState = ListEditState.NOTE_LIST; // 初始状态为便签列表 + mModeCallBack = new ModeCallback(); // 创建多选模式回调 + } + + // 多选模式回调类(批量操作) + private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { + private DropdownMenu mDropDownMenu; // 下拉菜单 + private ActionMode mActionMode; // 操作模式 + private MenuItem mMoveMenu; // 移动菜单项 + + // 创建操作模式 + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + getMenuInflater().inflate(R.menu.note_list_options, menu); // 加载菜单布局 + menu.findItem(R.id.delete).setOnMenuItemClickListener(this); // 设置删除监听 + mMoveMenu = menu.findItem(R.id.move); // 获取移动菜单项 + // 根据条件显示/隐藏移动菜单 + if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER + || DataUtils.getUserFolderCount(mContentResolver) == 0) { + mMoveMenu.setVisible(false); // 隐藏移动菜单 + } else { + mMoveMenu.setVisible(true); // 显示移动菜单 + mMoveMenu.setOnMenuItemClickListener(this); // 设置点击监听 + } + mActionMode = mode; // 保存操作模式引用 + mNotesListAdapter.setChoiceMode(true); // 设置适配器为选择模式 + mNotesListView.setLongClickable(false); // 禁用长按 + mAddNewNote.setVisibility(View.GONE); // 隐藏添加按钮 + + // 设置自定义视图(下拉菜单) + View customView = LayoutInflater.from(NotesListActivity.this).inflate( + R.layout.note_list_dropdown_menu, null); + mode.setCustomView(customView); + mDropDownMenu = new DropdownMenu(NotesListActivity.this, + (Button) customView.findViewById(R.id.selection_menu), + R.menu.note_list_dropdown); // 创建下拉菜单 + mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ + public boolean onMenuItemClick(MenuItem item) { + // 全选/取消全选 + mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); + updateMenu(); // 更新菜单 + return true; + } + }); + return true; + } + + // 更新菜单显示 + private void updateMenu() { + int selectedCount = mNotesListAdapter.getSelectedCount(); // 获取选中数量 + // 更新下拉菜单标题 + String format = getResources().getString(R.string.menu_select_title, selectedCount); + mDropDownMenu.setTitle(format); + MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); + if (item != null) { + if (mNotesListAdapter.isAllSelected()) { + item.setChecked(true); // 设置为选中状态 + item.setTitle(R.string.menu_deselect_all); // 显示取消全选 + } else { + item.setChecked(false); // 设置为未选中 + item.setTitle(R.string.menu_select_all); // 显示全选 + } + } + } + + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + return false; // 不准备菜单 + } + + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + return false; // 不处理操作项点击 + } + + // 销毁操作模式 + public void onDestroyActionMode(ActionMode mode) { + mNotesListAdapter.setChoiceMode(false); // 退出选择模式 + mNotesListView.setLongClickable(true); // 启用长按 + mAddNewNote.setVisibility(View.VISIBLE); // 显示添加按钮 + } + + // 结束操作模式 + public void finishActionMode() { + mActionMode.finish(); + } + + // 列表项选中状态变化 + public void onItemCheckedStateChanged(ActionMode mode, int position, long id, + boolean checked) { + mNotesListAdapter.setCheckedItem(position, checked); // 更新选中状态 + updateMenu(); // 更新菜单 + } + + // 菜单项点击处理 + public boolean onMenuItemClick(MenuItem item) { + if (mNotesListAdapter.getSelectedCount() == 0) { + Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), + Toast.LENGTH_SHORT).show(); // 提示未选择任何项 + return true; + } + + switch (item.getItemId()) { + case R.id.delete: // 删除操作 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(getString(R.string.alert_title_delete)); + builder.setIcon(android.R.drawable.ic_dialog_alert); + builder.setMessage(getString(R.string.alert_message_delete_notes, + mNotesListAdapter.getSelectedCount())); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + batchDelete(); // 批量删除 + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); // 显示确认对话框 + break; + case R.id.move: // 移动操作 + startQueryDestinationFolders(); // 查询目标文件夹 + break; + default: + return false; + } + return true; + } + } + + // 新便签按钮触摸监听器(实现特殊触摸事件分发) + private class NewNoteOnTouchListener implements OnTouchListener { + + public boolean onTouch(View v, MotionEvent event) { + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: { // 按下事件 + Display display = getWindowManager().getDefaultDisplay(); + int screenHeight = display.getHeight(); // 屏幕高度 + int newNoteViewHeight = mAddNewNote.getHeight(); // 按钮高度 + int start = screenHeight - newNoteViewHeight; // 按钮起始Y坐标 + int eventY = start + (int) event.getY(); // 事件绝对Y坐标 + + // 减去标题栏高度(子文件夹状态) + if (mState == ListEditState.SUB_FOLDER) { + eventY -= mTitleBar.getHeight(); + start -= mTitleBar.getHeight(); + } + + /** + * 特殊处理:点击按钮透明区域时将事件分发给底层列表视图 + * 透明区域由公式 y=-0.12x+94 定义(单位:像素) + * 这是一个UI设计的特殊需求 + */ + if (event.getY() < (event.getX() * (-0.12) + 94)) { + // 获取列表最后一个子视图 + View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 + - mNotesListView.getFooterViewsCount()); + if (view != null && view.getBottom() > start + && (view.getTop() < (start + 94))) { + mOriginY = (int) event.getY(); // 保存原始Y坐标 + mDispatchY = eventY; // 设置分发Y坐标 + event.setLocation(event.getX(), mDispatchY); // 修改事件位置 + mDispatch = true; // 标记为分发状态 + return mNotesListView.dispatchTouchEvent(event); // 分发给列表视图 + } + } + break; + } + case MotionEvent.ACTION_MOVE: { // 移动事件 + if (mDispatch) { + mDispatchY += (int) event.getY() - mOriginY; // 更新分发Y坐标 + event.setLocation(event.getX(), mDispatchY); // 修改事件位置 + return mNotesListView.dispatchTouchEvent(event); // 继续分发 + } + break; + } + default: { // 其他事件(抬起等) + if (mDispatch) { + event.setLocation(event.getX(), mDispatchY); // 修改事件位置 + mDispatch = false; // 清除分发标记 + return mNotesListView.dispatchTouchEvent(event); // 分发最终事件 + } + break; + } + } + return false; // 不处理事件 + } + }; + + // 开始异步查询便签列表 + private void startAsyncNotesListQuery() { + String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION + : NORMAL_SELECTION; // 根据文件夹ID选择查询条件 + mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, + Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { + String.valueOf(mCurrentFolderId) // 参数:文件夹ID + }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); // 排序:文件夹在前,按修改时间降序 + } + + // 后台查询处理器(异步查询数据库) + private final class BackgroundQueryHandler extends AsyncQueryHandler { + public BackgroundQueryHandler(ContentResolver contentResolver) { + super(contentResolver); + } + + @Override + protected void onQueryComplete(int token, Object cookie, Cursor cursor) { + switch (token) { + case FOLDER_NOTE_LIST_QUERY_TOKEN: // 便签列表查询完成 + mNotesListAdapter.changeCursor(cursor); // 更新适配器游标 + break; + case FOLDER_LIST_QUERY_TOKEN: // 文件夹列表查询完成 + if (cursor != null && cursor.getCount() > 0) { + showFolderListMenu(cursor); // 显示文件夹选择菜单 + } else { + Log.e(TAG, "Query folder failed"); + } + break; + default: + return; + } + } + } + + // 显示文件夹选择菜单(用于移动操作) + private void showFolderListMenu(Cursor cursor) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(R.string.menu_title_select_folder); // 设置标题 + final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); // 创建文件夹适配器 + builder.setAdapter(adapter, new DialogInterface.OnClickListener() { + // 文件夹选择回调 + public void onClick(DialogInterface dialog, int which) { + // 批量移动到选中的文件夹 + DataUtils.batchMoveToFolder(mContentResolver, + mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); + Toast.makeText( + NotesListActivity.this, + getString(R.string.format_move_notes_to_folder, + mNotesListAdapter.getSelectedCount(), + adapter.getFolderName(NotesListActivity.this, which)), // 显示移动结果 + Toast.LENGTH_SHORT).show(); + mModeCallBack.finishActionMode(); // 结束多选模式 + } + }); + builder.show(); // 显示对话框 + } + + // 创建新便签 + private void createNewNote() { + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 插入或编辑操作 + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); // 传递当前文件夹ID + this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); // 启动便签编辑活动 + } + + // 批量删除选中的便签 + private void batchDelete() { + new AsyncTask>() { + protected HashSet doInBackground(Void... unused) { + HashSet widgets = mNotesListAdapter.getSelectedWidget(); // 获取关联的小部件 + if (!isSyncMode()) { // 非同步模式:直接删除 + if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter + .getSelectedItemIds())) { + } else { + Log.e(TAG, "Delete notes error, should not happens"); + } + } else { // 同步模式:移动到回收站 + if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter + .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) { + Log.e(TAG, "Move notes to trash folder error, should not happens"); + } + } + return widgets; // 返回小部件集合 + } + + @Override + protected void onPostExecute(HashSet widgets) { + if (widgets != null) { + for (AppWidgetAttribute widget : widgets) { + // 更新关联的小部件 + if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { + updateWidget(widget.widgetId, widget.widgetType); + } + } + } + mModeCallBack.finishActionMode(); // 结束多选模式 + } + }.execute(); // 执行异步任务 + } + + // 删除文件夹 + private void deleteFolder(long folderId) { + if (folderId == Notes.ID_ROOT_FOLDER) { + Log.e(TAG, "Wrong folder id, should not happen " + folderId); + return; + } + + HashSet ids = new HashSet(); + ids.add(folderId); // 添加文件夹ID + HashSet widgets = DataUtils.getFolderNoteWidget(mContentResolver, + folderId); // 获取文件夹下便签的小部件 + if (!isSyncMode()) { // 非同步模式:直接删除 + DataUtils.batchDeleteNotes(mContentResolver, ids); + } else { // 同步模式:移动到回收站 + DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER); + } + // 更新关联的小部件 + if (widgets != null) { + for (AppWidgetAttribute widget : widgets) { + if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { + updateWidget(widget.widgetId, widget.widgetType); + } + } + } + } + + // 打开便签(编辑) + private void openNode(NoteItemData data) { + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_VIEW); // 查看操作 + intent.putExtra(Intent.EXTRA_UID, data.getId()); // 传递便签ID + this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); // 启动便签编辑活动 + } + + // 打开文件夹(进入子文件夹) + private void openFolder(NoteItemData data) { + mCurrentFolderId = data.getId(); // 更新当前文件夹ID + startAsyncNotesListQuery(); // 查询子文件夹内容 + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { + mState = ListEditState.CALL_RECORD_FOLDER; // 设置状态为通话记录文件夹 + mAddNewNote.setVisibility(View.GONE); // 隐藏添加按钮(通话记录不能新建) + } else { + mState = ListEditState.SUB_FOLDER; // 设置状态为子文件夹 + } + // 更新标题栏 + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { + mTitleBar.setText(R.string.call_record_folder_name); // 显示通话记录文件夹名称 + } else { + mTitleBar.setText(data.getSnippet()); // 显示文件夹名称 + } + mTitleBar.setVisibility(View.VISIBLE); // 显示标题栏 + } + + // 按钮点击事件 + public void onClick(View v) { + switch (v.getId()) { + case R.id.btn_new_note: // 新建便签按钮 + createNewNote(); + break; + default: + break; + } + } + + // 显示软键盘 + private void showSoftInput() { + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + if (inputMethodManager != null) { + inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); // 强制显示 + } + } + + // 隐藏软键盘 + private void hideSoftInput(View view) { + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); // 隐藏键盘 + } + + // 显示创建/修改文件夹对话框 + private void showCreateOrModifyFolderDialog(final boolean create) { + final AlertDialog.Builder builder = new AlertDialog.Builder(this); + View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); // 加载对话框布局 + final EditText etName = (EditText) view.findViewById(R.id.et_foler_name); // 文件夹名称输入框 + showSoftInput(); // 显示软键盘 + if (!create) { // 修改文件夹名称 + if (mFocusNoteDataItem != null) { + etName.setText(mFocusNoteDataItem.getSnippet()); // 设置当前文件夹名称 + builder.setTitle(getString(R.string.menu_folder_change_name)); // 设置标题 + } else { + Log.e(TAG, "The long click data item is null"); + return; + } + } else { // 创建新文件夹 + etName.setText(""); // 清空输入框 + builder.setTitle(this.getString(R.string.menu_create_folder)); // 设置标题 + } + + builder.setPositiveButton(android.R.string.ok, null); // 确定按钮(后续自定义) + builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + hideSoftInput(etName); // 隐藏软键盘 + } + }); + + final Dialog dialog = builder.setView(view).show(); // 显示对话框 + final Button positive = (Button)dialog.findViewById(android.R.id.button1); // 获取确定按钮 + positive.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + hideSoftInput(etName); // 隐藏软键盘 + String name = etName.getText().toString(); // 获取输入的名称 + // 检查文件夹名称是否已存在 + if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { + Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), + Toast.LENGTH_LONG).show(); // 显示错误提示 + etName.setSelection(0, etName.length()); // 全选文本 + return; + } + if (!create) { // 修改文件夹名称 + if (!TextUtils.isEmpty(name)) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.SNIPPET, name); // 设置新名称 + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); // 设置类型 + values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地修改 + // 更新数据库 + mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + + "=?", new String[] { + String.valueOf(mFocusNoteDataItem.getId()) // 指定要更新的文件夹 + }); + } + } else if (!TextUtils.isEmpty(name)) { // 创建新文件夹 + ContentValues values = new ContentValues(); + values.put(NoteColumns.SNIPPET, name); // 设置名称 + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); // 设置类型 + mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); // 插入数据库 + } + dialog.dismiss(); // 关闭对话框 + } + }); + + // 初始状态:如果输入框为空,禁用确定按钮 + if (TextUtils.isEmpty(etName.getText())) { + positive.setEnabled(false); + } + // 添加文本变化监听,动态启用/禁用确定按钮 + etName.addTextChangedListener(new TextWatcher() { + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + public void onTextChanged(CharSequence s, int start, int before, int count) { + if (TextUtils.isEmpty(etName.getText())) { + positive.setEnabled(false); // 空文本时禁用 + } else { + positive.setEnabled(true); // 有文本时启用 + } + } + + public void afterTextChanged(Editable s) { + } + }); + } + + // 返回键处理 + @Override + public void onBackPressed() { + switch (mState) { + case SUB_FOLDER: // 子文件夹状态:返回到根目录 + mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mState = ListEditState.NOTE_LIST; + startAsyncNotesListQuery(); // 重新查询根目录 + mTitleBar.setVisibility(View.GONE); // 隐藏标题栏 + break; + case CALL_RECORD_FOLDER: // 通话记录文件夹:返回到根目录 + mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mState = ListEditState.NOTE_LIST; + mAddNewNote.setVisibility(View.VISIBLE); // 显示添加按钮 + mTitleBar.setVisibility(View.GONE); // 隐藏标题栏 + startAsyncNotesListQuery(); // 重新查询根目录 + break; + case NOTE_LIST: // 根目录状态:退出应用 + super.onBackPressed(); + break; + default: + break; + } + } + + // 更新桌面小部件 + private void updateWidget(int appWidgetId, int appWidgetType) { + Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + // 根据小部件类型设置对应的接收器 + if (appWidgetType == Notes.TYPE_WIDGET_2X) { + intent.setClass(this, NoteWidgetProvider_2x.class); + } else if (appWidgetType == Notes.TYPE_WIDGET_4X) { + intent.setClass(this, NoteWidgetProvider_4x.class); + } else { + Log.e(TAG, "Unspported widget type"); + return; + } + + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { + appWidgetId // 小部件ID + }); + + sendBroadcast(intent); // 发送广播更新小部件 + setResult(RESULT_OK, intent); // 设置结果 + } + + // 文件夹上下文菜单创建监听器 + private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { + if (mFocusNoteDataItem != null) { + menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); // 设置菜单标题为文件夹名 + menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); // 查看文件夹 + menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); // 删除文件夹 + menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name); // 重命名文件夹 + } + } + }; + + // 上下文菜单关闭 + @Override + public void onContextMenuClosed(Menu menu) { + if (mNotesListView != null) { + mNotesListView.setOnCreateContextMenuListener(null); // 清除菜单监听器 + } + super.onContextMenuClosed(menu); + } + + // 上下文菜单项选择处理 + @Override + public boolean onContextItemSelected(MenuItem item) { + if (mFocusNoteDataItem == null) { + Log.e(TAG, "The long click data item is null"); + return false; + } + switch (item.getItemId()) { + case MENU_FOLDER_VIEW: // 查看文件夹 + openFolder(mFocusNoteDataItem); + break; + case MENU_FOLDER_DELETE: // 删除文件夹 + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(getString(R.string.alert_title_delete)); + builder.setIcon(android.R.drawable.ic_dialog_alert); + builder.setMessage(getString(R.string.alert_message_delete_folder)); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteFolder(mFocusNoteDataItem.getId()); // 执行删除 + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); // 显示确认对话框 + break; + case MENU_FOLDER_CHANGE_NAME: // 重命名文件夹 + showCreateOrModifyFolderDialog(false); // 显示修改对话框 + break; + default: + break; + } + + return true; + } + + // 准备选项菜单(根据状态加载不同的菜单) + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + menu.clear(); // 清除旧菜单 + if (mState == ListEditState.NOTE_LIST) { // 根目录状态 + getMenuInflater().inflate(R.menu.note_list, menu); + // 根据同步状态设置同步菜单项标题 + menu.findItem(R.id.menu_sync).setTitle( + GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); + } else if (mState == ListEditState.SUB_FOLDER) { // 子文件夹状态 + getMenuInflater().inflate(R.menu.sub_folder, menu); + } else if (mState == ListEditState.CALL_RECORD_FOLDER) { // 通话记录文件夹状态 + getMenuInflater().inflate(R.menu.call_record_folder, menu); + } else { + Log.e(TAG, "Wrong state:" + mState); + } + return true; + } + + // 选项菜单项选择处理 + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_new_folder: { // 新建文件夹 + showCreateOrModifyFolderDialog(true); + break; + } + case R.id.menu_export_text: { // 导出到文本 + exportNoteToText(); + break; + } + case R.id.menu_sync: { // 同步 + if (isSyncMode()) { + if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { + GTaskSyncService.startSync(this); // 开始同步 + } else { + GTaskSyncService.cancelSync(this); // 取消同步 + } + } else { + startPreferenceActivity(); // 未设置同步账户,跳转到设置 + } + break; + } + case R.id.menu_setting: { // 设置 + startPreferenceActivity(); + break; + } + case R.id.menu_new_note: { // 新建便签(子文件夹菜单中的) + createNewNote(); + break; + } + case R.id.menu_search: // 搜索 + onSearchRequested(); + break; + default: + break; + } + return true; + } + + // 搜索请求 + @Override + public boolean onSearchRequested() { + startSearch(null, false, null /* appData */, false); // 启动搜索 + return true; + } + + // 导出便签到文本文件 + private void exportNoteToText() { + final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); // 获取备份工具 + new AsyncTask() { + @Override + protected Integer doInBackground(Void... unused) { + return backup.exportToText(); // 执行导出 + } + + @Override + protected void onPostExecute(Integer result) { + // 根据导出结果显示不同提示 + if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { // SD卡未挂载 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_unmounted)); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SUCCESS) { // 导出成功 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.success_sdcard_export)); + builder.setMessage(NotesListActivity.this.getString( + R.string.format_exported_file_location, backup + .getExportedTextFileName(), backup.getExportedTextFileDir())); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SYSTEM_ERROR) { // 系统错误 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_export)); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } + } + }.execute(); // 执行异步任务 + } + + // 检查是否处于同步模式(已设置同步账户) + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + // 启动偏好设置活动 + private void startPreferenceActivity() { + Activity from = getParent() != null ? getParent() : this; + Intent intent = new Intent(from, NotesPreferenceActivity.class); + from.startActivityIfNeeded(intent, -1); + } + + // 列表项点击监听器 + private class OnListItemClickListener implements OnItemClickListener { + public void onItemClick(AdapterView parent, View view, int position, long id) { + if (view instanceof NotesListItem) { + NoteItemData item = ((NotesListItem) view).getItemData(); // 获取数据项 + // 多选模式下点击便签:切换选中状态 + if (mNotesListAdapter.isInChoiceMode()) { + if (item.getType() == Notes.TYPE_NOTE) { + position = position - mNotesListView.getHeaderViewsCount(); // 计算实际位置 + mModeCallBack.onItemCheckedStateChanged(null, position, id, + !mNotesListAdapter.isSelectedItem(position)); // 切换选中状态 + } + return; + } + + // 根据状态处理不同类型的点击 + switch (mState) { + case NOTE_LIST: // 根目录:点击文件夹进入,点击便签编辑 + if (item.getType() == Notes.TYPE_FOLDER + || item.getType() == Notes.TYPE_SYSTEM) { + openFolder(item); // 打开文件夹 + } else if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); // 打开便签 + } else { + Log.e(TAG, "Wrong note type in NOTE_LIST"); + } + break; + case SUB_FOLDER: // 子文件夹:只能点击便签 + case CALL_RECORD_FOLDER: // 通话记录文件夹:只能点击便签 + if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); // 打开便签 + } else { + Log.e(TAG, "Wrong note type in SUB_FOLDER"); + } + break; + default: + break; + } + } + } + } + + // 查询目标文件夹列表(用于移动操作) + private void startQueryDestinationFolders() { + String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; + // 根目录状态下添加根文件夹选项 + selection = (mState == ListEditState.NOTE_LIST) ? selection: + "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; + + mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, + null, + Notes.CONTENT_NOTE_URI, + FoldersListAdapter.PROJECTION, + selection, + new String[] { + String.valueOf(Notes.TYPE_FOLDER), // 类型:文件夹 + String.valueOf(Notes.ID_TRASH_FOLER), // 排除回收站 + String.valueOf(mCurrentFolderId) // 排除当前文件夹 + }, + NoteColumns.MODIFIED_DATE + " DESC"); // 按修改时间降序 + } + + // 列表项长按事件 + public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { + if (view instanceof NotesListItem) { + mFocusNoteDataItem = ((NotesListItem) view).getItemData(); // 保存焦点数据项 + // 长按便签:进入多选模式 + if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) { + if (mNotesListView.startActionMode(mModeCallBack) != null) { + mModeCallBack.onItemCheckedStateChanged(null, position, id, true); // 选中当前项 + mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); // 触觉反馈 + } else { + Log.e(TAG, "startActionMode fails"); + } + } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { + // 长按文件夹:添加上下文菜单 + mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); + } + } + return false; + } +} \ No newline at end of file diff --git a/src/ui/NotesListAdapter.java b/src/ui/NotesListAdapter.java new file mode 100644 index 0000000..10776f0 --- /dev/null +++ b/src/ui/NotesListAdapter.java @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.util.Log; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; + +import net.micode.notes.data.Notes; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; + + +// 便签列表适配器,继承CursorAdapter用于显示数据库中的便签和文件夹列表 +public class NotesListAdapter extends CursorAdapter { + private static final String TAG = "NotesListAdapter"; // 日志标签 + private Context mContext; // 上下文 + private HashMap mSelectedIndex; // 选中项索引映射(位置 -> 是否选中) + private int mNotesCount; // 便签(非文件夹)总数 + private boolean mChoiceMode; // 是否处于多选模式 + + // 小部件属性类(用于批量操作时获取关联的小部件信息) + public static class AppWidgetAttribute { + public int widgetId; // 小部件ID + public int widgetType; // 小部件类型 + }; + + // 构造方法 + public NotesListAdapter(Context context) { + super(context, null); // 初始游标为null + mSelectedIndex = new HashMap(); // 初始化选中项映射 + mContext = context; // 保存上下文引用 + mNotesCount = 0; // 初始便签数为0 + } + + // 创建新列表项视图 + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new NotesListItem(context); // 创建自定义列表项视图 + } + + // 绑定数据到列表项视图 + @Override + public void bindView(View view, Context context, Cursor cursor) { + if (view instanceof NotesListItem) { + NoteItemData itemData = new NoteItemData(context, cursor); // 从游标创建数据对象 + // 绑定数据到列表项,传递选择模式和选中状态 + ((NotesListItem) view).bind(context, itemData, mChoiceMode, + isSelectedItem(cursor.getPosition())); + } + } + + // 设置列表项选中状态 + public void setCheckedItem(final int position, final boolean checked) { + mSelectedIndex.put(position, checked); // 更新选中状态映射 + notifyDataSetChanged(); // 通知数据变化,刷新界面 + } + + // 检查是否处于多选模式 + public boolean isInChoiceMode() { + return mChoiceMode; + } + + // 设置选择模式 + public void setChoiceMode(boolean mode) { + mSelectedIndex.clear(); // 清空选中状态 + mChoiceMode = mode; // 更新模式标志 + } + + // 全选/取消全选所有便签项 + public void selectAll(boolean checked) { + Cursor cursor = getCursor(); + // 遍历所有项 + for (int i = 0; i < getCount(); i++) { + if (cursor.moveToPosition(i)) { + // 只对便签类型(非文件夹)进行操作 + if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { + setCheckedItem(i, checked); // 设置选中状态 + } + } + } + } + + // 获取选中项的ID集合 + public HashSet getSelectedItemIds() { + HashSet itemSet = new HashSet(); + // 遍历选中项映射 + for (Integer position : mSelectedIndex.keySet()) { + if (mSelectedIndex.get(position) == true) { + Long id = getItemId(position); // 获取该项的ID + if (id == Notes.ID_ROOT_FOLDER) { + Log.d(TAG, "Wrong item id, should not happen"); // 根文件夹不应被选中 + } else { + itemSet.add(id); // 添加到集合 + } + } + } + return itemSet; + } + + // 获取选中项关联的小部件属性集合 + public HashSet getSelectedWidget() { + HashSet itemSet = new HashSet(); + // 遍历选中项映射 + for (Integer position : mSelectedIndex.keySet()) { + if (mSelectedIndex.get(position) == true) { + Cursor c = (Cursor) getItem(position); // 获取对应位置的游标 + if (c != null) { + AppWidgetAttribute widget = new AppWidgetAttribute(); + NoteItemData item = new NoteItemData(mContext, c); // 创建数据对象 + widget.widgetId = item.getWidgetId(); // 获取小部件ID + widget.widgetType = item.getWidgetType(); // 获取小部件类型 + itemSet.add(widget); // 添加到集合 + // 注意:这里不关闭游标,只有适配器可以关闭游标 + } else { + Log.e(TAG, "Invalid cursor"); + return null; + } + } + } + return itemSet; + } + + // 获取选中项数量 + public int getSelectedCount() { + Collection values = mSelectedIndex.values(); + if (null == values) { + return 0; + } + Iterator iter = values.iterator(); + int count = 0; + // 统计值为true的项数 + while (iter.hasNext()) { + if (true == iter.next()) { + count++; + } + } + return count; + } + + // 检查是否全部便签项都被选中 + public boolean isAllSelected() { + int checkedCount = getSelectedCount(); // 选中数量 + return (checkedCount != 0 && checkedCount == mNotesCount); // 不为0且等于便签总数 + } + + // 检查指定位置项是否被选中 + public boolean isSelectedItem(final int position) { + if (null == mSelectedIndex.get(position)) { + return false; // 映射中不存在则返回false + } + return mSelectedIndex.get(position); // 返回选中状态 + } + + // 内容变化时回调 + @Override + protected void onContentChanged() { + super.onContentChanged(); + calcNotesCount(); // 重新计算便签数量 + } + + // 游标变化时回调 + @Override + public void changeCursor(Cursor cursor) { + super.changeCursor(cursor); // 调用父类方法 + calcNotesCount(); // 重新计算便签数量 + } + + // 计算便签(非文件夹)数量 + private void calcNotesCount() { + mNotesCount = 0; + // 遍历所有项 + for (int i = 0; i < getCount(); i++) { + Cursor c = (Cursor) getItem(i); + if (c != null) { + // 只统计便签类型(TYPE_NOTE) + if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { + mNotesCount++; // 便签计数加1 + } + } else { + Log.e(TAG, "Invalid cursor"); + return; + } + } + } +} \ No newline at end of file diff --git a/src/ui/NotesListItem.java b/src/ui/NotesListItem.java new file mode 100644 index 0000000..2a1434f --- /dev/null +++ b/src/ui/NotesListItem.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.text.format.DateUtils; +import android.view.View; +import android.widget.CheckBox; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser.NoteItemBgResources; + + +// 便签列表项自定义视图,继承LinearLayout,用于显示单个便签/文件夹项 +public class NotesListItem extends LinearLayout { + private ImageView mAlert; // 提醒图标(闹钟或通话记录图标) + private TextView mTitle; // 标题文本(便签内容或文件夹名) + private TextView mTime; // 时间文本(修改时间) + private TextView mCallName; // 联系人姓名(通话记录用) + private NoteItemData mItemData; // 绑定的数据项 + private CheckBox mCheckBox; // 复选框(多选模式用) + + // 构造方法 + public NotesListItem(Context context) { + super(context); + inflate(context, R.layout.note_item, this); // 加载布局文件 + // 初始化视图组件 + mAlert = (ImageView) findViewById(R.id.iv_alert_icon); + mTitle = (TextView) findViewById(R.id.tv_title); + mTime = (TextView) findViewById(R.id.tv_time); + mCallName = (TextView) findViewById(R.id.tv_name); + mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); // 使用Android标准ID + } + + // 绑定数据到视图 + public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { + // 多选模式处理:显示/隐藏复选框 + if (choiceMode && data.getType() == Notes.TYPE_NOTE) { + mCheckBox.setVisibility(View.VISIBLE); // 显示复选框(仅对便签类型) + mCheckBox.setChecked(checked); // 设置选中状态 + } else { + mCheckBox.setVisibility(View.GONE); // 隐藏复选框 + } + + mItemData = data; // 保存数据引用 + + // 通话记录文件夹的特殊处理 + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { + mCallName.setVisibility(View.GONE); // 隐藏联系人姓名 + mAlert.setVisibility(View.VISIBLE); // 显示图标 + mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 设置主标题样式 + // 显示文件夹名称和文件数量 + mTitle.setText(context.getString(R.string.call_record_folder_name) + + context.getString(R.string.format_folder_files_count, data.getNotesCount())); + mAlert.setImageResource(R.drawable.call_record); // 设置通话记录图标 + } + // 通话记录便签的特殊处理 + else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { + mCallName.setVisibility(View.VISIBLE); // 显示联系人姓名 + mCallName.setText(data.getCallName()); // 设置联系人姓名 + mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); // 设置副标题样式 + mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 设置格式化摘要 + // 根据是否有提醒设置图标 + if (data.hasAlert()) { + mAlert.setImageResource(R.drawable.clock); // 显示闹钟图标 + mAlert.setVisibility(View.VISIBLE); + } else { + mAlert.setVisibility(View.GONE); // 隐藏图标 + } + } + // 普通文件夹和便签处理 + else { + mCallName.setVisibility(View.GONE); // 隐藏联系人姓名 + mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 设置主标题样式 + + // 文件夹类型 + if (data.getType() == Notes.TYPE_FOLDER) { + // 显示文件夹名和包含的文件数 + mTitle.setText(data.getSnippet() + + context.getString(R.string.format_folder_files_count, + data.getNotesCount())); + mAlert.setVisibility(View.GONE); // 文件夹不显示提醒图标 + } + // 便签类型 + else { + mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 设置格式化摘要 + // 根据是否有提醒设置图标 + if (data.hasAlert()) { + mAlert.setImageResource(R.drawable.clock); // 显示闹钟图标 + mAlert.setVisibility(View.VISIBLE); + } else { + mAlert.setVisibility(View.GONE); // 隐藏图标 + } + } + } + // 设置相对时间(如"2分钟前") + mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); + + setBackground(data); // 设置背景(根据位置和类型) + } + + // 设置列表项背景(根据位置和类型) + private void setBackground(NoteItemData data) { + int id = data.getBgColorId(); // 获取背景颜色ID + if (data.getType() == Notes.TYPE_NOTE) { // 便签类型 + // 根据位置选择不同的背景资源 + if (data.isSingle() || data.isOneFollowingFolder()) { + // 单个或跟在文件夹后的第一个便签:圆角所有边 + setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); + } else if (data.isLast()) { + // 最后一项:底部圆角 + setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); + } else if (data.isFirst() || data.isMultiFollowingFolder()) { + // 第一项或跟在文件夹后的多个便签:顶部圆角 + setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); + } else { + // 中间项:直角 + setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); + } + } else { // 文件夹类型 + // 文件夹使用统一背景 + setBackgroundResource(NoteItemBgResources.getFolderBgRes()); + } + } + + // 获取绑定的数据项 + public NoteItemData getItemData() { + return mItemData; + } +} \ No newline at end of file diff --git a/src/ui/NotesPreferenceActivity.java b/src/ui/NotesPreferenceActivity.java new file mode 100644 index 0000000..00b8746 --- /dev/null +++ b/src/ui/NotesPreferenceActivity.java @@ -0,0 +1,413 @@ +/* + * 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; + + +```java +// 便签偏好设置活动,管理同步账户和应用程序设置 +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"; + // 同步账户分类键(UI中的分类) + 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; // 同步服务广播接收器 + private Account[] mOriAccounts; // 原始账户数组(用于检测新账户) + private boolean mHasAddedAccount; // 是否添加了新账户标志 + + // 创建活动 + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + // 启用ActionBar返回按钮 + getActionBar().setDisplayHomeAsUpEnabled(true); + + addPreferencesFromResource(R.xml.preferences); // 加载偏好设置XML + mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); // 获取账户分类 + mReceiver = new GTaskReceiver(); // 创建广播接收器 + IntentFilter filter = new IntentFilter(); + filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); // 过滤同步服务广播 + 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; + } + }); + + 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; // 标记当前账户 + } + 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" // 过滤Gmail账户 + }); + 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(); // 刷新界面 + } + // which == 2 取消,不做任何操作 + } + }); + dialogBuilder.show(); + } + + // 获取Google账户列表 + 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); + + // 在新线程中清空本地同步信息 + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); // 清空Google任务ID + values.put(NoteColumns.SYNC_ID, 0); // 重置同步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(); + + // 在新线程中清空本地同步信息 + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); // 清空Google任务ID + values.put(NoteColumns.SYNC_ID, 0); // 重置同步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); // 默认返回0 + } + + // 同步服务广播接收器(用于更新UI状态) + 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; + default: + return false; + } + } +} +``` \ No newline at end of file diff --git a/src/widget/NoteWidgetProvider.java b/src/widget/NoteWidgetProvider.java new file mode 100644 index 0000000..5884f64 --- /dev/null +++ b/src/widget/NoteWidgetProvider.java @@ -0,0 +1,156 @@ +/* + * 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; + +```java +// 便签桌面小部件提供器抽象类,继承AppWidgetProvider +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; // ID列索引 + public static final int COLUMN_BG_COLOR_ID = 1; // 背景颜色ID列索引 + public static final int COLUMN_SNIPPET = 2; // 摘要列索引 + + private static final String TAG = "NoteWidgetProvider"; // 日志标签 + + // 小部件被删除时的回调 + @Override + public void onDeleted(Context context, int[] appWidgetIds) { + ContentValues values = new ContentValues(); + // 将被删除的小部件ID设置为无效值 + values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + for (int i = 0; i < appWidgetIds.length; i++) { + // 更新数据库,清空关联便签的小部件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) { + return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, + PROJECTION, + // 查询条件:指定小部件ID且不在回收站中 + NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", + new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, + null); + } + + // 更新小部件(公开方法) + protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + update(context, appWidgetManager, appWidgetIds, false); // 默认非隐私模式 + } + + // 更新小部件(私有方法,支持隐私模式) + private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, + boolean privacyMode) { + for (int i = 0; i < appWidgetIds.length; i++) { + if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { + int bgId = ResourceParser.getDefaultBgId(context); // 默认背景ID + String snippet = ""; // 便签内容摘要 + + // 创建点击小部件后启动的Intent + Intent intent = new Intent(context, NoteEditActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // 单例模式 + intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); // 传递小部件ID + intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); // 传递小部件类型 + + // 查询关联的便签信息 + Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]); + if (c != null && c.moveToFirst()) { + if (c.getCount() > 1) { + // 错误情况:多个便签关联到同一个widget ID + 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); // 获取背景颜色ID + intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); // 传递便签ID + intent.setAction(Intent.ACTION_VIEW); // 查看现有便签 + } else { + // 无关联便签:显示默认文本 + snippet = context.getResources().getString(R.string.widget_havenot_content); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 创建新便签 + } + + if (c != null) { + c.close(); // 关闭游标 + } + + // 创建RemoteViews对象 + RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); + rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); // 设置背景图片 + intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); // 传递背景ID给编辑活动 + + /** + * 生成待定Intent(点击小部件后启动) + */ + 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(由子类实现) + protected abstract int getBgResourceId(int bgId); + + // 抽象方法:获取小部件布局ID(由子类实现) + protected abstract int getLayoutId(); + + // 抽象方法:获取小部件类型(由子类实现) + 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..adcb2f7 --- /dev/null +++ b/src/widget/NoteWidgetProvider_2x.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.ResourceParser; + + +public class NoteWidgetProvider_2x extends NoteWidgetProvider { + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + } + + @Override + protected int getLayoutId() { + return R.layout.widget_2x; + } + + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); + } + + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_2X; + } +} diff --git a/src/widget/NoteWidgetProvider_4x.java b/src/widget/NoteWidgetProvider_4x.java new file mode 100644 index 0000000..c12a02e --- /dev/null +++ b/src/widget/NoteWidgetProvider_4x.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_4x extends NoteWidgetProvider { + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + } + + protected int getLayoutId() { + return R.layout.widget_4x; + } + + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); + } + + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_4X; + } +}