diff --git a/src/androidTest/java/net/micode/notes/ExampleInstrumentedTest.java b/src/androidTest/java/net/micode/notes/ExampleInstrumentedTest.java
deleted file mode 100644
index a889a75..0000000
--- a/src/androidTest/java/net/micode/notes/ExampleInstrumentedTest.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package net.micode.notes;
-
-import android.content.Context;
-
-import androidx.test.platform.app.InstrumentationRegistry;
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.*;
-
-/**
- * Instrumented test, which will execute on an Android device.
- *
- * @see Testing documentation
- */
-@RunWith(AndroidJUnit4.class)
-public class ExampleInstrumentedTest {
- @Test
- public void useAppContext() {
- // Context of the app under test.
- Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
- assertEquals("net.micode.notes", appContext.getPackageName());
- }
-}
\ No newline at end of file
diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml
deleted file mode 100644
index cb43220..0000000
--- a/src/main/AndroidManifest.xml
+++ /dev/null
@@ -1,157 +0,0 @@
-
-
- * 该类提供了获取联系人信息的静态方法,并使用缓存机制提高查询效率 - *
- */ -public class Contact { - /** - * 联系人缓存,用于存储已查询过的电话号码和对应联系人姓名 - */ - private static HashMap- * 该方法会先检查缓存,如果缓存中存在则直接返回,否则查询联系人数据库 - *
- * @param context 上下文对象 - * @param phoneNumber 电话号码 - * @return 联系人姓名,若未找到则返回null - */ - public static String getContact(Context context, String phoneNumber) { - if(sContactCache == null) { - sContactCache = new HashMap- * 该类包含了便签应用的核心数据定义,包括便签类型、系统文件夹ID、意图额外参数、 - * 组件类型、以及各种URI定义。同时还定义了便签表和数据表的列名,以及文本便签和 - * 通话便签的具体数据结构。 - *
- */ -public class Notes { - /** - * 内容提供者的授权名称,用于构建内容URI - */ - 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; - - /** - * 以下是系统文件夹的标识符 - * {@link Notes#ID_ROOT_FOLDER } 是默认文件夹 - * {@link Notes#ID_TEMPARAY_FOLDER } 用于存放不属于任何文件夹的便签 - * {@link Notes#ID_CALL_RECORD_FOLDER} 用于存储通话记录便签 - */ - public static final int ID_ROOT_FOLDER = 0; - public static final int ID_TEMPARAY_FOLDER = -1; - public static final int ID_CALL_RECORD_FOLDER = -2; - /** - * 回收站文件夹ID,用于存储被删除的便签和文件夹 - */ - public static final int ID_TRASH_FOLER = -3; - - /** - * 意图额外参数:提醒日期 - */ - public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; - /** - * 意图额外参数:背景颜色ID - */ - 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"; - /** - * 意图额外参数:组件类型 - */ - public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; - /** - * 意图额外参数:文件夹ID - */ - public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; - /** - * 意图额外参数:通话日期 - */ - public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; - - /** - * 组件类型:无效组件 - */ - public static final int TYPE_WIDGET_INVALIDE = -1; - /** - * 组件类型:2x2大小的便签组件 - */ - public static final int TYPE_WIDGET_2X = 0; - /** - * 组件类型:4x4大小的便签组件 - */ - public static final int TYPE_WIDGET_4X = 1; - - /** - * 锁类型:便签锁 - */ - public static final int LOCK_TYPE_NOTE = 0; - - /** - * 锁类型:文件夹锁 - */ - public static final int LOCK_TYPE_FOLDER = 1; - - /** - * 数据类型常量类,定义了不同类型便签的数据项类型 - */ - public static class DataConstants { - /** - * 文本便签的数据项类型 - */ - public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; - /** - * 通话便签的数据项类型 - */ - public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; - } - - /** - * 用于查询所有便签和文件夹的Uri - */ - 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"); - - public interface NoteColumns { - /** - * 行的唯一ID - *类型: INTEGER (long)
- */ - public static final String ID = "_id"; - - /** - * 便签或文件夹的父ID - *类型: INTEGER (long)
- */ - public static final String PARENT_ID = "parent_id"; - - /** - * 便签或文件夹的创建日期 - *类型: INTEGER (long)
- */ - public static final String CREATED_DATE = "created_date"; - - /** - * 最近修改日期 - *类型: INTEGER (long)
- */ - public static final String MODIFIED_DATE = "modified_date"; - - - /** - * 提醒日期 - *类型: INTEGER (long)
- */ - public static final String ALERTED_DATE = "alert_date"; - - /** - * 文件夹名称或便签的文本内容 - *类型: TEXT
- */ - public static final String SNIPPET = "snippet"; - - /** - * 便签的组件ID - *类型: INTEGER (long)
- */ - public static final String WIDGET_ID = "widget_id"; - - /** - * 便签的组件类型 - *类型: INTEGER (long)
- */ - public static final String WIDGET_TYPE = "widget_type"; - - /** - * 便签的背景颜色ID - *类型: INTEGER (long)
- */ - public static final String BG_COLOR_ID = "bg_color_id"; - - /** - * 对于文本便签,没有附件;对于多媒体便签,至少有一个附件 - *类型: INTEGER
- */ - public static final String HAS_ATTACHMENT = "has_attachment"; - - /** - * 文件夹中的便签数量 - *类型: INTEGER (long)
- */ - public static final String NOTES_COUNT = "notes_count"; - - /** - * 文件类型:文件夹或便签 - *类型: INTEGER
- */ - public static final String TYPE = "type"; - - /** - * 最后同步ID - *类型: INTEGER (long)
- */ - public static final String SYNC_ID = "sync_id"; - - /** - * 表示本地是否修改的标志 - *类型: INTEGER
- */ - public static final String LOCAL_MODIFIED = "local_modified"; - - /** - * 原始父ID - *类型: INTEGER (long)
- */ - public static final String ORIGIN_PARENT_ID = "origin_parent_id"; - - /** - * GTASK ID - *类型: TEXT
- */ - public static final String GTASK_ID = "gtask_id"; - - /** - * 版本号 - *类型: INTEGER
- */ - public static final String VERSION = "version"; - - /** - * 置顶状态 - *类型: INTEGER
- *0表示未置顶,1表示置顶
- */ - public static final String PINNED = "pinned"; - - /** - * 是否上锁 - *类型: INTEGER
- *0表示未上锁,1表示上锁
- */ - public static final String IS_LOCKED = "is_locked"; - - /** - * 加密后的密码 - *类型: TEXT
- */ - public static final String LOCK_PASSWORD = "lock_password"; - - /** - * 锁类型 - *类型: INTEGER
- *0表示便签锁,1表示文件夹锁
- */ - public static final String LOCK_TYPE = "lock_type"; - } - - public interface DataColumns { - /** - * 行的唯一ID - *类型: INTEGER (long)
- */ - public static final String ID = "_id"; - - /** - * 该行表示的项目的MIME类型 - *类型: Text
- */ - public static final String MIME_TYPE = "mime_type"; - - /** - * 该数据所属便签的引用ID - *类型: INTEGER (long)
- */ - public static final String NOTE_ID = "note_id"; - - /** - * 便签或文件夹的创建日期 - *类型: INTEGER (long)
- */ - public static final String CREATED_DATE = "created_date"; - - /** - * 最近修改日期 - *类型: INTEGER (long)
- */ - public static final String MODIFIED_DATE = "modified_date"; - - /** - * 数据内容 - *类型: TEXT
- */ - public static final String CONTENT = "content"; - - - /** - * 通用数据列,含义由{@link # MIMETYPE}决定,用于整数数据类型 - *类型: INTEGER
- */ - public static final String DATA1 = "data1"; - - /** - * 通用数据列,含义由{@link # MIMETYPE}决定,用于整数数据类型 - *类型: INTEGER
- */ - public static final String DATA2 = "data2"; - - /** - * 通用数据列,含义由{@link # MIMETYPE}决定,用于文本数据类型 - *类型: TEXT
- */ - public static final String DATA3 = "data3"; - - /** - * 通用数据列,含义由{@link # MIMETYPE}决定,用于文本数据类型 - *类型: TEXT
- */ - public static final String DATA4 = "data4"; - - /** - * 通用数据列,含义由{@link # MIMETYPE}决定,用于文本数据类型 - *类型: TEXT
- */ - public static final String DATA5 = "data5"; - } - - public static final class TextNote implements DataColumns { - /** - * 指示文本是否处于清单模式 - *类型: Integer 1:清单模式 0:普通模式
- */ - public static final String MODE = DATA1; - - /** - * 清单模式 - */ - public static final int MODE_CHECK_LIST = 1; - - /** - * 文本便签的目录MIME类型 - */ - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; - - /** - * 文本便签的单项MIME类型 - */ - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; - - /** - * 文本便签的内容URI - */ - public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); - } - - public static final class CallNote implements DataColumns { - /** - * 此记录的通话日期 - *类型: INTEGER (long)
- */ - public static final String CALL_DATE = DATA1; - - /** - * 此记录的电话号码 - *类型: TEXT
- */ - public static final String PHONE_NUMBER = DATA3; - - /** - * 通话便签的目录MIME类型 - */ - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; - - /** - * 通话便签的单项MIME类型 - */ - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; - - /** - * 通话便签的内容URI - */ - public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); - } -} diff --git a/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java b/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java deleted file mode 100644 index ce29b9f..0000000 --- a/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java +++ /dev/null @@ -1,470 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.data; - -import android.content.ContentValues; -import android.content.Context; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; -import android.util.Log; - -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.DataConstants; -import net.micode.notes.data.Notes.NoteColumns; - - -/** - * 笔记数据库帮助类,负责数据库的创建、升级及触发器管理 - * 采用单例模式确保数据库连接的唯一性,封装了表结构定义、系统文件夹初始化等核心操作 - */ -public class NotesDatabaseHelper extends SQLiteOpenHelper { - // 数据库文件名 - private static final String DB_NAME = "note.db"; - // 数据库版本号,用于升级控制 - private static final int DB_VERSION = 6; - - /** - * 数据库表名常量定义 - */ - public interface TABLE { - // 笔记表,存储笔记和文件夹的元数据 - public static final String NOTE = "note"; - // 数据表,存储笔记的具体内容(如文本、通话记录等) - public static final String DATA = "data"; - } - - // 日志标签 - private static final String TAG = "NotesDatabaseHelper"; - // 单例实例 - private static NotesDatabaseHelper mInstance; - - /** - * 笔记表创建SQL语句 - * 包含笔记/文件夹的基本属性:ID、父文件夹ID、提醒时间、背景色、创建/修改时间等 - */ - private static final String CREATE_NOTE_TABLE_SQL = - "CREATE TABLE " + TABLE.NOTE + "(" + - NoteColumns.ID + " INTEGER PRIMARY KEY," + - NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + - NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + - NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + - NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.PINNED + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.IS_LOCKED + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.LOCK_PASSWORD + " TEXT NOT NULL DEFAULT ''," + - NoteColumns.LOCK_TYPE + " INTEGER NOT NULL DEFAULT 0" + - ")"; - - /** - * 数据表创建SQL语句 - * 存储笔记的具体内容,支持多种类型(文本、通话记录等),通过MIME_TYPE区分 - */ - private static final String CREATE_DATA_TABLE_SQL = - "CREATE TABLE " + TABLE.DATA + "(" + - DataColumns.ID + " INTEGER PRIMARY KEY," + - DataColumns.MIME_TYPE + " TEXT NOT NULL," + - DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + - DataColumns.DATA1 + " INTEGER," + - DataColumns.DATA2 + " INTEGER," + - DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + - DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + - DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + - ")"; - - /** - * 为数据表的NOTE_ID字段创建索引 - * 优化根据笔记ID查询数据的性能 - */ - private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = - "CREATE INDEX IF NOT EXISTS note_id_index ON " + - TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; - - /** - * 触发器:更新笔记父文件夹时,增加新父文件夹的笔记计数 - */ - private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = - "CREATE TRIGGER increase_folder_count_on_update "+ - " 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"; - - /** - * 私有构造方法,防止外部实例化 - * @param context 上下文对象 - */ - public NotesDatabaseHelper(Context context) { - super(context, DB_NAME, null, DB_VERSION); - } - - /** - * 创建笔记表并初始化相关触发器和系统文件夹 - * @param db 数据库实例 - */ - public void createNoteTable(SQLiteDatabase db) { - db.execSQL(CREATE_NOTE_TABLE_SQL); - reCreateNoteTableTriggers(db); - createSystemFolder(db); - Log.d(TAG, "note table has been created"); - } - - /** - * 重新创建笔记表的所有触发器(先删除旧触发器再创建新的) - * @param db 数据库实例 - */ - 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); - } - - /** - * 初始化系统文件夹(通话记录文件夹、根目录、临时文件夹、回收站) - * @param db 数据库实例 - */ - 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); - } - - /** - * 创建数据表并初始化相关触发器和索引 - * @param db 数据库实例 - */ - public void createDataTable(SQLiteDatabase db) { - db.execSQL(CREATE_DATA_TABLE_SQL); - reCreateDataTableTriggers(db); - db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); - Log.d(TAG, "data table has been created"); - } - - /** - * 重新创建数据表的所有触发器(先删除旧触发器再创建新的) - * @param db 数据库实例 - */ - private void reCreateDataTableTriggers(SQLiteDatabase db) { - db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); - db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); - db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); - - db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); - db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); - db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); - } - - /** - * 获取单例实例 - * @param context 上下文对象 - * @return 数据库帮助类实例 - */ - static synchronized NotesDatabaseHelper getInstance(Context context) { - if (mInstance == null) { - mInstance = new NotesDatabaseHelper(context); - } - return mInstance; - } - - /** - * 数据库首次创建时调用,初始化表结构 - * @param db 数据库实例 - */ - @Override - public void onCreate(SQLiteDatabase db) { - createNoteTable(db); - createDataTable(db); - } - - /** - * 数据库版本升级时调用 - * @param db 数据库实例 - * @param oldVersion 旧版本号 - * @param newVersion 新版本号 - */ - @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - boolean reCreateTriggers = false; - boolean skipV2 = false; - - // 版本1升级到版本2 - if (oldVersion == 1) { - upgradeToV2(db); - skipV2 = true; // 此升级包含了从v2到v3的升级 - oldVersion++; - } - - // 版本2升级到版本3(跳过已包含在v1->v2中的情况) - if (oldVersion == 2 && !skipV2) { - upgradeToV3(db); - reCreateTriggers = true; - oldVersion++; - } - - // 版本3升级到版本4 - if (oldVersion == 3) { - upgradeToV4(db); - oldVersion++; - } - - // 版本4升级到版本5 - if (oldVersion == 4) { - upgradeToV5(db); - oldVersion++; - } - - // 版本5升级到版本6:添加锁相关字段 - if (oldVersion == 5) { - upgradeToV6(db); - oldVersion++; - } - - // 如果需要,重新创建触发器 - if (reCreateTriggers) { - reCreateNoteTableTriggers(db); - reCreateDataTableTriggers(db); - } - - // 验证升级是否完成 - if (oldVersion != newVersion) { - throw new IllegalStateException("Upgrade notes database to version " + newVersion - + "fails"); - } - } - - /** - * 升级到版本2:删除旧表并重新创建(结构调整) - * @param db 数据库实例 - */ - private void upgradeToV2(SQLiteDatabase db) { - db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); - db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); - createNoteTable(db); - createDataTable(db); - } - - /** - * 升级到版本3:添加GTask ID字段和回收站文件夹 - * @param db 数据库实例 - */ - private void upgradeToV3(SQLiteDatabase db) { - // 删除未使用的触发器 - db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); - db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); - db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); - // 添加GTask ID字段,用于同步 - db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID - + " TEXT NOT NULL DEFAULT ''"); - // 添加回收站系统文件夹 - ContentValues values = new ContentValues(); - values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); - values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); - db.insert(TABLE.NOTE, null, values); - } - - /** - * 升级到版本4:添加版本号字段,用于数据同步控制 - * @param db 数据库实例 - */ - private void upgradeToV4(SQLiteDatabase db) { - db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION - + " INTEGER NOT NULL DEFAULT 0"); - } - - /** - * 升级到版本5:添加置顶字段,用于便签置顶功能 - * @param db 数据库实例 - */ - private void upgradeToV5(SQLiteDatabase db) { - db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.PINNED - + " INTEGER NOT NULL DEFAULT 0"); - } - - /** - * 升级到版本6:添加锁相关字段,用于便签和文件夹上锁功能 - * @param db 数据库实例 - */ - private void upgradeToV6(SQLiteDatabase db) { - db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.IS_LOCKED - + " INTEGER NOT NULL DEFAULT 0"); - db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.LOCK_PASSWORD - + " TEXT NOT NULL DEFAULT ''"); - db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.LOCK_TYPE - + " INTEGER NOT NULL DEFAULT 0"); - } -} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/data/NotesProvider.java b/src/main/java/net/micode/notes/data/NotesProvider.java deleted file mode 100644 index 678534f..0000000 --- a/src/main/java/net/micode/notes/data/NotesProvider.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.data; - -import android.app.SearchManager; -import android.content.ContentProvider; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Intent; -import android.content.UriMatcher; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.net.Uri; -import android.text.TextUtils; -import android.util.Log; - -import net.micode.notes.R; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.data.NotesDatabaseHelper.TABLE; - -/** - * 便签应用的内容提供者(ContentProvider) - * 负责管理便签数据的CRUD操作,包括搜索功能 - */ -public class NotesProvider extends ContentProvider { - /** - * URI匹配器,用于匹配不同的URI请求,根据URI类型执行相应的操作 - */ - private static final UriMatcher mMatcher; - - /** - * 数据库帮助类实例,用于获取数据库连接 - */ - private NotesDatabaseHelper mHelper; - - /** - * 日志标签,用于日志输出 - */ - private static final String TAG = "NotesProvider"; - - /** - * URI匹配类型常量定义,用于区分不同的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; // 搜索建议操作 - - /** - * 静态初始化块,配置URI匹配规则 - * 为不同类型的URI请求配置对应的匹配类型 - */ - static { - mMatcher = new UriMatcher(UriMatcher.NO_MATCH); - // 匹配便签表的URI - mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); - mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); - // 匹配数据表的URI - mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); - mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); - // 匹配搜索相关的URI - mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); - mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); - mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); - } - - /** - * 搜索查询的投影(列)定义 - * x'0A' 在SQLite中代表 '\n' 字符 - * 对于搜索结果中的标题和内容,我们将修剪 '\n' 和空白字符以显示更多信息 - */ - private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," - + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," - + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," - + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," - + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," - + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," - + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; - - /** - * 便签片段搜索查询的SQL语句 - * 搜索条件:便签片段包含关键词,且不在回收站中,类型为普通便签 - */ - 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; - - /** - * 初始化内容提供者 - * @return 如果初始化成功返回true,否则返回false - */ - @Override - public boolean onCreate() { - mHelper = NotesDatabaseHelper.getInstance(getContext()); - return true; - } - - /** - * 查询数据 - * @param uri 要查询的URI - * @param projection 要返回的列,null表示所有列 - * @param selection 查询条件,null表示无条件 - * @param selectionArgs 查询条件参数 - * @param sortOrder 排序方式,null表示默认排序 - * @return 包含查询结果的Cursor对象 - */ - @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, - String sortOrder) { - Cursor c = null; - SQLiteDatabase db = mHelper.getReadableDatabase(); - String id = null; - - // 根据URI类型执行不同的查询操作 - switch (mMatcher.match(uri)) { - case URI_NOTE: - // 查询所有便签 - c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, - sortOrder); - break; - case URI_NOTE_ITEM: - // 查询单条便签记录 - id = uri.getPathSegments().get(1); - c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id - + parseSelection(selection), selectionArgs, null, null, sortOrder); - break; - case URI_DATA: - // 查询所有数据记录 - c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, - sortOrder); - break; - case URI_DATA_ITEM: - // 查询单条数据记录 - id = uri.getPathSegments().get(1); - c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id - + parseSelection(selection), selectionArgs, null, null, sortOrder); - break; - case URI_SEARCH: - case URI_SEARCH_SUGGEST: - // 处理搜索和搜索建议请求 - if (sortOrder != null || projection != null) { - throw new IllegalArgumentException( - "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); - } - - String searchString = null; - // 根据URI类型获取搜索关键词 - if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { - if (uri.getPathSegments().size() > 1) { - searchString = uri.getPathSegments().get(1); - } - } else { - searchString = uri.getQueryParameter("pattern"); - } - - // 如果搜索关键词为空,返回null - if (TextUtils.isEmpty(searchString)) { - return null; - } - - try { - // 构造模糊查询字符串 - searchString = String.format("%%%s%%", searchString); - c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, - new String[] { searchString }); - } catch (IllegalStateException ex) { - Log.e(TAG, "got exception: " + ex.toString()); - } - break; - default: - throw new IllegalArgumentException("Unknown URI " + uri); - } - - // 设置内容观察者,以便在数据变化时通知相关组件 - if (c != null) { - c.setNotificationUri(getContext().getContentResolver(), uri); - } - return c; - } - - /** - * 插入数据 - * @param uri 要插入数据的URI - * @param values 要插入的数据值 - * @return 新插入数据的URI - */ - @Override - public Uri insert(Uri uri, ContentValues values) { - SQLiteDatabase db = mHelper.getWritableDatabase(); - long dataId = 0, noteId = 0, insertedId = 0; - - // 根据URI类型执行不同的插入操作 - switch (mMatcher.match(uri)) { - case URI_NOTE: - // 插入便签数据 - insertedId = noteId = db.insert(TABLE.NOTE, null, values); - break; - case URI_DATA: - // 插入数据表记录 - if (values.containsKey(DataColumns.NOTE_ID)) { - noteId = values.getAsLong(DataColumns.NOTE_ID); - } else { - Log.d(TAG, "Wrong data format without note id:" + values.toString()); - } - insertedId = dataId = db.insert(TABLE.DATA, null, values); - break; - default: - throw new IllegalArgumentException("Unknown URI " + uri); - } - - // 通知便签URI的数据变化 - if (noteId > 0) { - getContext().getContentResolver().notifyChange( - ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); - } - - // 通知数据URI的数据变化 - if (dataId > 0) { - getContext().getContentResolver().notifyChange( - ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); - } - - // 返回新插入数据的URI - return ContentUris.withAppendedId(uri, insertedId); - } - - /** - * 删除数据 - * @param uri 要删除数据的URI - * @param selection 删除条件,null表示无条件 - * @param selectionArgs 删除条件参数 - * @return 被删除的行数 - */ - @Override - public int delete(Uri uri, String selection, String[] selectionArgs) { - int count = 0; - String id = null; - SQLiteDatabase db = mHelper.getWritableDatabase(); - boolean deleteData = false; - - // 根据URI类型执行不同的删除操作 - switch (mMatcher.match(uri)) { - case URI_NOTE: - // 删除便签记录(不删除ID小于0的系统文件夹) - selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; - count = db.delete(TABLE.NOTE, selection, selectionArgs); - break; - case URI_NOTE_ITEM: - // 删除单条便签记录 - id = uri.getPathSegments().get(1); - /** - * ID小于0的是系统文件夹,不允许删除(移动到回收站) - */ - long noteId = Long.valueOf(id); - if (noteId <= 0) { - break; - } - count = db.delete(TABLE.NOTE, - NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); - break; - case URI_DATA: - // 删除数据记录 - count = db.delete(TABLE.DATA, selection, selectionArgs); - deleteData = true; - break; - case URI_DATA_ITEM: - // 删除单条数据记录 - id = uri.getPathSegments().get(1); - count = db.delete(TABLE.DATA, - DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); - deleteData = true; - break; - default: - throw new IllegalArgumentException("Unknown URI " + uri); - } - - // 如果成功删除数据,发送数据变化通知 - if (count > 0) { - if (deleteData) { - // 如果删除的是数据表记录,通知便签URI数据变化 - getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); - } - // 通知当前URI数据变化 - getContext().getContentResolver().notifyChange(uri, null); - } - return count; - } - - /** - * 更新数据 - * @param uri 要更新数据的URI - * @param values 更新的数据值 - * @param selection 更新条件,null表示无条件 - * @param selectionArgs 更新条件参数 - * @return 被更新的行数 - */ - @Override - public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { - int count = 0; - String id = null; - SQLiteDatabase db = mHelper.getWritableDatabase(); - boolean updateData = false; - - // 根据URI类型执行不同的更新操作 - switch (mMatcher.match(uri)) { - case URI_NOTE: - // 更新便签记录,增加版本号 - increaseNoteVersion(-1, selection, selectionArgs); - count = db.update(TABLE.NOTE, values, selection, selectionArgs); - break; - case URI_NOTE_ITEM: - // 更新单条便签记录,增加版本号 - id = uri.getPathSegments().get(1); - 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); - 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); - } - // 通知当前URI数据变化 - getContext().getContentResolver().notifyChange(uri, null); - } - return count; - } - - /** - * 解析查询/更新条件 - * 将原始条件转换为SQL语句中的AND条件 - * @param selection 原始条件字符串 - * @return 格式化后的条件字符串 - */ - private String parseSelection(String selection) { - return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); - } - - /** - * 增加便签版本号 - * 当便签被修改时,调用此方法增加版本号 - * @param id 便签ID,如果id>0则更新指定便签,否则更新所有匹配条件的便签 - * @param selection 更新条件 - * @param selectionArgs 更新条件参数 - */ - private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { - StringBuilder sql = new StringBuilder(120); - sql.append("UPDATE "); - sql.append(TABLE.NOTE); - sql.append(" SET "); - sql.append(NoteColumns.VERSION); - sql.append("=" + NoteColumns.VERSION + "+1 "); - - // 构造WHERE子句 - if (id > 0 || !TextUtils.isEmpty(selection)) { - sql.append(" WHERE "); - } - if (id > 0) { - sql.append(NoteColumns.ID + "=" + String.valueOf(id)); - } - if (!TextUtils.isEmpty(selection)) { - String selectString = id > 0 ? parseSelection(selection) : selection; - // 替换预编译语句中的占位符 - for (String args : selectionArgs) { - selectString = selectString.replaceFirst("\\?", args); - } - sql.append(selectString); - } - - // 执行SQL语句更新版本号 - mHelper.getWritableDatabase().execSQL(sql.toString()); - } - - /** - * 返回指定URI的MIME类型 - * @param uri 要获取MIME类型的URI - * @return MIME类型字符串 - */ - @Override - public String getType(Uri uri) { - // TODO: 实现此方法,返回合适的MIME类型 - return null; - } -} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/gtask/data/MetaData.java b/src/main/java/net/micode/notes/gtask/data/MetaData.java deleted file mode 100644 index 2a39a68..0000000 --- a/src/main/java/net/micode/notes/gtask/data/MetaData.java +++ /dev/null @@ -1,157 +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; - -/** - * MetaData类是Task的子类,用于存储与Google Tasks同步相关的元数据信息。 - *- * 该类主要用于在GTask同步过程中存储任务的关联信息,将元数据以JSON格式存储在 - * Task的notes字段中,并提供了相应的解析和访问方法。 - *
- */ -public class MetaData extends Task { - private final static String TAG = MetaData.class.getSimpleName(); - - /** - * 与当前元数据相关联的Google Task ID - */ - private String mRelatedGid = null; - - /** - * 设置元数据信息 - *- * 将Google Task ID添加到元数据JSON对象中,并将其存储在Task的notes字段中。 - * 同时设置任务名称为元数据标识名称。 - *
- * - * @param gid 与元数据关联的Google Task ID - * @param metaInfo 包含元数据信息的JSON对象 - */ - public void setMeta(String gid, JSONObject metaInfo) { - try { - // 将关联的Google Task ID添加到元数据中 - metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); - } catch (JSONException e) { - Log.e(TAG, "failed to put related gid"); - } - // 将元数据JSON对象转换为字符串并存储在notes字段中 - setNotes(metaInfo.toString()); - // 设置任务名称为元数据标识名称 - setName(GTaskStringUtils.META_NOTE_NAME); - } - - /** - * 获取与当前元数据相关联的Google Task ID - * - * @return 关联的Google Task ID,如果没有则返回null - */ - public String getRelatedGid() { - return mRelatedGid; - } - - /** - * 判断当前元数据是否值得保存 - *- * 只有当notes字段不为null时,元数据才值得保存 - *
- * - * @return 如果notes字段不为null则返回true,否则返回false - */ - @Override - public boolean isWorthSaving() { - return getNotes() != null; - } - - /** - * 从远程JSON数据设置内容 - *- * 从远程获取的JSON数据中解析元信息,并提取关联的Google Task ID - *
- * - * @param js 包含远程数据的JSON对象 - */ - @Override - public void setContentByRemoteJSON(JSONObject js) { - // 调用父类方法设置基本内容 - super.setContentByRemoteJSON(js); - // 如果notes字段不为null,则解析元数据 - if (getNotes() != null) { - try { - // 解析notes字段中的JSON元数据 - JSONObject metaInfo = new JSONObject(getNotes().trim()); - // 提取关联的Google Task ID - mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); - } catch (JSONException e) { - Log.w(TAG, "failed to get related gid"); - mRelatedGid = null; - } - } - } - - /** - * 从本地JSON数据设置内容(不支持) - *- * 该方法不应该被调用,因为MetaData主要用于处理远程同步数据 - *
- * - * @param js 本地JSON对象 - * @throws IllegalAccessError 总是抛出此异常,表示该方法不应该被调用 - */ - @Override - public void setContentByLocalJSON(JSONObject js) { - // 此方法不应该被调用 - throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); - } - - /** - * 从内容获取本地JSON数据(不支持) - *- * 该方法不应该被调用,因为MetaData主要用于处理远程同步数据 - *
- * - * @return 本地JSON对象 - * @throws IllegalAccessError 总是抛出此异常,表示该方法不应该被调用 - */ - @Override - public JSONObject getLocalJSONFromContent() { - throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); - } - - /** - * 获取同步操作(不支持) - *- * 该方法不应该被调用,因为MetaData主要用于处理远程同步数据 - *
- * - * @param c 本地数据库游标 - * @return 同步操作类型 - * @throws IllegalAccessError 总是抛出此异常,表示该方法不应该被调用 - */ - @Override - public int getSyncAction(Cursor c) { - throw new IllegalAccessError("MetaData:getSyncAction should not be called"); - } - -} diff --git a/src/main/java/net/micode/notes/gtask/data/Node.java b/src/main/java/net/micode/notes/gtask/data/Node.java deleted file mode 100644 index dea45d5..0000000 --- a/src/main/java/net/micode/notes/gtask/data/Node.java +++ /dev/null @@ -1,223 +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; - -/** - * Node类是GTask同步系统中的抽象基类,定义了同步节点的基本属性和操作接口。 - *- * 该类为所有参与GTask同步的实体(如Task、TaskList等)提供了统一的接口和基础属性, - * 包括唯一标识符、名称、最后修改时间、删除状态等,并定义了同步操作所需的抽象方法。 - *
- */ -public abstract class Node { - /** - * 同步操作:无操作 - */ - public static final int SYNC_ACTION_NONE = 0; - - /** - * 同步操作:向远程添加节点 - */ - public static final int SYNC_ACTION_ADD_REMOTE = 1; - - /** - * 同步操作:向本地添加节点 - */ - public static final int SYNC_ACTION_ADD_LOCAL = 2; - - /** - * 同步操作:从远程删除节点 - */ - public static final int SYNC_ACTION_DEL_REMOTE = 3; - - /** - * 同步操作:从本地删除节点 - */ - public static final int SYNC_ACTION_DEL_LOCAL = 4; - - /** - * 同步操作:更新远程节点 - */ - public static final int SYNC_ACTION_UPDATE_REMOTE = 5; - - /** - * 同步操作:更新本地节点 - */ - public static final int SYNC_ACTION_UPDATE_LOCAL = 6; - - /** - * 同步操作:更新冲突(本地和远程都有修改) - */ - public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; - - /** - * 同步操作:同步错误 - */ - public static final int SYNC_ACTION_ERROR = 8; - - /** - * 节点的唯一标识符(Google Task ID) - */ - private String mGid; - - /** - * 节点的名称 - */ - private String mName; - - /** - * 节点的最后修改时间戳 - */ - private long mLastModified; - - /** - * 节点的删除状态 - */ - private boolean mDeleted; - - /** - * 构造函数,初始化节点的默认值 - */ - public Node() { - mGid = null; - mName = ""; - mLastModified = 0; - mDeleted = false; - } - - /** - * 获取创建节点的同步操作JSON对象 - * - * @param actionId 操作ID - * @return 创建操作的JSON对象 - */ - public abstract JSONObject getCreateAction(int actionId); - - /** - * 获取更新节点的同步操作JSON对象 - * - * @param actionId 操作ID - * @return 更新操作的JSON对象 - */ - public abstract JSONObject getUpdateAction(int actionId); - - /** - * 从远程JSON数据设置节点内容 - * - * @param js 包含远程数据的JSON对象 - */ - public abstract void setContentByRemoteJSON(JSONObject js); - - /** - * 从本地JSON数据设置节点内容 - * - * @param js 包含本地数据的JSON对象 - */ - public abstract void setContentByLocalJSON(JSONObject js); - - /** - * 从节点内容获取本地JSON数据 - * - * @return 包含本地数据的JSON对象 - */ - public abstract JSONObject getLocalJSONFromContent(); - - /** - * 根据本地数据库游标获取同步操作类型 - * - * @param c 本地数据库游标 - * @return 同步操作类型(参考SYNC_ACTION_*常量) - */ - public abstract int getSyncAction(Cursor c); - - /** - * 设置节点的唯一标识符 - * - * @param gid 节点的唯一标识符(Google Task ID) - */ - public void setGid(String gid) { - this.mGid = gid; - } - - /** - * 设置节点的名称 - * - * @param name 节点的名称 - */ - public void setName(String name) { - this.mName = name; - } - - /** - * 设置节点的最后修改时间戳 - * - * @param lastModified 最后修改时间戳 - */ - public void setLastModified(long lastModified) { - this.mLastModified = lastModified; - } - - /** - * 设置节点的删除状态 - * - * @param deleted 是否删除 - */ - public void setDeleted(boolean deleted) { - this.mDeleted = deleted; - } - - /** - * 获取节点的唯一标识符 - * - * @return 节点的唯一标识符(Google Task ID) - */ - public String getGid() { - return this.mGid; - } - - /** - * 获取节点的名称 - * - * @return 节点的名称 - */ - public String getName() { - return this.mName; - } - - /** - * 获取节点的最后修改时间戳 - * - * @return 最后修改时间戳 - */ - public long getLastModified() { - return this.mLastModified; - } - - /** - * 获取节点的删除状态 - * - * @return 是否删除 - */ - public boolean getDeleted() { - return this.mDeleted; - } - -} diff --git a/src/main/java/net/micode/notes/gtask/data/SqlData.java b/src/main/java/net/micode/notes/gtask/data/SqlData.java deleted file mode 100644 index 3d537ca..0000000 --- a/src/main/java/net/micode/notes/gtask/data/SqlData.java +++ /dev/null @@ -1,337 +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; - - -/** - * SqlData类是小米笔记应用中GTask同步模块的核心数据处理类,负责本地SQL数据的CRUD操作。CRUD 是数据库操作的四种基本功能缩写: - -- C(Create):创建新笔记数据 -- R(Read):读取现有笔记数据 -- U(Update):更新笔记数据 -- D(Delete):删除笔记数据 - *- * 在Notes与Google Tasks的同步过程中,该类扮演着桥梁角色: - * 1. 接收并解析来自GTask的JSON格式数据 - * 2. 将数据转换为本地数据库可存储的格式 - * 3. 通过ContentResolver与本地ContentProvider交互,执行数据的插入、更新和删除操作 - * 4. 支持数据差异跟踪,仅提交修改的字段以优化性能 - * 5. 提供版本验证机制,避免同步冲突 - *
- *- * 该类是同步流程中的关键组件,确保本地笔记数据与Google Tasks之间的数据一致性和完整性。 - *
- */ -public class SqlData { - private static final String TAG = SqlData.class.getSimpleName(); - - /** - * 无效ID常量,用于标记未初始化或无效的数据ID - * 在同步过程中用于区分新创建的数据和已存在的数据 - */ - private static final int INVALID_ID = -99999; - - /** - * 数据库查询投影列,定义了从数据库中获取的数据字段 - * 包含数据ID、MIME类型、内容以及扩展字段DATA1和DATA3 - */ - public static final String[] PROJECTION_DATA = new String[] { - DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, - DataColumns.DATA3 - }; - - /** - * 数据ID列在投影中的索引位置 - */ - public static final int DATA_ID_COLUMN = 0; - - /** - * 数据MIME类型列在投影中的索引位置 - * 用于区分不同类型的数据(如文本笔记、通话记录等) - */ - public static final int DATA_MIME_TYPE_COLUMN = 1; - - /** - * 数据内容列在投影中的索引位置 - * 存储笔记的主要内容 - */ - public static final int DATA_CONTENT_COLUMN = 2; - - /** - * 数据内容DATA1字段在投影中的索引位置 - * 用于存储整数类型的扩展数据(如笔记模式、通话日期等) - */ - public static final int DATA_CONTENT_DATA_1_COLUMN = 3; - - /** - * 数据内容DATA3字段在投影中的索引位置 - * 用于存储字符串类型的扩展数据(如电话号码等) - */ - public static final int DATA_CONTENT_DATA_3_COLUMN = 4; - - /** - * 用于访问ContentProvider的ContentResolver实例 - * 是与本地数据库交互的核心接口 - */ - private ContentResolver mContentResolver; - - /** - * 标记是否为新建数据 - * true表示该数据需要插入数据库,false表示需要更新数据库 - */ - private boolean mIsCreate; - - /** - * 数据ID - * 唯一标识数据库中的数据记录 - */ - private long mDataId; - - /** - * 数据MIME类型 - * 定义数据的类型,如文本笔记(DataConstants.NOTE)或通话记录 - */ - private String mDataMimeType; - - /** - * 数据内容 - * 存储笔记的主要文本内容 - */ - private String mDataContent; - - /** - * 数据内容的DATA1字段 - * 根据MIME类型不同存储不同的整数数据,如: - * - 对于文本笔记:存储笔记模式(普通模式或 checklist 模式) - * - 对于通话记录:存储通话日期 - */ - private long mDataContentData1; - - /** - * 数据内容的DATA3字段 - * 根据MIME类型不同存储不同的字符串数据,如: - * - 对于通话记录:存储电话号码 - */ - private String mDataContentData3; - - /** - * 用于跟踪数据变化的ContentValues对象 - * 只包含已修改的字段,用于优化数据库更新操作 - */ - private ContentValues mDiffDataValues; - - /** - * 构造函数,用于创建新的SqlData实例(用于插入新数据) - *- * 初始化所有字段为默认值,并将mIsCreate标记设置为true - *
- * - * @param context 上下文对象,用于获取ContentResolver实例 - */ - public SqlData(Context context) { - mContentResolver = context.getContentResolver(); - mIsCreate = true; - mDataId = INVALID_ID; - mDataMimeType = DataConstants.NOTE; - mDataContent = ""; - mDataContentData1 = 0; - mDataContentData3 = ""; - mDiffDataValues = new ContentValues(); - } - - /** - * 构造函数,用于从数据库Cursor加载SqlData实例(用于更新现有数据) - *- * 从Cursor中读取数据并初始化所有字段,将mIsCreate标记设置为false - *
- * - * @param context 上下文对象,用于获取ContentResolver实例 - * @param c 数据库Cursor对象,包含要加载的数据记录 - */ - public SqlData(Context context, Cursor c) { - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(c); - mDiffDataValues = new ContentValues(); - } - - /** - * 从数据库Cursor中加载数据到当前SqlData实例 - *- * 根据PROJECTION_DATA中定义的列顺序,从Cursor中读取对应字段的值 - *
- * - * @param c 包含数据的Cursor对象,必须指向有效的数据行 - */ - private void loadFromCursor(Cursor c) { - mDataId = c.getLong(DATA_ID_COLUMN); - mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); - mDataContent = c.getString(DATA_CONTENT_COLUMN); - mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); - mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); - } - - /** - * 从JSON对象设置数据内容,并跟踪数据变化 - *- * 该方法是同步过程中的关键方法,用于将从GTask获取的JSON数据转换为本地数据格式 - * 同时会跟踪数据变化,仅将修改的字段记录到mDiffDataValues中 - *
- * - * @param js 包含GTask数据的JSON对象 - * @throws JSONException 如果JSON解析失败 - */ - public void setContent(JSONObject js) throws JSONException { - long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; - if (mIsCreate || mDataId != dataId) { - mDiffDataValues.put(DataColumns.ID, dataId); - } - mDataId = dataId; - - String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) - : DataConstants.NOTE; - if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { - mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); - } - mDataMimeType = dataMimeType; - - String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; - if (mIsCreate || !mDataContent.equals(dataContent)) { - mDiffDataValues.put(DataColumns.CONTENT, dataContent); - } - mDataContent = dataContent; - - long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; - if (mIsCreate || mDataContentData1 != dataContentData1) { - mDiffDataValues.put(DataColumns.DATA1, dataContentData1); - } - mDataContentData1 = dataContentData1; - - String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; - if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { - mDiffDataValues.put(DataColumns.DATA3, dataContentData3); - } - mDataContentData3 = dataContentData3; - } - - /** - * 获取当前数据的JSON表示 - *- * 将本地数据转换为JSON格式,用于与GTask进行数据交换 - * 注意:只有已提交到数据库的数据才能获取JSON表示 - *
- * - * @return 包含当前数据的JSON对象,如果数据未提交到数据库则返回null - * @throws JSONException 如果JSON构建失败 - */ - public JSONObject getContent() throws JSONException { - if (mIsCreate) { - Log.e(TAG, "it seems that we haven't created this in database yet"); - return null; - } - JSONObject js = new JSONObject(); - js.put(DataColumns.ID, mDataId); - js.put(DataColumns.MIME_TYPE, mDataMimeType); - js.put(DataColumns.CONTENT, mDataContent); - js.put(DataColumns.DATA1, mDataContentData1); - js.put(DataColumns.DATA3, mDataContentData3); - return js; - } - - /** - * 将数据提交到本地数据库 - *- * 这是SqlData类的核心方法,根据mIsCreate标记执行插入或更新操作: - * 1. 如果是新数据(mIsCreate=true),执行插入操作 - * 2. 如果是现有数据(mIsCreate=false),仅当有数据变化时执行更新操作 - * 3. 支持版本验证机制,避免在同步过程中出现数据冲突 - *
- * - * @param noteId 所属的Note ID,用于关联到具体的笔记 - * @param validateVersion 是否验证版本,true表示需要进行版本检查 - * @param version 版本号,用于版本验证 - * @throws ActionFailureException 如果数据提交失败 - */ - public void commit(long noteId, boolean validateVersion, long version) { - - if (mIsCreate) { - if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { - mDiffDataValues.remove(DataColumns.ID); - } - - mDiffDataValues.put(DataColumns.NOTE_ID, noteId); - Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); - try { - mDataId = Long.valueOf(uri.getPathSegments().get(1)); - } catch (NumberFormatException e) { - Log.e(TAG, "Get note id error :" + e.toString()); - throw new ActionFailureException("create note failed"); - } - } else { - if (mDiffDataValues.size() > 0) { - int result = 0; - if (!validateVersion) { - result = mContentResolver.update(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); - } else { - result = mContentResolver.update(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, - " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE - + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { - String.valueOf(noteId), String.valueOf(version) - }); - } - if (result == 0) { - Log.w(TAG, "there is no update. maybe user updates note when syncing"); - } - } - } - - mDiffDataValues.clear(); - mIsCreate = false; - } - - /** - * 获取数据ID - *- * 返回当前数据的唯一标识符,用于在数据库中定位该记录 - *
- * - * @return 数据ID,如果数据未提交到数据库则返回INVALID_ID - */ - public long getId() { - return mDataId; - } -} diff --git a/src/main/java/net/micode/notes/gtask/data/SqlNote.java b/src/main/java/net/micode/notes/gtask/data/SqlNote.java deleted file mode 100644 index ad39ff5..0000000 --- a/src/main/java/net/micode/notes/gtask/data/SqlNote.java +++ /dev/null @@ -1,714 +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; - - -/** - * SqlNote类是小米笔记应用中GTask同步模块的核心类,负责本地笔记数据的CRUD操作。 - *- * 在Notes与Google Tasks的同步过程中,该类扮演着重要角色: - * 1. 封装本地笔记数据模型,支持笔记和文件夹两种类型 - * 2. 通过ContentResolver与本地ContentProvider交互,执行数据的插入、更新和删除操作 - * 3. 支持将JSON格式的GTask数据转换为本地数据模型 - * 4. 支持将本地数据模型转换为JSON格式以便与GTask同步 - * 5. 实现数据差异跟踪,仅提交修改的字段以优化性能 - * 6. 提供版本验证机制,避免同步冲突 - *
- */ -public class SqlNote { - private static final String TAG = SqlNote.class.getSimpleName(); - - /** - * 无效的ID值,用于初始化和错误检查 - */ - private static final int INVALID_ID = -99999; - -/** - * 查询笔记时使用的投影列,包含笔记的所有核心字段 - */ - public static final String[] PROJECTION_NOTE = new String[] { - NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, - NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, - NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE, - NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID, - NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID, - NoteColumns.VERSION - }; - -/** - * 投影列索引:笔记ID - */ - public static final int ID_COLUMN = 0; - - /** - * 投影列索引:提醒日期 - */ - public static final int ALERTED_DATE_COLUMN = 1; - - /** - * 投影列索引:背景颜色ID - */ - public static final int BG_COLOR_ID_COLUMN = 2; - - /** - * 投影列索引:创建日期 - */ - public static final int CREATED_DATE_COLUMN = 3; - - /** - * 投影列索引:是否有附件 - */ - public static final int HAS_ATTACHMENT_COLUMN = 4; - - /** - * 投影列索引:修改日期 - */ - public static final int MODIFIED_DATE_COLUMN = 5; - - /** - * 投影列索引:笔记数量 - */ - public static final int NOTES_COUNT_COLUMN = 6; - - /** - * 投影列索引:父文件夹ID - */ - public static final int PARENT_ID_COLUMN = 7; - - /** - * 投影列索引:笔记摘要 - */ - public static final int SNIPPET_COLUMN = 8; - - /** - * 投影列索引:笔记类型(笔记或文件夹) - */ - public static final int TYPE_COLUMN = 9; - - /** - * 投影列索引:小部件ID - */ - public static final int WIDGET_ID_COLUMN = 10; - - /** - * 投影列索引:小部件类型 - */ - public static final int WIDGET_TYPE_COLUMN = 11; - - /** - * 投影列索引:同步ID - */ - public static final int SYNC_ID_COLUMN = 12; - - /** - * 投影列索引:本地修改标记 - */ - public static final int LOCAL_MODIFIED_COLUMN = 13; - - /** - * 投影列索引:原始父文件夹ID - */ - public static final int ORIGIN_PARENT_ID_COLUMN = 14; - - /** - * 投影列索引:Google Task ID - */ - public static final int GTASK_ID_COLUMN = 15; - - /** - * 投影列索引:版本号 - */ - public static final int VERSION_COLUMN = 16; - - /** - * 上下文对象,用于访问系统服务 - */ - private Context mContext; - - /** - * ContentResolver对象,用于与ContentProvider交互 - */ - private ContentResolver mContentResolver; - - /** - * 标记是否为新创建的笔记 - */ - private boolean mIsCreate; - - /** - * 笔记ID - */ - private long mId; - - /** - * 提醒日期 - */ - private long mAlertDate; - - /** - * 背景颜色ID - */ - private int mBgColorId; - - /** - * 创建日期 - */ - private long mCreatedDate; - - /** - * 是否有附件(0:无,1:有) - */ - private int mHasAttachment; - - /** - * 修改日期 - */ - private long mModifiedDate; - - /** - * 父文件夹ID - */ - private long mParentId; - - /** - * 笔记摘要 - */ - private String mSnippet; - - /** - * 笔记类型(笔记或文件夹) - */ - private int mType; - - /** - * 小部件ID - */ - private int mWidgetId; - - /** - * 小部件类型 - */ - private int mWidgetType; - - /** - * 原始父文件夹ID - */ - private long mOriginParent; - - /** - * 版本号,用于避免同步冲突 - */ - private long mVersion; - - /** - * 记录笔记数据的变更,仅提交修改的字段以优化性能 - */ - private ContentValues mDiffNoteValues; - - /** - * 笔记内容列表,每个SqlData对象代表笔记的一个内容部分 - */ - private ArrayList- * 在小米笔记与Google Tasks的同步过程中,该类负责: - * 1. 封装Google Tasks任务的数据模型 - * 2. 实现任务的创建、更新等同步操作 - * 3. 处理本地数据与Google Tasks数据之间的转换 - * 4. 管理任务的层次结构和关系 - *
- */ -public class Task extends Node { - private static final String TAG = Task.class.getSimpleName(); - - /** - * 任务是否已完成 - */ - private boolean mCompleted; - - /** - * 任务的备注信息 - */ - private String mNotes; - - /** - * 任务的元信息,包含与本地笔记的关联数据 - */ - private JSONObject mMetaInfo; - - /** - * 任务的前一个兄弟节点(在同一父任务列表中的前一个任务) - */ - private Task mPriorSibling; - - /** - * 任务的父任务列表 - */ - private TaskList mParent; - -/** - * 构造函数,创建一个新的Task对象 - */ - public Task() { - super(); - mCompleted = false; - mNotes = null; - mPriorSibling = null; - mParent = null; - mMetaInfo = null; - } - -/** - * 获取创建任务的JSON动作 - *- * 该方法生成用于向Google Tasks服务器发送创建任务请求的JSON数据 - *
- * - * @param actionId 动作ID,用于标识当前操作 - * @return 包含创建任务信息的JSON对象 - * @throws ActionFailureException 如果生成JSON对象失败 - */ - public JSONObject getCreateAction(int actionId) { - JSONObject js = new JSONObject(); - - try { - // action_type - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); - - // action_id - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // index - js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); - - // entity_delta - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); - entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); - entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, - GTaskStringUtils.GTASK_JSON_TYPE_TASK); - if (getNotes() != null) { - entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); - } - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - // parent_id - js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); - - // dest_parent_type - js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, - GTaskStringUtils.GTASK_JSON_TYPE_GROUP); - - // list_id - js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); - - // prior_sibling_id - if (mPriorSibling != null) { - js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); - } - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate task-create jsonobject"); - } - - return js; - } - -/** - * 获取更新任务的JSON动作 - *- * 该方法生成用于向Google Tasks服务器发送更新任务请求的JSON数据 - *
- * - * @param actionId 动作ID,用于标识当前操作 - * @return 包含更新任务信息的JSON对象 - * @throws ActionFailureException 如果生成JSON对象失败 - */ - public JSONObject getUpdateAction(int actionId) { - JSONObject js = new JSONObject(); - - try { - // action_type - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); - - // action_id - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // id - js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); - - // entity_delta - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); - if (getNotes() != null) { - entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); - } - entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate task-update jsonobject"); - } - - return js; - } - -/** - * 从Google Tasks服务器返回的JSON数据设置任务内容 - * - * @param js 包含Google Tasks任务数据的JSON对象 - * @throws ActionFailureException 如果解析JSON数据失败 - */ - public void setContentByRemoteJSON(JSONObject js) { - if (js != null) { - try { - // id - if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { - setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); - } - - // last_modified - if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { - setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); - } - - // name - if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { - setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); - } - - // notes - if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { - setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); - } - - // deleted - if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { - setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); - } - - // completed - if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { - setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to get task content from jsonobject"); - } - } - } - -/** - * 从本地JSON数据设置任务内容 - * - * @param js 包含本地笔记数据的JSON对象 - */ - public void setContentByLocalJSON(JSONObject js) { - if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) - || !js.has(GTaskStringUtils.META_HEAD_DATA)) { - Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); - } - - try { - JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - - if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { - Log.e(TAG, "invalid type"); - return; - } - - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { - setName(data.getString(DataColumns.CONTENT)); - break; - } - } - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - } - -/** - * 获取任务内容的本地JSON表示 - *- * 该方法将任务数据转换为本地笔记系统使用的JSON格式 - *
- * - * @return 包含任务数据的本地JSON对象,如果转换失败返回null - */ - public JSONObject getLocalJSONFromContent() { - String name = getName(); - try { - if (mMetaInfo == null) { - // new task created from web - if (name == null) { - Log.w(TAG, "the note seems to be an empty one"); - return null; - } - - JSONObject js = new JSONObject(); - JSONObject note = new JSONObject(); - JSONArray dataArray = new JSONArray(); - JSONObject data = new JSONObject(); - data.put(DataColumns.CONTENT, name); - dataArray.put(data); - js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); - note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); - js.put(GTaskStringUtils.META_HEAD_NOTE, note); - return js; - } else { - // synced task - JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { - data.put(DataColumns.CONTENT, getName()); - break; - } - } - - note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); - return mMetaInfo; - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return null; - } - } - -/** - * 设置任务的元信息 - *- * 元信息包含任务与本地笔记的关联数据 - *
- * - * @param metaData 包含元信息的MetaData对象 - */ - public void setMetaInfo(MetaData metaData) { - if (metaData != null && metaData.getNotes() != null) { - try { - mMetaInfo = new JSONObject(metaData.getNotes()); - } catch (JSONException e) { - Log.w(TAG, e.toString()); - mMetaInfo = null; - } - } - } - -/** - * 获取任务的同步动作类型 - *- * 该方法根据本地数据和远程数据的状态,确定需要执行的同步操作类型 - *
- * - * @param c 包含本地笔记数据的Cursor对象 - * @return 同步动作类型,取值为SYNC_ACTION_*常量之一 - */ - public int getSyncAction(Cursor c) { - try { - JSONObject noteInfo = null; - if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { - noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - } - - if (noteInfo == null) { - Log.w(TAG, "it seems that note meta has been deleted"); - return SYNC_ACTION_UPDATE_REMOTE; - } - - if (!noteInfo.has(NoteColumns.ID)) { - Log.w(TAG, "remote note id seems to be deleted"); - return SYNC_ACTION_UPDATE_LOCAL; - } - - // validate the note id now - if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { - Log.w(TAG, "note id doesn't match"); - return SYNC_ACTION_UPDATE_LOCAL; - } - - if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { - // there is no local update - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // no update both side - return SYNC_ACTION_NONE; - } else { - // apply remote to local - return SYNC_ACTION_UPDATE_LOCAL; - } - } else { - // validate gtask id - if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { - Log.e(TAG, "gtask id doesn't match"); - return SYNC_ACTION_ERROR; - } - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // local modification only - return SYNC_ACTION_UPDATE_REMOTE; - } else { - return SYNC_ACTION_UPDATE_CONFLICT; - } - } - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - - return SYNC_ACTION_ERROR; - } - -/** - * 判断任务是否值得保存 - *- * 如果任务有元信息、名称或备注,则认为值得保存 - *
- * - * @return 任务值得保存返回true,否则返回false - */ - public boolean isWorthSaving() { - return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) - || (getNotes() != null && getNotes().trim().length() > 0); - } - -/** - * 设置任务的完成状态 - * - * @param completed 任务是否已完成 - */ - public void setCompleted(boolean completed) { - this.mCompleted = completed; - } - -/** - * 设置任务的备注信息 - * - * @param notes 任务的备注信息 - */ - public void setNotes(String notes) { - this.mNotes = notes; - } - -/** - * 设置任务的前一个兄弟节点 - * - * @param priorSibling 前一个兄弟任务 - */ - public void setPriorSibling(Task priorSibling) { - this.mPriorSibling = priorSibling; - } - -/** - * 设置任务的父任务列表 - * - * @param parent 父任务列表 - */ - public void setParent(TaskList parent) { - this.mParent = parent; - } - -/** - * 获取任务的完成状态 - * - * @return 任务是否已完成 - */ - public boolean getCompleted() { - return this.mCompleted; - } - -/** - * 获取任务的备注信息 - * - * @return 任务的备注信息 - */ - public String getNotes() { - return this.mNotes; - } - -/** - * 获取任务的前一个兄弟节点 - * - * @return 前一个兄弟任务 - */ - public Task getPriorSibling() { - return this.mPriorSibling; - } - -/** - * 获取任务的父任务列表 - * - * @return 父任务列表 - */ - public TaskList getParent() { - return this.mParent; - } - -} diff --git a/src/main/java/net/micode/notes/gtask/data/TaskList.java b/src/main/java/net/micode/notes/gtask/data/TaskList.java deleted file mode 100644 index 1cfab78..0000000 --- a/src/main/java/net/micode/notes/gtask/data/TaskList.java +++ /dev/null @@ -1,486 +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; - - -/** - * TaskList类是Node类的子类,用于表示Google Tasks中的任务列表。 - *- * 在小米笔记与Google Tasks的同步过程中,该类负责: - * 1. 封装Google Tasks任务列表的数据模型 - * 2. 管理任务列表中的子任务(Task对象) - * 3. 实现任务列表的创建、更新等同步操作 - * 4. 处理本地文件夹与Google Tasks列表之间的转换 - *
- */ -public class TaskList extends Node { - private static final String TAG = TaskList.class.getSimpleName(); - - /** - * 任务列表的索引位置 - */ - private int mIndex; - - /** - * 任务列表中的子任务列表 - */ - private ArrayList- * 该方法生成用于向Google Tasks服务器发送创建任务列表请求的JSON数据 - *
- * - * @param actionId 动作ID,用于标识当前操作 - * @return 包含创建任务列表信息的JSON对象 - * @throws ActionFailureException 如果生成JSON对象失败 - */ - public JSONObject getCreateAction(int actionId) { - JSONObject js = new JSONObject(); - - try { - // action_type - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); - - // action_id - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // index - js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); - - // entity_delta - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); - entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); - entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, - GTaskStringUtils.GTASK_JSON_TYPE_GROUP); - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate tasklist-create jsonobject"); - } - - return js; - } - -/** - * 获取更新任务列表的JSON动作 - *- * 该方法生成用于向Google Tasks服务器发送更新任务列表请求的JSON数据 - *
- * - * @param actionId 动作ID,用于标识当前操作 - * @return 包含更新任务列表信息的JSON对象 - * @throws ActionFailureException 如果生成JSON对象失败 - */ - public JSONObject getUpdateAction(int actionId) { - JSONObject js = new JSONObject(); - - try { - // action_type - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); - - // action_id - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // id - js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); - - // entity_delta - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); - entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate tasklist-update jsonobject"); - } - - return js; - } - -/** - * 从Google Tasks服务器返回的JSON数据设置任务列表内容 - * - * @param js 包含Google Tasks任务列表数据的JSON对象 - * @throws ActionFailureException 如果解析JSON数据失败 - */ - public void setContentByRemoteJSON(JSONObject js) { - if (js != null) { - try { - // id - if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { - setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); - } - - // last_modified - if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { - setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); - } - - // name - if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { - setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); - } - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to get tasklist content from jsonobject"); - } - } - } - -/** - * 从本地JSON数据设置任务列表内容 - *- * 根据本地文件夹类型设置任务列表名称,支持普通文件夹、系统文件夹等 - *
- * - * @param js 包含本地文件夹数据的JSON对象 - */ - public void setContentByLocalJSON(JSONObject js) { - if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { - Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); - } - - try { - JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - - if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { - String name = folder.getString(NoteColumns.SNIPPET); - setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); - } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { - if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) - setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); - else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) - setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_CALL_NOTE); - else - Log.e(TAG, "invalid system folder"); - } else { - Log.e(TAG, "error type"); - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - } - -/** - * 获取任务列表内容的本地JSON表示 - *- * 该方法将任务列表数据转换为本地文件夹系统使用的JSON格式 - *
- * - * @return 包含任务列表数据的本地JSON对象,如果转换失败返回null - */ - public JSONObject getLocalJSONFromContent() { - try { - JSONObject js = new JSONObject(); - JSONObject folder = new JSONObject(); - - String folderName = getName(); - if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) - folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), - folderName.length()); - folder.put(NoteColumns.SNIPPET, folderName); - if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) - || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) - folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); - else - folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); - - js.put(GTaskStringUtils.META_HEAD_NOTE, folder); - - return js; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return null; - } - } - -/** - * 获取任务列表的同步动作类型 - *- * 该方法根据本地数据和远程数据的状态,确定需要执行的同步操作类型 - *
- * - * @param c 包含本地文件夹数据的Cursor对象 - * @return 同步动作类型,取值为SYNC_ACTION_*常量之一 - */ - public int getSyncAction(Cursor c) { - try { - if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { - // there is no local update - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // no update both side - return SYNC_ACTION_NONE; - } else { - // apply remote to local - return SYNC_ACTION_UPDATE_LOCAL; - } - } else { - // validate gtask id - if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { - Log.e(TAG, "gtask id doesn't match"); - return SYNC_ACTION_ERROR; - } - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // local modification only - return SYNC_ACTION_UPDATE_REMOTE; - } else { - // for folder conflicts, just apply local modification - return SYNC_ACTION_UPDATE_REMOTE; - } - } - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - - return SYNC_ACTION_ERROR; - } - -/** - * 获取任务列表中的子任务数量 - * - * @return 子任务数量 - */ - public int getChildTaskCount() { - return mChildren.size(); - } - -/** - * 向任务列表中添加子任务 - * - * @param task 要添加的子任务 - * @return 添加成功返回true,否则返回false - */ - public boolean addChildTask(Task task) { - boolean ret = false; - if (task != null && !mChildren.contains(task)) { - ret = mChildren.add(task); - if (ret) { - // need to set prior sibling and parent - task.setPriorSibling(mChildren.isEmpty() ? null : mChildren - .get(mChildren.size() - 1)); - task.setParent(this); - } - } - return ret; - } - -/** - * 在指定位置向任务列表中添加子任务 - * - * @param task 要添加的子任务 - * @param index 要添加的位置索引 - * @return 添加成功返回true,否则返回false - */ - public boolean addChildTask(Task task, int index) { - if (index < 0 || index > mChildren.size()) { - Log.e(TAG, "add child task: invalid index"); - return false; - } - - int pos = mChildren.indexOf(task); - if (task != null && pos == -1) { - mChildren.add(index, task); - - // update the task list - Task preTask = null; - Task afterTask = null; - if (index != 0) - preTask = mChildren.get(index - 1); - if (index != mChildren.size() - 1) - afterTask = mChildren.get(index + 1); - - task.setPriorSibling(preTask); - if (afterTask != null) - afterTask.setPriorSibling(task); - } - - return true; - } - -/** - * 从任务列表中移除子任务 - * - * @param task 要移除的子任务 - * @return 移除成功返回true,否则返回false - */ - public boolean removeChildTask(Task task) { - boolean ret = false; - int index = mChildren.indexOf(task); - if (index != -1) { - ret = mChildren.remove(task); - - if (ret) { - // reset prior sibling and parent - task.setPriorSibling(null); - task.setParent(null); - - // update the task list - if (index != mChildren.size()) { - mChildren.get(index).setPriorSibling( - index == 0 ? null : mChildren.get(index - 1)); - } - } - } - return ret; - } - -/** - * 移动任务列表中的子任务到指定位置 - * - * @param task 要移动的子任务 - * @param index 目标位置索引 - * @return 移动成功返回true,否则返回false - */ - public boolean moveChildTask(Task task, int index) { - - if (index < 0 || index >= mChildren.size()) { - Log.e(TAG, "move child task: invalid index"); - return false; - } - - int pos = mChildren.indexOf(task); - if (pos == -1) { - Log.e(TAG, "move child task: the task should in the list"); - return false; - } - - if (pos == index) - return true; - return (removeChildTask(task) && addChildTask(task, index)); - } - -/** - * 根据Google Task ID查找子任务 - * - * @param gid Google Task ID - * @return 找到的子任务,如果找不到返回null - */ - public Task findChildTaskByGid(String gid) { - for (int i = 0; i < mChildren.size(); i++) { - Task t = mChildren.get(i); - if (t.getGid().equals(gid)) { - return t; - } - } - return null; - } - -/** - * 获取子任务在任务列表中的索引位置 - * - * @param task 要查找的子任务 - * @return 子任务的索引位置,如果不存在返回-1 - */ - public int getChildTaskIndex(Task task) { - return mChildren.indexOf(task); - } - -/** - * 根据索引位置获取子任务 - * - * @param index 要获取的子任务的索引位置 - * @return 索引位置对应的子任务,如果索引无效返回null - */ - public Task getChildTaskByIndex(int index) { - if (index < 0 || index >= mChildren.size()) { - Log.e(TAG, "getTaskByIndex: invalid index"); - return null; - } - return mChildren.get(index); - } - -/** - * 根据Google Task ID获取子任务 - *- * 注意:该方法与findChildTaskByGid功能相同,名称可能存在拼写错误("ChilTask"应为"ChildTask") - *
- * - * @param gid Google Task ID - * @return 找到的子任务,如果找不到返回null - */ - public Task getChilTaskByGid(String gid) { - for (Task task : mChildren) { - if (task.getGid().equals(gid)) - return task; - } - return null; - } - -/** - * 获取任务列表中的所有子任务 - * - * @return 包含所有子任务的ArrayList - */ - public ArrayList- * 当GTask同步操作(如创建、更新、删除任务或任务列表)执行失败时抛出此异常 - *
- */ -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/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java b/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java deleted file mode 100644 index b9f564d..0000000 --- a/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java +++ /dev/null @@ -1,39 +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; - -/** - * NetworkFailureException是GTask同步过程中用于表示网络操作失败的自定义检查型异常 - *- * 当GTask同步操作(如网络请求、数据传输)因网络问题(如网络连接中断、超时等)失败时抛出此异常 - *
- */ -public class NetworkFailureException extends Exception { - private static final long serialVersionUID = 2107610287180234136L; - - public NetworkFailureException() { - super(); - } - - public NetworkFailureException(String paramString) { - super(paramString); - } - - public NetworkFailureException(String paramString, Throwable paramThrowable) { - super(paramString, paramThrowable); - } -} diff --git a/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java deleted file mode 100644 index 9e52a69..0000000 --- a/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java +++ /dev/null @@ -1,209 +0,0 @@ - -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.remote; - -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.os.AsyncTask; - -import net.micode.notes.R; -import net.micode.notes.ui.NotesListActivity; -import net.micode.notes.ui.NotesPreferenceActivity; - - -/** - * GTaskASyncTask是用于在后台执行GTask同步操作的异步任务类 - *- * 该类负责: - * 1. 在后台线程执行GTask同步操作 - * 2. 显示同步进度通知 - * 3. 处理同步结果并显示相应通知 - * 4. 支持同步取消功能 - *
- */ -public class GTaskASyncTask extends AsyncTask- * 该类提供了以下主要功能: - * 1. Google账号登录和认证 - * 2. 创建、更新、删除任务 - * 3. 创建、更新、删除任务列表 - * 4. 移动任务(在同一任务列表内或不同任务列表之间) - * 5. 获取任务列表和任务数据 - *
- *- * 该类采用单例模式设计,确保应用中只有一个GTask客户端实例 - *
- */ -public class GTaskClient { - /** - * 日志标签 - */ - private static final String TAG = GTaskClient.class.getSimpleName(); - - /** - * Google Tasks基础URL - */ - private static final String GTASK_URL = "https://mail.google.com/tasks/"; - - /** - * Google Tasks GET请求URL - */ - private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; - - /** - * Google Tasks POST请求URL - */ - private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; - - /** - * GTaskClient单例实例 - */ - private static GTaskClient mInstance = null; - - /** - * HTTP客户端实例,用于与Google Tasks服务器进行通信 - */ - private DefaultHttpClient mHttpClient; - - /** - * 当前使用的GET请求URL - */ - private String mGetUrl; - - /** - * 当前使用的POST请求URL - */ - private String mPostUrl; - - /** - * Google Tasks客户端版本号 - */ - private long mClientVersion; - - /** - * 登录状态标志 - */ - private boolean mLoggedin; - - /** - * 上次登录时间 - */ - private long mLastLoginTime; - - /** - * 操作ID,用于标识不同的同步操作 - */ - private int mActionId; - - /** - * 当前同步的Google账号 - */ - private Account mAccount; - - /** - * 更新操作数组,用于批量提交更新操作 - */ - private JSONArray mUpdateArray; - - /** - * GTaskClient构造函数(私有,用于单例模式) - */ - private GTaskClient() { - mHttpClient = null; - mGetUrl = GTASK_GET_URL; - mPostUrl = GTASK_POST_URL; - mClientVersion = -1; - mLoggedin = false; - mLastLoginTime = 0; - mActionId = 1; - mAccount = null; - mUpdateArray = null; - } - - /** - * 获取GTaskClient单例实例 - * - * @return GTaskClient单例实例 - */ - public static synchronized GTaskClient getInstance() { - if (mInstance == null) { - mInstance = new GTaskClient(); - } - return mInstance; - } - - /** - * 登录Google Tasks账号 - *- * 如果距离上次登录时间不超过5分钟,则不需要重新登录 - * 如果账号发生变化,需要重新登录 - *
- * - * @param activity 调用登录的Activity - * @return 登录成功返回true,失败返回false - */ - public boolean login(Activity activity) { - // we suppose that the cookie would expire after 5 minutes - // then we need to re-login - final long interval = 1000 * 60 * 5; - if (mLastLoginTime + interval < System.currentTimeMillis()) { - mLoggedin = false; - } - - // need to re-login after account switch - if (mLoggedin - && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity - .getSyncAccountName(activity))) { - mLoggedin = false; - } - - if (mLoggedin) { - Log.d(TAG, "already logged in"); - return true; - } - - mLastLoginTime = System.currentTimeMillis(); - String authToken = loginGoogleAccount(activity, false); - if (authToken == null) { - Log.e(TAG, "login google account failed"); - return false; - } - - // login with custom domain if necessary - if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() - .endsWith("googlemail.com"))) { - StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); - int index = mAccount.name.indexOf('@') + 1; - String suffix = mAccount.name.substring(index); - url.append(suffix + "/"); - mGetUrl = url.toString() + "ig"; - mPostUrl = url.toString() + "r/ig"; - - if (tryToLoginGtask(activity, authToken)) { - mLoggedin = true; - } - } - - // try to login with google official url - if (!mLoggedin) { - mGetUrl = GTASK_GET_URL; - mPostUrl = GTASK_POST_URL; - if (!tryToLoginGtask(activity, authToken)) { - return false; - } - } - - mLoggedin = true; - return true; - } - - /** - * 登录Google账号,获取认证令牌 - * - * @param activity 调用登录的Activity - * @param invalidateToken 是否使当前令牌失效 - * @return 认证令牌字符串,失败返回null - */ - private String loginGoogleAccount(Activity activity, boolean invalidateToken) { - String authToken; - AccountManager accountManager = AccountManager.get(activity); - Account[] accounts = accountManager.getAccountsByType("com.google"); - - if (accounts.length == 0) { - Log.e(TAG, "there is no available google account"); - return null; - } - - String accountName = NotesPreferenceActivity.getSyncAccountName(activity); - Account account = null; - for (Account a : accounts) { - if (a.name.equals(accountName)) { - account = a; - break; - } - } - if (account != null) { - mAccount = account; - } else { - Log.e(TAG, "unable to get an account with the same name in the settings"); - return null; - } - - // get the token now - AccountManagerFuture- * 如果登录失败,会尝试使令牌失效并重新登录 - *
- * - * @param activity 调用登录的Activity - * @param authToken 认证令牌 - * @return 登录成功返回true,失败返回false - */ - private boolean tryToLoginGtask(Activity activity, String authToken) { - if (!loginGtask(authToken)) { - // maybe the auth token is out of date, now let's invalidate the - // token and try again - authToken = loginGoogleAccount(activity, true); - if (authToken == null) { - Log.e(TAG, "login google account failed"); - return false; - } - - if (!loginGtask(authToken)) { - Log.e(TAG, "login gtask failed"); - return false; - } - } - return true; - } - - /** - * 使用认证令牌登录Google Tasks - * - * @param authToken 认证令牌 - * @return 登录成功返回true,失败返回false - */ - private boolean loginGtask(String authToken) { - int timeoutConnection = 10000; - int timeoutSocket = 15000; - HttpParams httpParameters = new BasicHttpParams(); - HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); - HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); - mHttpClient = new DefaultHttpClient(httpParameters); - BasicCookieStore localBasicCookieStore = new BasicCookieStore(); - mHttpClient.setCookieStore(localBasicCookieStore); - HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); - - // login gtask - try { - String loginUrl = mGetUrl + "?auth=" + authToken; - HttpGet httpGet = new HttpGet(loginUrl); - HttpResponse response = null; - response = mHttpClient.execute(httpGet); - - // get the cookie now - List- * 支持gzip和deflate压缩格式 - *
- * - * @param entity HTTP响应实体 - * @return 响应内容字符串 - * @throws IOException 如果读取响应内容失败 - */ - private String getResponseContent(HttpEntity entity) throws IOException { - String contentEncoding = null; - if (entity.getContentEncoding() != null) { - contentEncoding = entity.getContentEncoding().getValue(); - Log.d(TAG, "encoding: " + contentEncoding); - } - - InputStream input = entity.getContent(); - if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { - input = new GZIPInputStream(entity.getContent()); - } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { - Inflater inflater = new Inflater(true); - input = new InflaterInputStream(entity.getContent(), inflater); - } - - try { - InputStreamReader isr = new InputStreamReader(input); - BufferedReader br = new BufferedReader(isr); - StringBuilder sb = new StringBuilder(); - - while (true) { - String buff = br.readLine(); - if (buff == null) { - return sb.toString(); - } - sb = sb.append(buff); - } - } finally { - input.close(); - } - } - - /** - * 发送POST请求到Google Tasks服务器 - * - * @param js 请求内容的JSON对象 - * @return 响应内容的JSON对象 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果请求格式或响应解析失败 - */ - private JSONObject postRequest(JSONObject js) throws NetworkFailureException { - if (!mLoggedin) { - Log.e(TAG, "please login first"); - throw new ActionFailureException("not logged in"); - } - - HttpPost httpPost = createHttpPost(); - try { - LinkedList- * 如果更新数组中的操作数量超过10个,则立即提交更新 - *
- * - * @param node 要更新的节点对象 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果更新操作添加失败 - */ - public void addUpdateNode(Node node) throws NetworkFailureException { - if (node != null) { - // too many update items may result in an error - // set max to 10 items - if (mUpdateArray != null && mUpdateArray.length() > 10) { - commitUpdate(); - } - - if (mUpdateArray == null) - mUpdateArray = new JSONArray(); - mUpdateArray.put(node.getUpdateAction(getActionId())); - } - } - - /** - * 移动任务 - *- * 支持在同一任务列表内移动或在不同任务列表之间移动 - *
- * - * @param task 要移动的任务 - * @param preParent 任务原来的父任务列表 - * @param curParent 任务现在的父任务列表 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果任务移动失败 - */ - public void moveTask(Task task, TaskList preParent, TaskList curParent) - throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - JSONObject action = new JSONObject(); - - // action_list - action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); - action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); - action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); - if (preParent == curParent && task.getPriorSibling() != null) { - // put prioring_sibing_id only if moving within the tasklist and - // it is not the first one - action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); - } - action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); - action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); - if (preParent != curParent) { - // put the dest_list only if moving between tasklists - action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); - } - actionList.put(action); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - postRequest(jsPost); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("move task: handing jsonobject failed"); - } - } - - /** - * 删除节点(任务或任务列表) - * - * @param node 要删除的节点对象 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果节点删除失败 - */ - 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"); - } - } - - /** - * 获取所有任务列表 - * - * @return 包含所有任务列表的JSON数组 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果获取任务列表失败 - */ - public JSONArray getTaskLists() throws NetworkFailureException { - if (!mLoggedin) { - Log.e(TAG, "please login first"); - throw new ActionFailureException("not logged in"); - } - - try { - HttpGet httpGet = new HttpGet(mGetUrl); - HttpResponse response = null; - response = mHttpClient.execute(httpGet); - - // get the task list - String resString = getResponseContent(response.getEntity()); - String jsBegin = "_setup("; - String jsEnd = ")}"; - int begin = resString.indexOf(jsBegin); - int end = resString.lastIndexOf(jsEnd); - String jsString = null; - if (begin != -1 && end != -1 && begin < end) { - jsString = resString.substring(begin + jsBegin.length(), end); - } - JSONObject js = new JSONObject(jsString); - return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); - } catch (ClientProtocolException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("gettasklists: httpget failed"); - } catch (IOException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("gettasklists: httpget failed"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("get task lists: handing jasonobject failed"); - } - } - - /** - * 获取指定任务列表中的所有任务 - * - * @param listGid 任务列表的Google ID - * @return 包含任务列表中所有任务的JSON数组 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果获取任务失败 - */ - public JSONArray getTaskList(String listGid) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - JSONObject action = new JSONObject(); - - // action_list - action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); - action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); - action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); - action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); - actionList.put(action); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - JSONObject jsResponse = postRequest(jsPost); - return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("get task list: handing jsonobject failed"); - } - } - - /** - * 获取当前同步的Google账号 - * - * @return 当前同步的Google账号 - */ - public Account getSyncAccount() { - return mAccount; - } - - /** - * 重置更新数组 - */ - public void resetUpdateArray() { - mUpdateArray = null; - } -} diff --git a/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java b/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java deleted file mode 100644 index 09c7b79..0000000 --- a/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java +++ /dev/null @@ -1,944 +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; - - -/** - * GTaskManager是GTask同步模块的核心管理类,负责协调本地笔记与Google Tasks服务器之间的同步 - *- * 该类采用单例模式,提供以下主要功能: - * 1. 管理同步状态和进度 - * 2. 初始化远程任务列表 - * 3. 同步本地和远程内容(文件夹和笔记) - * 4. 处理同步冲突和错误 - *
- */ -public class GTaskManager { - private static final String TAG = GTaskManager.class.getSimpleName(); - - /** - * 同步成功状态 - */ - public static final int STATE_SUCCESS = 0; - - /** - * 网络错误状态 - */ - public static final int STATE_NETWORK_ERROR = 1; - - /** - * 内部错误状态 - */ - public static final int STATE_INTERNAL_ERROR = 2; - - /** - * 同步进行中状态 - */ - public static final int STATE_SYNC_IN_PROGRESS = 3; - - /** - * 同步已取消状态 - */ - public static final int STATE_SYNC_CANCELLED = 4; - - /** - * GTaskManager的单例实例 - */ - private static GTaskManager mInstance = null; - - /** - * 用于Google登录的Activity实例 - */ - private Activity mActivity; - - /** - * 应用上下文 - */ - private Context mContext; - - /** - * 内容解析器,用于访问本地数据库 - */ - private ContentResolver mContentResolver; - - /** - * 同步状态标志,表示是否正在进行同步 - */ - private boolean mSyncing; - - /** - * 取消标志,表示同步是否已被取消 - */ - private boolean mCancelled; - - /** - * 远程任务列表的HashMap,键为任务列表的GID - */ - private HashMap- * 该服务提供了以下主要功能: - * 1. 启动GTask同步操作 - * 2. 取消正在进行的同步操作 - * 3. 通过广播通知同步状态和进度 - *
- */ -public class GTaskSyncService extends Service { - /** - * 同步操作类型的Intent参数名称 - */ - public final static String ACTION_STRING_NAME = "sync_action_type"; - - /** - * 启动同步操作的常量 - */ - public final static int ACTION_START_SYNC = 0; - - /** - * 取消同步操作的常量 - */ - public final static int ACTION_CANCEL_SYNC = 1; - - /** - * 无效操作的常量 - */ - public final static int ACTION_INVALID = 2; - - /** - * GTask同步服务广播的Intent名称 - */ - 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(); - 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; - } - return super.onStartCommand(intent, flags, startId); - } - - @Override - public void onLowMemory() { - if (mSyncTask != null) { - mSyncTask.cancelSync(); - } - } - - @Override - public IBinder onBind(Intent intent) { - return null; - } - - /** - * 发送同步状态广播 - * @param msg 同步进度消息 - */ - public void sendBroadcast(String msg) { - mSyncProgress = msg; - Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); - intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); - intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); - sendBroadcast(intent); - } - - /** - * 启动GTask同步服务 - * @param activity 调用该方法的Activity实例 - */ - public static void startSync(Activity activity) { - GTaskManager.getInstance().setActivityContext(activity); - Intent intent = new Intent(activity, GTaskSyncService.class); - intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); - activity.startService(intent); - } - - /** - * 取消GTask同步服务 - * @param context 调用该方法的上下文 - */ - public static void cancelSync(Context context) { - Intent intent = new Intent(context, GTaskSyncService.class); - intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); - context.startService(intent); - } - - /** - * 检查是否正在进行同步 - * @return 如果正在同步返回true,否则返回false - */ - public static boolean isSyncing() { - return mSyncTask != null; - } - - /** - * 获取当前同步进度信息 - * @return 当前同步进度字符串 - */ - public static String getProgressString() { - return mSyncProgress; - } -} diff --git a/src/main/java/net/micode/notes/model/Note.java b/src/main/java/net/micode/notes/model/Note.java deleted file mode 100644 index 44935dd..0000000 --- a/src/main/java/net/micode/notes/model/Note.java +++ /dev/null @@ -1,430 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.model; -import android.content.ContentProviderOperation; -import android.content.ContentProviderResult; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.content.OperationApplicationException; -import android.net.Uri; -import android.os.RemoteException; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.CallNote; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.data.Notes.TextNote; - -import java.util.ArrayList; - - -/** - * 笔记核心数据模型类,负责笔记的创建、更新和同步操作。 - *- * 该类是笔记应用的核心数据模型,提供了笔记的创建、更新和同步功能, - * 支持文本笔记和通话笔记两种类型,并通过ContentResolver与数据库进行交互。 - *
- */ -public class Note { - /** - * 用于存储笔记基本属性的变更值 - */ - private ContentValues mNoteDiffValues; - - /** - * 用于存储笔记具体数据(文本或通话数据) - */ - private NoteData mNoteData; - - /** - * 日志标签 - */ - private static final String TAG = Note.class.getSimpleName(); - /** - * 创建新笔记并返回其ID - *- * 在数据库中创建一个新的笔记记录,并返回生成的笔记ID。 - * 新笔记将包含默认的创建时间、修改时间、类型等信息。 - *
- * - * @param context 应用上下文,用于获取ContentResolver - * @param folderId 笔记所属文件夹ID - * @return 新创建的笔记ID - */ - public static synchronized long getNewNoteId(Context context, long folderId) { - // Create a new note in the database - ContentValues values = new ContentValues(); - long createdTime = System.currentTimeMillis(); - values.put(NoteColumns.CREATED_DATE, createdTime); - values.put(NoteColumns.MODIFIED_DATE, createdTime); - values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); - values.put(NoteColumns.LOCAL_MODIFIED, 1); - values.put(NoteColumns.PARENT_ID, folderId); - Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); - - long noteId = 0; - try { - noteId = Long.valueOf(uri.getPathSegments().get(1)); - } catch (NumberFormatException e) { - Log.e(TAG, "Get note id error :" + e.toString()); - noteId = 0; - } - if (noteId == -1) { - throw new IllegalStateException("Wrong note id:" + noteId); - } - return noteId; - } - - /** - * 构造方法,初始化笔记数据模型 - */ - public Note() { - mNoteDiffValues = new ContentValues(); - mNoteData = new NoteData(); - } - - /** - * 设置笔记的基本属性值 - *- * 更新笔记的基本属性,并标记为本地修改状态,同时更新修改时间。 - *
- * - * @param key 属性键名,对应NoteColumns中的字段名 - * @param value 属性值 - */ - public void setNoteValue(String key, String value) { - mNoteDiffValues.put(key, value); - mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); - mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); - } - - /** - * 设置笔记文本数据 - *- * 更新笔记的文本内容数据,并标记为本地修改状态。 - *
- * - * @param key 文本数据键名,对应TextNote中的字段名 - * @param value 文本数据值 - */ - public void setTextData(String key, String value) { - mNoteData.setTextData(key, value); - } - - /** - * 设置文本数据ID - *- * 设置与当前笔记关联的文本数据记录ID。 - *
- * - * @param id 文本数据ID - */ - public void setTextDataId(long id) { - mNoteData.setTextDataId(id); - } - - /** - * 获取文本数据ID - *- * 获取与当前笔记关联的文本数据记录ID。 - *
- * - * @return 文本数据ID - */ - public long getTextDataId() { - return mNoteData.mTextDataId; - } - - /** - * 设置通话数据ID - *- * 设置与当前笔记关联的通话数据记录ID。 - *
- * - * @param id 通话数据ID - */ - public void setCallDataId(long id) { - mNoteData.setCallDataId(id); - } - - /** - * 设置通话数据 - *- * 更新笔记的通话内容数据,并标记为本地修改状态。 - *
- * - * @param key 通话数据键名,对应CallNote中的字段名 - * @param value 通话数据值 - */ - public void setCallData(String key, String value) { - mNoteData.setCallData(key, value); - } - - /** - * 检查笔记是否在本地被修改 - *- * 检查笔记的基本属性或具体数据是否在本地被修改过。 - *
- * - * @return 如果有本地修改则返回true,否则返回false - */ - public boolean isLocalModified() { - return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); - } - - /** - * 执行笔记同步操作,将本地修改提交到数据库 - *- * 将本地对笔记的修改同步到数据库中,包括基本属性和具体数据的更新。 - * 如果同步失败,会记录错误日志但仍尝试完成数据更新。 - *
- * - * @param context 应用上下文,用于获取ContentResolver - * @param noteId 笔记ID - * @return 同步成功返回true,失败返回false - */ - public boolean syncNote(Context context, long noteId) { - if (noteId <= 0) { - throw new IllegalArgumentException("Wrong note id:" + noteId); - } - - if (!isLocalModified()) { - return true; - } - - /** - * 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 - */ - 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)) { - return false; - } - - return true; - } - - /** - * 笔记数据内部类,负责管理笔记的文本和通话数据。 - *- * 该内部类封装了笔记的具体内容数据,包括文本笔记和通话笔记, - * 并提供了数据的设置和持久化方法。 - *
- */ - private class NoteData { - /** - * 文本数据ID - */ - private long mTextDataId; - - /** - * 文本数据内容 - */ - private ContentValues mTextDataValues; - - /** - * 通话数据ID - */ - private long mCallDataId; - - /** - * 通话数据内容 - */ - private ContentValues mCallDataValues; - - /** - * 日志标签 - */ - private static final String TAG = "NoteData"; - - /** - * 构造方法,初始化笔记数据 - */ - public NoteData() { - mTextDataValues = new ContentValues(); - mCallDataValues = new ContentValues(); - mTextDataId = 0; - mCallDataId = 0; - } - - /** - * 检查笔记数据是否在本地被修改 - *- * 检查文本数据或通话数据是否在本地被修改过。 - *
- * - * @return 如果有本地修改则返回true,否则返回false - */ - boolean isLocalModified() { - return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; - } - - /** - * 设置文本数据ID - *- * 设置与当前笔记关联的文本数据记录ID。 - *
- * - * @param id 文本数据ID - */ - void setTextDataId(long id) { - if(id <= 0) { - throw new IllegalArgumentException("Text data id should larger than 0"); - } - mTextDataId = id; - } - - /** - * 设置通话数据ID - *- * 设置与当前笔记关联的通话数据记录ID。 - *
- * - * @param id 通话数据ID - */ - void setCallDataId(long id) { - if (id <= 0) { - throw new IllegalArgumentException("Call data id should larger than 0"); - } - mCallDataId = id; - } - - /** - * 设置通话数据 - *- * 更新笔记的通话内容数据,并标记为本地修改状态。 - *
- * - * @param key 通话数据键名,对应CallNote中的字段名 - * @param value 通话数据值 - */ - void setCallData(String key, String value) { - mCallDataValues.put(key, value); - mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); - mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); - } - - /** - * 设置文本数据 - *- * 更新笔记的文本内容数据,并标记为本地修改状态。 - *
- * - * @param key 文本数据键名,对应TextNote中的字段名 - * @param value 文本数据值 - */ - void setTextData(String key, String value) { - mTextDataValues.put(key, value); - mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); - mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); - } - - /** - * 将笔记数据推送到ContentResolver进行持久化 - *- * 将本地修改的文本数据或通话数据持久化到数据库中。 - * 如果数据ID为0,则执行插入操作;否则执行更新操作。 - *
- * - * @param context 应用上下文,用于获取ContentResolver - * @param noteId 笔记ID - * @return 成功返回笔记URI,失败返回null - */ - Uri pushIntoContentResolver(Context context, long noteId) { - /** - * Check for safety - */ - if (noteId <= 0) { - throw new IllegalArgumentException("Wrong note id:" + noteId); - } - - ArrayList- * 该类采用单例模式实现,提供了将笔记内容导出为用户可读文本格式的功能, - * 支持将不同文件夹的笔记分类导出,并处理SD卡状态检查和文件生成等操作。 - *
- */ -public class BackupUtils { - /** - * 日志标签 - */ - private static final String TAG = BackupUtils.class.getSimpleName(); - /** - * 单例实例 - */ - private static BackupUtils sInstance; - - /** - * 获取BackupUtils的单例实例 - *- * 如果实例不存在,则创建一个新实例并返回;否则返回已存在的实例。 - *
- * - * @param context 应用上下文 - * @return BackupUtils的单例实例 - */ - public static synchronized BackupUtils getInstance(Context context) { - if (sInstance == null) { - sInstance = new BackupUtils(context); - } - return sInstance; - } - - /** - * 备份或恢复操作的状态常量 - *- * 这些状态常量用于表示备份或恢复操作的执行结果和状态。 - *
- */ - /** - * SD卡未挂载状态 - */ - public static final int STATE_SD_CARD_UNMOUONTED = 0; - - /** - * 备份文件不存在状态 - */ - public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; - - /** - * 数据格式损坏状态,可能被其他程序修改 - */ - public static final int STATE_DATA_DESTROIED = 2; - - /** - * 运行时异常导致备份或恢复失败状态 - */ - public static final int STATE_SYSTEM_ERROR = 3; - - /** - * 备份或恢复成功状态 - */ - public static final int STATE_SUCCESS = 4; - - /** - * 文本导出实例,负责实际的文本导出操作 - */ - private TextExport mTextExport; - - /** - * 私有构造方法,初始化BackupUtils实例 - *- * 创建TextExport实例用于文本导出操作。 - *
- * - * @param context 应用上下文 - */ - private BackupUtils(Context context) { - mTextExport = new TextExport(context); - } - - /** - * 检查外部存储是否可用 - *- * 判断SD卡是否已挂载并可读写。 - *
- * - * @return 如果外部存储可用返回true,否则返回false - */ - private static boolean externalStorageAvailable() { - return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); - } - - /** - * 将笔记导出为文本文件 - *- * 调用内部TextExport实例的exportToText方法执行实际导出操作。 - *
- * - * @return 导出操作的状态码,可能的值为STATE_SD_CARD_UNMOUONTED、STATE_SYSTEM_ERROR或STATE_SUCCESS - */ - public int exportToText() { - return mTextExport.exportToText(); - } - - /** - * 获取导出的文本文件名 - *- * 返回最近一次导出操作生成的文本文件名。 - *
- * - * @return 导出的文本文件名 - */ - public String getExportedTextFileName() { - return mTextExport.mFileName; - } - - /** - * 获取导出的文本文件目录 - *- * 返回导出文本文件的存储目录路径。 - *
- * - * @return 导出的文本文件目录路径 - */ - public String getExportedTextFileDir() { - return mTextExport.mFileDirectory; - } - - /** - * 文本导出内部类,负责实际的笔记文本导出操作。 - *- * 该内部类实现了将笔记内容导出为用户可读文本格式的功能, - * 支持按文件夹分类导出,并处理文件生成和内容格式化等操作。 - *
- */ - private static class TextExport { - private static final String[] NOTE_PROJECTION = { - NoteColumns.ID, - NoteColumns.MODIFIED_DATE, - NoteColumns.SNIPPET, - NoteColumns.TYPE - }; - - private static final int NOTE_COLUMN_ID = 0; - - private static final int NOTE_COLUMN_MODIFIED_DATE = 1; - - private static final int NOTE_COLUMN_SNIPPET = 2; - - private static final String[] DATA_PROJECTION = { - DataColumns.CONTENT, - DataColumns.MIME_TYPE, - DataColumns.DATA1, - DataColumns.DATA2, - DataColumns.DATA3, - DataColumns.DATA4, - }; - - private static final int DATA_COLUMN_CONTENT = 0; - - private static final int DATA_COLUMN_MIME_TYPE = 1; - - private static final int DATA_COLUMN_CALL_DATE = 2; - - private static final int DATA_COLUMN_PHONE_NUMBER = 4; - - /** - * 文本格式化字符串数组,从资源文件中加载 - */ - private final String [] TEXT_FORMAT; - private static final int FORMAT_FOLDER_NAME = 0; - private static final int FORMAT_NOTE_DATE = 1; - private static final int FORMAT_NOTE_CONTENT = 2; - - /** - * 应用上下文 - */ - private Context mContext; - /** - * 导出的文件名 - */ - private String mFileName; - /** - * 导出的文件目录 - */ - private String mFileDirectory; - - /** - * 构造方法,初始化TextExport实例 - *- * 从资源文件中加载文本格式化字符串,并初始化上下文和文件信息。 - *
- * - * @param context 应用上下文 - */ - public TextExport(Context context) { - TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); - mContext = context; - mFileName = ""; - mFileDirectory = ""; - } - - /** - * 获取指定ID的文本格式化字符串 - *- * 从TEXT_FORMAT数组中获取指定索引的格式化字符串。 - *
- * - * @param id 格式化字符串的索引 - * @return 对应的格式化字符串 - */ - private String getFormat(int id) { - return TEXT_FORMAT[id]; - } - - /** - * 将指定文件夹的笔记导出为文本 - *- * 查询并导出指定文件夹下的所有笔记,包括每个笔记的修改日期和内容。 - *
- * - * @param folderId 文件夹ID - * @param ps 输出流,用于写入导出的文本内容 - */ - private void exportFolderToText(String folderId, PrintStream ps) { - // Query notes belong to this folder - Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, - NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { - folderId - }, null); - - if (notesCursor != null) { - if (notesCursor.moveToFirst()) { - do { - // Print note's last modified date - ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( - mContext.getString(R.string.format_datetime_mdhm), - notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); - // Query data belong to this note - String noteId = notesCursor.getString(NOTE_COLUMN_ID); - exportNoteToText(noteId, ps); - } while (notesCursor.moveToNext()); - } - notesCursor.close(); - } - } - - /** - * 将指定笔记导出到打印流 - *- * 查询并导出指定笔记的详细内容,区分文本笔记和通话笔记的不同格式。 - *
- * - * @param noteId 笔记ID - * @param ps 打印流,用于写入导出的笔记内容 - */ - private void exportNoteToText(String noteId, PrintStream ps) { - Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, - DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { - noteId - }, null); - - if (dataCursor != null) { - if (dataCursor.moveToFirst()) { - do { - String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); - if (DataConstants.CALL_NOTE.equals(mimeType)) { - // Print phone number - String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); - long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); - String location = dataCursor.getString(DATA_COLUMN_CONTENT); - - if (!TextUtils.isEmpty(phoneNumber)) { - ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), - phoneNumber)); - } - // Print call date - ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat - .format(mContext.getString(R.string.format_datetime_mdhm), - callDate))); - // Print call attachment location - if (!TextUtils.isEmpty(location)) { - ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), - location)); - } - } else if (DataConstants.NOTE.equals(mimeType)) { - String content = dataCursor.getString(DATA_COLUMN_CONTENT); - if (!TextUtils.isEmpty(content)) { - ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), - content)); - } - } - } while (dataCursor.moveToNext()); - } - dataCursor.close(); - } - // print a line separator between note - try { - ps.write(new byte[] { - Character.LINE_SEPARATOR, Character.LETTER_NUMBER - }); - } catch (IOException e) { - Log.e(TAG, e.toString()); - } - } - - /** - * 将笔记导出为用户可读的文本格式 - *- * 检查SD卡状态,创建输出文件,然后按文件夹分类导出所有笔记内容。 - *
- * - * @return 导出操作的状态码,可能的值为STATE_SD_CARD_UNMOUONTED、STATE_SYSTEM_ERROR或STATE_SUCCESS - */ - public int exportToText() { - if (!externalStorageAvailable()) { - Log.d(TAG, "Media was not mounted"); - return STATE_SD_CARD_UNMOUONTED; - } - - PrintStream ps = getExportToTextPrintStream(); - if (ps == null) { - Log.e(TAG, "get print stream error"); - return STATE_SYSTEM_ERROR; - } - // First export folder and its notes - Cursor folderCursor = mContext.getContentResolver().query( - Notes.CONTENT_NOTE_URI, - NOTE_PROJECTION, - "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " - + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " - + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null); - - if (folderCursor != null) { - if (folderCursor.moveToFirst()) { - do { - // Print folder's name - String folderName = ""; - if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { - folderName = mContext.getString(R.string.call_record_folder_name); - } else { - folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); - } - if (!TextUtils.isEmpty(folderName)) { - ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); - } - String folderId = folderCursor.getString(NOTE_COLUMN_ID); - exportFolderToText(folderId, ps); - } while (folderCursor.moveToNext()); - } - folderCursor.close(); - } - - // Export notes in root's folder - Cursor noteCursor = mContext.getContentResolver().query( - Notes.CONTENT_NOTE_URI, - NOTE_PROJECTION, - NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID - + "=0", null, null); - - if (noteCursor != null) { - if (noteCursor.moveToFirst()) { - do { - ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( - mContext.getString(R.string.format_datetime_mdhm), - noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); - // Query data belong to this note - String noteId = noteCursor.getString(NOTE_COLUMN_ID); - exportNoteToText(noteId, ps); - } while (noteCursor.moveToNext()); - } - noteCursor.close(); - } - ps.close(); - - return STATE_SUCCESS; - } - - /** - * 获取用于导出文本的打印流 - *- * 创建并返回指向导出文本文件的打印流,用于写入导出的笔记内容。 - *
- * - * @return 指向导出文本文件的打印流,如果创建失败返回null - */ - private PrintStream getExportToTextPrintStream() { - File file = generateFileMountedOnSDcard(mContext, R.string.file_path, - R.string.file_name_txt_format); - if (file == null) { - Log.e(TAG, "create file to exported failed"); - return null; - } - mFileName = file.getName(); - mFileDirectory = mContext.getString(R.string.file_path); - PrintStream ps = null; - try { - FileOutputStream fos = new FileOutputStream(file); - ps = new PrintStream(fos); - } catch (FileNotFoundException e) { - e.printStackTrace(); - return null; - } catch (NullPointerException e) { - e.printStackTrace(); - return null; - } - return ps; - } - } - - /** - * 在SD卡上生成用于存储导入数据的文本文件 - *- * 根据指定的文件路径和文件名格式,在SD卡上创建相应的目录和文件。 - *
- * - * @param context 应用上下文 - * @param filePathResId 文件路径资源ID - * @param fileNameFormatResId 文件名格式资源ID - * @return 创建的文件对象,如果创建失败返回null - */ - private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { - StringBuilder sb = new StringBuilder(); - sb.append(Environment.getExternalStorageDirectory()); - sb.append(context.getString(filePathResId)); - File filedir = new File(sb.toString()); - sb.append(context.getString( - fileNameFormatResId, - DateFormat.format(context.getString(R.string.format_date_ymd), - System.currentTimeMillis()))); - File file = new File(sb.toString()); - - try { - if (!filedir.exists()) { - filedir.mkdir(); - } - if (!file.exists()) { - file.createNewFile(); - } - return file; - } catch (SecurityException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return null; - } -} - - diff --git a/src/main/java/net/micode/notes/tool/GTaskStringUtils.java b/src/main/java/net/micode/notes/tool/GTaskStringUtils.java deleted file mode 100644 index e9e7aab..0000000 --- a/src/main/java/net/micode/notes/tool/GTaskStringUtils.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.tool; - -/** - * GTask字符串常量工具类,定义了与GTask服务交互时使用的各种JSON字段名和文件夹名称。 - *- * 该类包含了与Google任务服务(GTask)进行JSON数据交换时所需的所有字符串常量, - * 包括动作类型、实体类型、字段名称以及文件夹命名规则等。 - *
- */ -public class GTaskStringUtils { - - /** 动作ID字段名 */ - public final static String GTASK_JSON_ACTION_ID = "action_id"; - - /** 动作列表字段名 */ - public final static String GTASK_JSON_ACTION_LIST = "action_list"; - - /** 动作类型字段名 */ - public final static String GTASK_JSON_ACTION_TYPE = "action_type"; - - /** 创建动作类型 */ - public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; - - /** 获取所有数据动作类型 */ - public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; - - /** 移动动作类型 */ - public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; - - /** 更新动作类型 */ - public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; - - /** 创建者ID字段名 */ - public final static String GTASK_JSON_CREATOR_ID = "creator_id"; - - /** 子实体字段名 */ - public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; - - /** 客户端版本字段名 */ - public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; - - /** 完成状态字段名 */ - public final static String GTASK_JSON_COMPLETED = "completed"; - - /** 当前列表ID字段名 */ - public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; - - /** 默认列表ID字段名 */ - public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; - - /** 删除状态字段名 */ - public final static String GTASK_JSON_DELETED = "deleted"; - - /** 目标列表字段名 */ - public final static String GTASK_JSON_DEST_LIST = "dest_list"; - - /** 目标父级字段名 */ - public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; - - /** 目标父级类型字段名 */ - public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; - - /** 实体增量字段名 */ - public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; - - /** 实体类型字段名 */ - public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; - - /** 获取已删除数据字段名 */ - public final static String GTASK_JSON_GET_DELETED = "get_deleted"; - - /** ID字段名 */ - public final static String GTASK_JSON_ID = "id"; - - /** 索引字段名 */ - public final static String GTASK_JSON_INDEX = "index"; - - /** 最后修改时间字段名 */ - public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; - - /** 最新同步点字段名 */ - public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; - - /** 列表ID字段名 */ - public final static String GTASK_JSON_LIST_ID = "list_id"; - - /** 列表集合字段名 */ - public final static String GTASK_JSON_LISTS = "lists"; - - /** 名称字段名 */ - public final static String GTASK_JSON_NAME = "name"; - - /** 新ID字段名 */ - public final static String GTASK_JSON_NEW_ID = "new_id"; - - /** 笔记字段名 */ - public final static String GTASK_JSON_NOTES = "notes"; - - /** 父级ID字段名 */ - public final static String GTASK_JSON_PARENT_ID = "parent_id"; - - /** 前一个兄弟节点ID字段名 */ - public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; - - /** 结果集合字段名 */ - public final static String GTASK_JSON_RESULTS = "results"; - - /** 源列表字段名 */ - public final static String GTASK_JSON_SOURCE_LIST = "source_list"; - - /** 任务集合字段名 */ - public final static String GTASK_JSON_TASKS = "tasks"; - - /** 类型字段名 */ - public final static String GTASK_JSON_TYPE = "type"; - - /** 分组类型 */ - public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; - - /** 任务类型 */ - public final static String GTASK_JSON_TYPE_TASK = "TASK"; - - /** 用户字段名 */ - public final static String GTASK_JSON_USER = "user"; - - /** MIUI笔记文件夹前缀 */ - public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; - - /** 默认文件夹名称 */ - public final static String FOLDER_DEFAULT = "Default"; - - /** 通话笔记文件夹名称 */ - public final static String FOLDER_CALL_NOTE = "Call_Note"; - - /** 元数据文件夹名称 */ - public final static String FOLDER_META = "METADATA"; - - /** GTask ID元数据头 */ - public final static String META_HEAD_GTASK_ID = "meta_gid"; - - /** 笔记元数据头 */ - public final static String META_HEAD_NOTE = "meta_note"; - - /** 数据元数据头 */ - public final static String META_HEAD_DATA = "meta_data"; - - /** 元数据笔记名称 */ - public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; - -} diff --git a/src/main/java/net/micode/notes/tool/ResourceParser.java b/src/main/java/net/micode/notes/tool/ResourceParser.java deleted file mode 100644 index 1c3c73a..0000000 --- a/src/main/java/net/micode/notes/tool/ResourceParser.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.tool; - -import android.content.Context; -import android.preference.PreferenceManager; - -import net.micode.notes.R; -import net.micode.notes.ui.NotesPreferenceActivity; - -/** - * 资源解析工具类,管理笔记应用中使用的各种资源配置和常量。 - *- * 该类包含了笔记的背景颜色、字体大小等常量定义,以及管理笔记背景、 - * 列表项背景、小部件背景和文本外观等资源的内部类。 - *
- */ -public class ResourceParser { - - /** 黄色背景ID */ - public static final int YELLOW = 0; - /** 蓝色背景ID */ - public static final int BLUE = 1; - /** 白色背景ID */ - public static final int WHITE = 2; - /** 绿色背景ID */ - public static final int GREEN = 3; - /** 红色背景ID */ - public static final int RED = 4; - - /** 默认背景颜色ID */ - public static final int BG_DEFAULT_COLOR = YELLOW; - - /** 小字体大小ID */ - public static final int TEXT_SMALL = 0; - /** 中字体大小ID */ - public static final int TEXT_MEDIUM = 1; - /** 大字体大小ID */ - public static final int TEXT_LARGE = 2; - /** 超大字体大小ID */ - public static final int TEXT_SUPER = 3; - - /** 默认字体大小ID */ - public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; - - /** - * 笔记背景资源管理类,提供笔记编辑界面的背景和标题背景资源。 - */ - public static class NoteBgResources { - /** 笔记编辑背景资源数组 */ - private final static int [] BG_EDIT_RESOURCES = new int [] { - R.drawable.edit_yellow, - R.drawable.edit_blue, - R.drawable.edit_white, - R.drawable.edit_green, - R.drawable.edit_red - }; - - /** 笔记编辑标题背景资源数组 */ - private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] { - R.drawable.edit_title_yellow, - R.drawable.edit_title_blue, - R.drawable.edit_title_white, - R.drawable.edit_title_green, - R.drawable.edit_title_red - }; - - /** - * 获取笔记背景资源ID - * - * @param id 背景颜色ID - * @return 对应的背景资源ID - */ - public static int getNoteBgResource(int id) { - return BG_EDIT_RESOURCES[id]; - } - - /** - * 获取笔记标题背景资源ID - * - * @param id 背景颜色ID - * @return 对应的标题背景资源ID - */ - public static int getNoteTitleBgResource(int id) { - return BG_EDIT_TITLE_RESOURCES[id]; - } - } - - /** - * 获取默认的笔记背景颜色ID - *- * 根据用户设置决定返回固定默认颜色还是随机颜色。 - *
- * - * @param context 上下文对象 - * @return 默认的背景颜色ID - */ - public static int getDefaultBgId(Context context) { - if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( - NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { - return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length); - } else { - return BG_DEFAULT_COLOR; - } - } - - /** - * 笔记列表项背景资源管理类,提供笔记列表中不同位置项的背景资源。 - */ - public static class NoteItemBgResources { - /** 列表第一项背景资源数组 */ - private final static int [] BG_FIRST_RESOURCES = new int [] { - R.drawable.list_yellow_up, - R.drawable.list_blue_up, - R.drawable.list_white_up, - R.drawable.list_green_up, - R.drawable.list_red_up - }; - - /** 列表中间项背景资源数组 */ - private final static int [] BG_NORMAL_RESOURCES = new int [] { - R.drawable.list_yellow_middle, - R.drawable.list_blue_middle, - R.drawable.list_white_middle, - R.drawable.list_green_middle, - R.drawable.list_red_middle - }; - - /** 列表最后一项背景资源数组 */ - private final static int [] BG_LAST_RESOURCES = new int [] { - R.drawable.list_yellow_down, - R.drawable.list_blue_down, - R.drawable.list_white_down, - R.drawable.list_green_down, - R.drawable.list_red_down, - }; - - /** 列表单独项背景资源数组 */ - private final static int [] BG_SINGLE_RESOURCES = new int [] { - R.drawable.list_yellow_single, - R.drawable.list_blue_single, - R.drawable.list_white_single, - R.drawable.list_green_single, - R.drawable.list_red_single - }; - - /** - * 获取列表第一项背景资源ID - * - * @param id 背景颜色ID - * @return 对应的第一项背景资源ID - */ - public static int getNoteBgFirstRes(int id) { - return BG_FIRST_RESOURCES[id]; - } - - /** - * 获取列表最后一项背景资源ID - * - * @param id 背景颜色ID - * @return 对应的最后一项背景资源ID - */ - public static int getNoteBgLastRes(int id) { - return BG_LAST_RESOURCES[id]; - } - - /** - * 获取列表单独项背景资源ID - * - * @param id 背景颜色ID - * @return 对应的单独项背景资源ID - */ - public static int getNoteBgSingleRes(int id) { - return BG_SINGLE_RESOURCES[id]; - } - - /** - * 获取列表中间项背景资源ID - * - * @param id 背景颜色ID - * @return 对应的中间项背景资源ID - */ - public static int getNoteBgNormalRes(int id) { - return BG_NORMAL_RESOURCES[id]; - } - - /** - * 获取文件夹背景资源ID - * - * @return 文件夹背景资源ID - */ - public static int getFolderBgRes() { - return R.drawable.list_folder; - } - } - - /** - * 小部件背景资源管理类,提供不同尺寸小部件的背景资源。 - */ - public static class WidgetBgResources { - /** 2x尺寸小部件背景资源数组 */ - private final static int [] BG_2X_RESOURCES = new int [] { - R.drawable.widget_2x_yellow, - R.drawable.widget_2x_blue, - R.drawable.widget_2x_white, - R.drawable.widget_2x_green, - R.drawable.widget_2x_red, - }; - - /** - * 获取2x尺寸小部件背景资源ID - * - * @param id 背景颜色ID - * @return 对应的2x尺寸小部件背景资源ID - */ - public static int getWidget2xBgResource(int id) { - return BG_2X_RESOURCES[id]; - } - - /** 4x尺寸小部件背景资源数组 */ - private final static int [] BG_4X_RESOURCES = new int [] { - R.drawable.widget_4x_yellow, - R.drawable.widget_4x_blue, - R.drawable.widget_4x_white, - R.drawable.widget_4x_green, - R.drawable.widget_4x_red - }; - - /** - * 获取4x尺寸小部件背景资源ID - * - * @param id 背景颜色ID - * @return 对应的4x尺寸小部件背景资源ID - */ - public static int getWidget4xBgResource(int id) { - return BG_4X_RESOURCES[id]; - } - } - - /** - * 文本外观资源管理类,提供不同字体大小的文本外观资源。 - */ - public static class TextAppearanceResources { - /** 文本外观资源数组 */ - private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] { - R.style.TextAppearanceNormal, - R.style.TextAppearanceMedium, - R.style.TextAppearanceLarge, - R.style.TextAppearanceSuper - }; - - /** - * 获取文本外观资源ID - *- * 如果ID超出资源数组范围,返回默认字体大小的资源ID。 - *
- * - * @param id 字体大小ID - * @return 对应的文本外观资源ID - */ - public static int getTexAppearanceResource(int id) { - /** - * HACKME: Fix bug of store the resource id in shared preference. - * The id may larger than the length of resources, in this case, - * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} - */ - if (id >= TEXTAPPEARANCE_RESOURCES.length) { - return BG_DEFAULT_FONT_SIZE; - } - return TEXTAPPEARANCE_RESOURCES[id]; - } - - /** - * 获取文本外观资源数组的大小 - * - * @return 文本外观资源数组的大小 - */ - public static int getResourcesSize() { - return TEXTAPPEARANCE_RESOURCES.length; - } - } -} diff --git a/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java b/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java deleted file mode 100644 index fd4c758..0000000 --- a/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.ui; - -import android.app.Activity; -import android.app.AlertDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.DialogInterface.OnClickListener; -import android.content.DialogInterface.OnDismissListener; -import android.content.Intent; -import android.media.AudioManager; -import android.media.MediaPlayer; -import android.media.RingtoneManager; -import android.net.Uri; -import android.os.Bundle; -import android.os.PowerManager; -import android.provider.Settings; -import android.view.Window; -import android.view.WindowManager; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.tool.DataUtils; - -import java.io.IOException; - - -/** - * 闹钟提醒活动类 - *- * 该类用于处理笔记的闹钟提醒功能,当设置了提醒的笔记到达指定时间时, - * 会显示提醒对话框并播放提醒铃声,用户可以选择关闭提醒或进入笔记编辑界面 - *
- */ -public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { - /** - * 触发提醒的笔记ID - */ - private long mNoteId; - - /** - * 笔记内容的摘要,用于在提醒对话框中显示 - */ - private String mSnippet; - - /** - * 提醒对话框中显示的摘要最大长度 - */ - private static final int SNIPPET_PREW_MAX_LEN = 60; - - /** - * 用于播放提醒铃声的媒体播放器 - */ - MediaPlayer mPlayer; - - /** - * 活动创建时的初始化方法 - *- * 该方法完成以下初始化工作: - * 1. 设置窗口特性,隐藏标题栏 - * 2. 配置窗口标志,确保在锁屏状态下也能显示 - * 3. 如果屏幕未开启,则添加额外标志以唤醒屏幕并保持点亮 - * 4. 从Intent中获取笔记ID和摘要信息 - * 5. 创建MediaPlayer实例用于播放提醒铃声 - * 6. 检查笔记是否存在于数据库中 - * 7. 如果笔记存在,则显示提醒对话框并播放提醒铃声 - *
- * @param savedInstanceState 保存的实例状态 - */ - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - 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)); - mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); - mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, - SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) - : mSnippet; - } catch (IllegalArgumentException e) { - e.printStackTrace(); - return; - } - - mPlayer = new MediaPlayer(); - if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { - showActionDialog(); - playAlarmSound(); - } else { - finish(); - } - } - - /** - * 检查屏幕是否处于开启状态 - *- * 该方法通过PowerManager系统服务获取当前屏幕状态 - *
- * @return 如果屏幕处于开启状态则返回true,否则返回false - */ - private boolean isScreenOn() { - PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); - return pm.isScreenOn(); - } - - /** - * 播放提醒铃声 - *- * 该方法完成以下工作: - * 1. 获取系统默认的闹钟铃声URI - * 2. 检查系统的静音模式设置,确定应该使用的音频流类型 - * 3. 根据静音模式设置选择合适的音频流类型 - * 4. 设置MediaPlayer的数据源为获取到的铃声URI - * 5. 准备MediaPlayer并设置为循环播放模式 - * 6. 开始播放提醒铃声 - * 7. 处理可能出现的各种异常 - *
- */ - private void playAlarmSound() { - Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); - - int silentModeStreams = Settings.System.getInt(getContentResolver(), - Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); - - if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { - mPlayer.setAudioStreamType(silentModeStreams); - } else { - mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); - } - try { - mPlayer.setDataSource(this, url); - mPlayer.prepare(); - mPlayer.setLooping(true); - mPlayer.start(); - } catch (IllegalArgumentException e) { - // 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(); - } - } - - /** - * 显示提醒对话框 - *- * 该方法创建并显示一个提醒对话框,包含以下内容: - * 1. 设置对话框标题为应用名称 - * 2. 设置对话框消息为笔记的摘要内容 - * 3. 添加确定按钮,点击后关闭对话框 - * 4. 如果屏幕处于开启状态,添加进入按钮,点击后进入笔记编辑界面 - * 5. 设置对话框关闭监听器,用于在对话框关闭时停止提醒铃声并结束活动 - *
- */ - 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); - } - - /** - * 处理提醒对话框中的按钮点击事件 - *- * 该方法实现了OnClickListener接口,根据点击的按钮执行不同的操作: - * 1. 如果点击的是负按钮(进入按钮),则创建Intent跳转到NoteEditActivity - * 2. 设置Intent的Action为ACTION_VIEW,并将笔记ID作为额外数据传递 - * 3. 启动NoteEditActivity让用户查看或编辑对应的笔记 - * 4. 如果点击的是其他按钮(如确定按钮),则不执行任何额外操作 - *
- * @param dialog 触发点击事件的对话框 - * @param which 点击的按钮ID,对应DialogInterface中的按钮常量 - */ - 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); - startActivity(intent); - break; - default: - break; - } - } - - /** - * 处理提醒对话框关闭事件 - *- * 该方法实现了OnDismissListener接口,当提醒对话框被关闭时(无论点击了哪个按钮或通过其他方式关闭), - * 会停止提醒铃声并结束当前活动 - *
- * @param dialog 被关闭的对话框 - */ - public void onDismiss(DialogInterface dialog) { - stopAlarmSound(); - finish(); - } - - /** - * 停止提醒铃声并释放媒体播放器资源 - *- * 该方法完成以下工作: - * 1. 检查媒体播放器是否存在 - * 2. 如果存在,则停止播放铃声 - * 3. 释放媒体播放器占用的资源 - * 4. 将媒体播放器引用置为null,防止内存泄漏 - *
- */ - private void stopAlarmSound() { - if (mPlayer != null) { - mPlayer.stop(); - mPlayer.release(); - mPlayer = null; - } - } -} diff --git a/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java b/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java deleted file mode 100644 index 4de50d9..0000000 --- a/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.ui; - -import android.app.AlarmManager; -import android.app.PendingIntent; -import android.content.BroadcastReceiver; -import android.content.ContentUris; -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 { - /** - * 闹钟数据查询的投影列数组 - *- * 定义了从数据库查询笔记闹钟数据时需要获取的列,包括笔记ID和闹钟触发日期 - *
- */ - private static final String [] PROJECTION = new String [] { - NoteColumns.ID, - NoteColumns.ALERTED_DATE - }; - - /** - * 查询结果中笔记ID列的索引 - */ - private static final int COLUMN_ID = 0; - - /** - * 查询结果中闹钟触发日期列的索引 - */ - private static final int COLUMN_ALERTED_DATE = 1; - - /** - * 接收广播时调用的方法 - *- * 当系统发送广播时(通常是系统启动完成),该方法会查询所有设置了未来闹钟的笔记, - * 并使用AlarmManager重新注册这些闹钟 - *
- * @param context 上下文对象 - * @param intent 接收到的广播意图 - */ - @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 sender = new Intent(context, AlarmReceiver.class); - sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); - PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); - AlarmManager alermManager = (AlarmManager) - context.getSystemService(Context.ALARM_SERVICE); - alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); - } while (c.moveToNext()); - } - c.close(); - } - } -} diff --git a/src/main/java/net/micode/notes/ui/AlarmReceiver.java b/src/main/java/net/micode/notes/ui/AlarmReceiver.java deleted file mode 100644 index 610716c..0000000 --- a/src/main/java/net/micode/notes/ui/AlarmReceiver.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.ui; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - -/** - * 闹钟触发广播接收器 - *- * 该广播接收器负责处理闹钟触发事件,当闹钟时间到达时,它会启动闹钟提醒活动 - *
- */ -public class AlarmReceiver extends BroadcastReceiver { - /** - * 接收闹钟触发广播时调用的方法 - *- * 当闹钟时间到达时,该方法会启动AlarmAlertActivity来显示闹钟提醒 - *
- * @param context 上下文对象 - * @param intent 接收到的广播意图,包含闹钟相关的笔记信息 - */ - @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/main/java/net/micode/notes/ui/DateTimePicker.java b/src/main/java/net/micode/notes/ui/DateTimePicker.java deleted file mode 100644 index c805b60..0000000 --- a/src/main/java/net/micode/notes/ui/DateTimePicker.java +++ /dev/null @@ -1,646 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.ui; - -import java.text.DateFormatSymbols; -import java.util.Calendar; - -import net.micode.notes.R; - - -import android.content.Context; -import android.text.format.DateFormat; -import android.view.View; -import android.widget.FrameLayout; -import android.widget.NumberPicker; - -/** - * 日期时间选择组件 - *- * 该类是一个自定义的日期时间选择组件,继承自FrameLayout,用于在小米便签应用中 - * 提供直观的日期时间选择界面。它支持12/24小时制切换,并通过NumberPicker组件 - * 实现日期、小时、分钟和AM/PM的选择 - *
- */ -public class DateTimePicker extends FrameLayout { - - /** - * 默认启用状态 - */ - private static final boolean DEFAULT_ENABLE_STATE = true; - - /** - * 半天的小时数(12小时) - */ - private static final int HOURS_IN_HALF_DAY = 12; - - /** - * 全天的小时数(24小时) - */ - private static final int HOURS_IN_ALL_DAY = 24; - - /** - * 一周的天数(7天) - */ - 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; - - /** - * 24小时制下小时选择器的最小值 - */ - 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; - - /** - * 12小时制下小时选择器的最小值 - */ - 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; - - /** - * 分钟选择器的最小值 - */ - private static final int MINUT_SPINNER_MIN_VAL = 0; - - /** - * 分钟选择器的最大值 - */ - private static final int MINUT_SPINNER_MAX_VAL = 59; - - /** - * AM/PM选择器的最小值 - */ - private static final int AMPM_SPINNER_MIN_VAL = 0; - - /** - * AM/PM选择器的最大值 - */ - private static final int AMPM_SPINNER_MAX_VAL = 1; - - /** - * 日期选择器组件 - */ - private final NumberPicker mDateSpinner; - - /** - * 小时选择器组件 - */ - private final NumberPicker mHourSpinner; - - /** - * 分钟选择器组件 - */ - private final NumberPicker mMinuteSpinner; - - /** - * AM/PM选择器组件 - */ - private final NumberPicker mAmPmSpinner; - - /** - * 当前选择的日期和时间 - */ - private Calendar mDate; - - /** - * 日期选择器显示的日期值数组 - */ - private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; - - /** - * 是否为上午 - */ - private boolean mIsAm; - - /** - * 是否为24小时制视图 - */ - private boolean mIs24HourView; - - /** - * 组件是否启用 - */ - 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) { - if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { - cal.setTimeInMillis(mDate.getTimeInMillis()); - cal.add(Calendar.DAY_OF_YEAR, 1); - isDateChanged = true; - } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { - cal.setTimeInMillis(mDate.getTimeInMillis()); - cal.add(Calendar.DAY_OF_YEAR, -1); - isDateChanged = true; - } - if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY || - oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { - mIsAm = !mIsAm; - updateAmPmControl(); - } - } else { - if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { - cal.setTimeInMillis(mDate.getTimeInMillis()); - cal.add(Calendar.DAY_OF_YEAR, 1); - isDateChanged = true; - } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { - cal.setTimeInMillis(mDate.getTimeInMillis()); - cal.add(Calendar.DAY_OF_YEAR, -1); - isDateChanged = true; - } - } - int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY); - mDate.set(Calendar.HOUR_OF_DAY, newHour); - onDateTimeChanged(); - if (isDateChanged) { - setCurrentYear(cal.get(Calendar.YEAR)); - setCurrentMonth(cal.get(Calendar.MONTH)); - setCurrentDay(cal.get(Calendar.DAY_OF_MONTH)); - } - } - }; - - 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) { - offset += 1; - } else if (oldVal == minValue && newVal == maxValue) { - offset -= 1; - } - if (offset != 0) { - mDate.add(Calendar.HOUR_OF_DAY, offset); - mHourSpinner.setValue(getCurrentHour()); - updateDateControl(); - int newHour = getCurrentHourOfDay(); - if (newHour >= HOURS_IN_HALF_DAY) { - mIsAm = false; - updateAmPmControl(); - } else { - mIsAm = true; - updateAmPmControl(); - } - } - mDate.set(Calendar.MINUTE, newVal); - onDateTimeChanged(); - } - }; - - private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { - @Override - public void onValueChange(NumberPicker picker, int oldVal, int newVal) { - mIsAm = !mIsAm; - if (mIsAm) { - mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); - } else { - mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); - } - updateAmPmControl(); - onDateTimeChanged(); - } - }; - - /** - * 日期时间变化监听器接口 - *- * 当日期时间选择器的值发生变化时,会通过此接口通知外部 - *
- */ - public interface OnDateTimeChangedListener { - /** - * 日期时间变化时调用的方法 - * @param view 日期时间选择器实例 - * @param year 选择的年份 - * @param month 选择的月份(0-11) - * @param dayOfMonth 选择的日(1-31) - * @param hourOfDay 选择的小时(0-23) - * @param minute 选择的分钟(0-59) - */ - void onDateTimeChanged(DateTimePicker view, int year, int month, - int dayOfMonth, int hourOfDay, int minute); - } - - /** - * 构造函数,使用当前时间初始化日期时间选择器 - * @param context 上下文对象 - */ - public DateTimePicker(Context context) { - this(context, System.currentTimeMillis()); - } - - /** - * 构造函数,使用指定时间初始化日期时间选择器,根据系统设置决定是否使用24小时制 - * @param context 上下文对象 - * @param date 初始日期时间,以毫秒为单位 - */ - public DateTimePicker(Context context, long date) { - this(context, date, DateFormat.is24HourFormat(context)); - } - - /** - * 构造函数,使用指定时间和时间格式初始化日期时间选择器 - * @param context 上下文对象 - * @param date 初始日期时间,以毫秒为单位 - * @param is24HourView 是否使用24小时制 - */ - public DateTimePicker(Context context, long date, boolean is24HourView) { - super(context); - mDate = Calendar.getInstance(); - mInitialising = true; - mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; - inflate(context, R.layout.datetime_picker, this); - - mDateSpinner = (NumberPicker) findViewById(R.id.date); - mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); - mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); - mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); - - mHourSpinner = (NumberPicker) findViewById(R.id.hour); - mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); - mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); - mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL); - mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL); - mMinuteSpinner.setOnLongPressUpdateInterval(100); - mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); - - String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); - mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); - mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); - mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL); - mAmPmSpinner.setDisplayedValues(stringsForAmPm); - mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); - - // update controls to initial state - updateDateControl(); - updateHourControl(); - updateAmPmControl(); - - set24HourView(is24HourView); - - // set to current time - setCurrentDate(date); - - setEnabled(isEnabled()); - - // set the content descriptions - 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 - */ - public int getCurrentHourOfDay() { - return mDate.get(Calendar.HOUR_OF_DAY); - } - - /** - * 获取当前小时 - *- * 根据当前视图模式返回正确的小时值: - * - 24小时制:直接返回当前小时(0-23) - * - 12小时制:返回1-12之间的小时值 - *
- * @return 当前小时值 - */ - private int getCurrentHour() { - if (mIs24HourView){ - return getCurrentHourOfDay(); - } else { - int hour = getCurrentHourOfDay(); - if (hour > HOURS_IN_HALF_DAY) { - return hour - HOURS_IN_HALF_DAY; - } else { - return hour == 0 ? HOURS_IN_HALF_DAY : hour; - } - } - } - - /** - * 设置当前小时(24小时制,范围0-23) - * @param hourOfDay 当前小时值(24小时制) - */ - public void setCurrentHour(int hourOfDay) { - if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { - return; - } - mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); - if (!mIs24HourView) { - if (hourOfDay >= HOURS_IN_HALF_DAY) { - mIsAm = false; - if (hourOfDay > HOURS_IN_HALF_DAY) { - hourOfDay -= HOURS_IN_HALF_DAY; - } - } else { - mIsAm = true; - if (hourOfDay == 0) { - hourOfDay = HOURS_IN_HALF_DAY; - } - } - updateAmPmControl(); - } - mHourSpinner.setValue(hourOfDay); - onDateTimeChanged(); - } - - /** - * 获取当前分钟 - * @return 当前分钟值(0-59) - */ - public int getCurrentMinute() { - return mDate.get(Calendar.MINUTE); - } - - /** - * 设置当前分钟 - * @param minute 当前分钟值(0-59) - */ - public void setCurrentMinute(int minute) { - if (!mInitialising && minute == getCurrentMinute()) { - return; - } - mMinuteSpinner.setValue(minute); - mDate.set(Calendar.MINUTE, minute); - onDateTimeChanged(); - } - - /** - * 获取当前是否为24小时制视图 - * @return true表示为24小时制视图,false表示为12小时制视图 - */ - public boolean is24HourView () { - return mIs24HourView; - } - - /** - * 设置是否使用24小时制或AM/PM模式 - * @param is24HourView true表示使用24小时制,false表示使用AM/PM模式 - */ - public void set24HourView(boolean is24HourView) { - if (mIs24HourView == is24HourView) { - return; - } - mIs24HourView = is24HourView; - mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); - int hour = getCurrentHourOfDay(); - updateHourControl(); - setCurrentHour(hour); - updateAmPmControl(); - } - - /** - * 更新日期控件 - *- * 该方法负责更新日期选择器的显示值,显示当前日期前后几天的日期 - *
- */ - private void updateDateControl() { - Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(mDate.getTimeInMillis()); - cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); - 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); - mDateSpinner.invalidate(); - } - - /** - * 更新AM/PM控件 - *- * 该方法负责根据当前时间和视图模式更新AM/PM选择器的显示 - *
- */ - private void updateAmPmControl() { - if (mIs24HourView) { - mAmPmSpinner.setVisibility(View.GONE); - } else { - int index = mIsAm ? Calendar.AM : Calendar.PM; - 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); - } else { - mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); - mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); - } - } - - /** - * 设置日期时间变化监听器 - * @param callback 日期时间变化时的回调函数,若为null则不执行任何操作 - */ - public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { - mOnDateTimeChangedListener = callback; - } - - /** - * 日期时间变化时调用的方法 - *- * 当日期或时间发生变化时,该方法会通知注册的监听器 - *
- */ - private void onDateTimeChanged() { - if (mOnDateTimeChangedListener != null) { - mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), - getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); - } - } -} diff --git a/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java b/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java deleted file mode 100644 index b9986ac..0000000 --- a/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.ui; - -import java.util.Calendar; - -import net.micode.notes.R; -import net.micode.notes.ui.DateTimePicker; -import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; - -import android.app.AlertDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.DialogInterface.OnClickListener; -import android.text.format.DateFormat; -import android.text.format.DateUtils; - -/** - * 日期时间选择对话框 - *- * 该类是一个封装了DateTimePicker组件的对话框,用于在小米便签应用中 - * 提供一个完整的日期时间选择界面。用户可以通过该对话框选择日期和时间, - * 并在确认后将选择结果返回给调用者 - *
- */ -public class DateTimePickerDialog extends AlertDialog implements OnClickListener { - - /** - * 当前选择的日期和时间 - */ - private Calendar mDate = Calendar.getInstance(); - - /** - * 是否使用24小时制视图 - */ - private boolean mIs24HourView; - - /** - * 日期时间设置监听器,用于通知外部选择结果 - */ - private OnDateTimeSetListener mOnDateTimeSetListener; - - /** - * 日期时间选择器组件 - */ - private DateTimePicker mDateTimePicker; - /** - * 日期时间设置监听器接口 - *- * 当用户在对话框中确认选择日期时间后,会通过此接口通知外部 - *
- */ - public interface OnDateTimeSetListener { - /** - * 日期时间设置完成时调用的方法 - * @param dialog 对话框实例 - * @param date 选择的日期时间,以毫秒为单位 - */ - void OnDateTimeSet(AlertDialog dialog, long date); - } - - /** - * 构造函数,使用指定日期初始化日期时间选择对话框 - * @param context 上下文对象 - * @param date 初始日期时间,以毫秒为单位 - */ - public DateTimePickerDialog(Context context, long date) { - super(context); - mDateTimePicker = new DateTimePicker(context); - setView(mDateTimePicker); - mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { - public void onDateTimeChanged(DateTimePicker view, int year, int month, - int dayOfMonth, int hourOfDay, int minute) { - mDate.set(Calendar.YEAR, year); - mDate.set(Calendar.MONTH, month); - mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); - mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); - mDate.set(Calendar.MINUTE, minute); - updateTitle(mDate.getTimeInMillis()); - } - }); - mDate.setTimeInMillis(date); - mDate.set(Calendar.SECOND, 0); - mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); - setButton(context.getString(R.string.datetime_dialog_ok), this); - setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); - set24HourView(DateFormat.is24HourFormat(this.getContext())); - updateTitle(mDate.getTimeInMillis()); - } - - /** - * 设置是否使用24小时制视图 - * @param is24HourView true表示使用24小时制,false表示使用12小时制 - */ - public void set24HourView(boolean is24HourView) { - mIs24HourView = is24HourView; - } - - /** - * 设置日期时间设置监听器 - * @param callBack 日期时间设置完成时的回调函数 - */ - public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { - mOnDateTimeSetListener = callBack; - } - - /** - * 更新对话框标题 - *- * 该方法根据当前选择的日期时间和视图模式更新对话框标题 - *
- * @param date 当前选择的日期时间,以毫秒为单位 - */ - 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; - setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); - } - - /** - * 点击对话框按钮时调用的方法 - *- * 当用户点击对话框的确定按钮时,会调用该方法,通知注册的监听器 - *
- * @param arg0 对话框实例 - * @param arg1 点击的按钮ID - */ - @Override - 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/main/java/net/micode/notes/ui/DropdownMenu.java b/src/main/java/net/micode/notes/ui/DropdownMenu.java deleted file mode 100644 index 4e58bbb..0000000 --- a/src/main/java/net/micode/notes/ui/DropdownMenu.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.ui; - -import android.content.Context; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.View.OnClickListener; -import android.widget.Button; -import android.widget.PopupMenu; -import android.widget.PopupMenu.OnMenuItemClickListener; - -import net.micode.notes.R; - -/** - * 下拉菜单封装类 - *- * 该类封装了Android的PopupMenu,提供了一个简单的接口来创建和管理下拉菜单 - *
- */ -public class DropdownMenu { - /** - * 触发下拉菜单的按钮 - */ - private Button mButton; - - /** - * 下拉菜单实例 - */ - private PopupMenu mPopupMenu; - - /** - * 菜单对象 - */ - private Menu mMenu; - - /** - * 构造函数,创建一个下拉菜单 - * @param context 上下文对象 - * @param button 触发下拉菜单的按钮 - * @param menuId 菜单资源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(); - } - }); - } - - /** - * 设置下拉菜单项点击监听器 - * @param listener 菜单项点击监听器 - */ - public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { - if (mPopupMenu != null) { - mPopupMenu.setOnMenuItemClickListener(listener); - } - } - - /** - * 查找指定ID的菜单项 - * @param id 菜单项ID - * @return 指定ID的菜单项,若不存在则返回null - */ - public MenuItem findItem(int id) { - return mMenu.findItem(id); - } - - /** - * 设置下拉菜单按钮的标题 - * @param title 按钮标题 - */ - public void setTitle(CharSequence title) { - mButton.setText(title); - } -} diff --git a/src/main/java/net/micode/notes/ui/FoldersListAdapter.java b/src/main/java/net/micode/notes/ui/FoldersListAdapter.java deleted file mode 100644 index 7e05bf2..0000000 --- a/src/main/java/net/micode/notes/ui/FoldersListAdapter.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.ui; - -import android.content.Context; -import android.database.Cursor; -import android.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; - - -/** - * 文件夹列表适配器 - *- * 该类继承自CursorAdapter,用于在小米便签应用中显示文件夹列表 - *
- */ -public class FoldersListAdapter extends CursorAdapter { - /** - * 文件夹数据查询的投影列数组 - *- * 定义了从数据库查询文件夹数据时需要获取的列,包括文件夹ID和名称 - *
- */ - public static final String [] PROJECTION = { - NoteColumns.ID, - NoteColumns.SNIPPET - }; - - /** - * 查询结果中文件夹ID列的索引 - */ - public static final int ID_COLUMN = 0; - - /** - * 查询结果中文件夹名称列的索引 - */ - public static final int NAME_COLUMN = 1; - - /** - * 构造函数,创建文件夹列表适配器 - * @param context 上下文对象 - * @param c 包含文件夹数据的游标 - */ - public FoldersListAdapter(Context context, Cursor c) { - super(context, c); - // TODO Auto-generated constructor stub - } - - /** - * 创建新的列表项视图 - * @param context 上下文对象 - * @param cursor 包含文件夹数据的游标 - * @param parent 父视图组 - * @return 新创建的列表项视图 - */ - @Override - public View newView(Context context, Cursor cursor, ViewGroup parent) { - return new FolderListItem(context); - } - - /** - * 将数据绑定到列表项视图 - * @param view 列表项视图 - * @param context 上下文对象 - * @param cursor 包含文件夹数据的游标 - */ - @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); - } - } - - /** - * 获取指定位置的文件夹名称 - * @param context 上下文对象 - * @param position 列表项位置 - * @return 文件夹名称 - */ - 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; - - /** - * 构造函数,创建文件夹列表项视图 - * @param context 上下文对象 - */ - public FolderListItem(Context context) { - super(context); - inflate(context, R.layout.folder_list_item, this); - mName = (TextView) findViewById(R.id.tv_folder_name); - } - - /** - * 绑定文件夹名称到视图 - * @param name 文件夹名称 - */ - public void bind(String name) { - mName.setText(name); - } - } - -} diff --git a/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java b/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java deleted file mode 100644 index 8fffe80..0000000 --- a/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.widget; -import android.app.PendingIntent; -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.ContentValues; -import android.content.Context; -import android.content.Intent; -import android.database.Cursor; -import android.util.Log; -import android.widget.RemoteViews; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.tool.ResourceParser; -import net.micode.notes.ui.NoteEditActivity; -import net.micode.notes.ui.NotesListActivity; - -/** - * 笔记小组件基类 - *- * 该抽象类为所有笔记小组件提供核心功能,包括小组件数据管理、UI更新、点击事件处理 - * 和小组件删除管理。它支持不同的小组件类型和布局,通过抽象方法让子类实现特定的 - * 布局和资源配置 - *
- */ -public abstract class NoteWidgetProvider extends AppWidgetProvider { - /** - * 小组件数据查询的投影列数组 - *- * 定义了从数据库查询笔记数据时需要获取的列,包括笔记ID、背景颜色ID和摘要内容 - *
- */ - public static final String [] PROJECTION = new String [] { - NoteColumns.ID, - NoteColumns.BG_COLOR_ID, - NoteColumns.SNIPPET - }; - - /** - * 查询结果中ID列的索引 - */ - public static final int COLUMN_ID = 0; - - /** - * 查询结果中背景颜色ID列的索引 - */ - public static final int COLUMN_BG_COLOR_ID = 1; - - /** - * 查询结果中摘要内容列的索引 - */ - public static final int COLUMN_SNIPPET = 2; - - /** - * 日志标签,用于小组件相关的日志输出 - */ - private static final String TAG = "NoteWidgetProvider"; - - /** - * 当小组件被删除时调用的方法 - *- * 该方法将数据库中与被删除小组件关联的笔记的WIDGET_ID字段更新为无效值, - * 解除笔记与已删除小组件的关联关系 - *
- * @param context 上下文对象 - * @param appWidgetIds 被删除的小组件ID数组 - */ - @Override - public void onDeleted(Context context, int[] appWidgetIds) { - ContentValues values = new ContentValues(); - values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); - for (int i = 0; i < appWidgetIds.length; i++) { - context.getContentResolver().update(Notes.CONTENT_NOTE_URI, - values, - NoteColumns.WIDGET_ID + "=?", - new String[] { String.valueOf(appWidgetIds[i])}); - } - } - - /** - * 查询与特定小组件ID关联的笔记信息 - *- * 该方法从数据库中查询与给定小组件ID关联的笔记数据,并排除已删除到回收站的笔记 - *
- * @param context 上下文对象 - * @param widgetId 要查询的小组件ID - * @return 返回包含笔记信息的Cursor对象,使用PROJECTION中定义的列 - */ - private Cursor getNoteWidgetInfo(Context context, int widgetId) { - return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, - PROJECTION, - NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", - new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, - null); - } - - /** - * 更新小组件的UI和数据 - *- * 该方法是update方法的公共保护接口,默认使用非隐私模式更新小组件 - *
- * @param context 上下文对象 - * @param appWidgetManager 小组件管理器 - * @param appWidgetIds 要更新的小组件ID数组 - */ - protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - update(context, appWidgetManager, appWidgetIds, false); - } - - /** - * 更新小组件的UI和数据(私有实现) - *- * 该方法负责实际更新小组件的内容,支持隐私模式和正常模式: - * 1. 查询与小组件关联的笔记信息 - * 2. 根据查询结果设置小组件显示的文本和背景 - * 3. 创建点击小组件时的PendingIntent - * 4. 在隐私模式下显示特定提示文本并跳转到笔记列表 - * 5. 在正常模式下显示笔记内容并支持查看或创建笔记 - *
- * @param context 上下文对象 - * @param appWidgetManager 小组件管理器 - * @param appWidgetIds 要更新的小组件ID数组 - * @param privacyMode 是否处于隐私模式 - */ - private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, - boolean privacyMode) { - for (int i = 0; i < appWidgetIds.length; i++) { - if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { - int bgId = ResourceParser.getDefaultBgId(context); - String snippet = ""; - Intent intent = new Intent(context, NoteEditActivity.class); - intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); - intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); - intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); - - Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]); - if (c != null && c.moveToFirst()) { - if (c.getCount() > 1) { - Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]); - c.close(); - return; - } - snippet = c.getString(COLUMN_SNIPPET); - bgId = c.getInt(COLUMN_BG_COLOR_ID); - intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); - intent.setAction(Intent.ACTION_VIEW); - } else { - snippet = context.getResources().getString(R.string.widget_havenot_content); - intent.setAction(Intent.ACTION_INSERT_OR_EDIT); - } - - if (c != null) { - c.close(); - } - - RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); - rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); - intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); - /** - * Generate the pending intent to start host for the widget - */ - PendingIntent pendingIntent = null; - if (privacyMode) { - rv.setTextViewText(R.id.widget_text, - context.getString(R.string.widget_under_visit_mode)); - pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent( - context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); - } else { - rv.setTextViewText(R.id.widget_text, snippet); - pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, - PendingIntent.FLAG_UPDATE_CURRENT); - } - - rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); - appWidgetManager.updateAppWidget(appWidgetIds[i], rv); - } - } - } - - /** - * 根据背景颜色ID获取对应的背景资源ID - *- * 该方法由子类实现,用于将数据库中的背景颜色ID转换为实际的资源ID - *
- * @param bgId 数据库中的背景颜色ID - * @return 对应的背景资源ID - */ - protected abstract int getBgResourceId(int bgId); - - /** - * 获取小组件的布局ID - *- * 该方法由子类实现,返回特定小组件类型的布局资源ID - *
- * @return 小组件布局资源ID - */ - protected abstract int getLayoutId(); - - /** - * 获取小组件类型 - *- * 该方法由子类实现,返回特定小组件的类型标识 - *
- * @return 小组件类型标识 - */ - protected abstract int getWidgetType(); -} diff --git a/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java b/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java deleted file mode 100644 index 02bd7f1..0000000 --- a/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.widget; - -import android.appwidget.AppWidgetManager; -import android.content.Context; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.tool.ResourceParser; - - -/** - * 2x尺寸的笔记小组件实现类 - *- * 该类继承自NoteWidgetProvider抽象类,实现了2x尺寸笔记小组件的具体功能 - * 包括布局设置、背景资源获取和小组件类型定义 - *
- */ -public class NoteWidgetProvider_2x extends NoteWidgetProvider { - /** - * 更新小组件的UI和数据 - *- * 该方法重写了AppWidgetProvider的onUpdate方法,调用父类的update方法来更新2x尺寸小组件 - *
- * @param context 上下文对象 - * @param appWidgetManager 小组件管理器 - * @param appWidgetIds 要更新的小组件ID数组 - */ - @Override - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - super.update(context, appWidgetManager, appWidgetIds); - } - - /** - * 获取2x尺寸小组件的布局ID - *- * 返回2x尺寸小组件的布局资源ID - *
- * @return 2x小组件布局资源ID - */ - @Override - protected int getLayoutId() { - return R.layout.widget_2x; - } - - /** - * 根据背景颜色ID获取2x小组件对应的背景资源ID - *- * 通过ResourceParser获取2x尺寸小组件的背景资源ID - *
- * @param bgId 数据库中的背景颜色ID - * @return 2x小组件对应的背景资源ID - */ - @Override - protected int getBgResourceId(int bgId) { - return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); - } - - /** - * 获取2x小组件类型 - *- * 返回2x尺寸小组件的类型标识 - *
- * @return 2x小组件类型标识 - */ - @Override - protected int getWidgetType() { - return Notes.TYPE_WIDGET_2X; - } -} diff --git a/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java b/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java deleted file mode 100644 index 6e4a984..0000000 --- a/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.widget; - -import android.appwidget.AppWidgetManager; -import android.content.Context; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.tool.ResourceParser; - - -/** - * 4x尺寸的笔记小组件实现类 - *- * 该类继承自NoteWidgetProvider抽象类,实现了4x尺寸笔记小组件的具体功能 - * 包括布局设置、背景资源获取和小组件类型定义 - *
- */ -public class NoteWidgetProvider_4x extends NoteWidgetProvider { - /** - * 更新小组件的UI和数据 - *- * 该方法重写了AppWidgetProvider的onUpdate方法,调用父类的update方法来更新4x尺寸小组件 - *
- * @param context 上下文对象 - * @param appWidgetManager 小组件管理器 - * @param appWidgetIds 要更新的小组件ID数组 - */ - @Override - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - super.update(context, appWidgetManager, appWidgetIds); - } - - /** - * 获取4x尺寸小组件的布局ID - *- * 返回4x尺寸小组件的布局资源ID - *
- * @return 4x小组件布局资源ID - */ - @Override - protected int getLayoutId() { - return R.layout.widget_4x; - } - - /** - * 根据背景颜色ID获取4x小组件对应的背景资源ID - *- * 通过ResourceParser获取4x尺寸小组件的背景资源ID - *
- * @param bgId 数据库中的背景颜色ID - * @return 4x小组件对应的背景资源ID - */ - @Override - protected int getBgResourceId(int bgId) { - return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); - } - - /** - * 获取4x小组件类型 - *- * 返回4x尺寸小组件的类型标识 - *
- * @return 4x小组件类型标识 - */ - @Override - protected int getWidgetType() { - return Notes.TYPE_WIDGET_4X; - } -} diff --git a/src/main/res/color/primary_text_dark.xml b/src/main/res/color/primary_text_dark.xml deleted file mode 100644 index 7c85459..0000000 --- a/src/main/res/color/primary_text_dark.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - -