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 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/java/net/micode/notes/MainActivity.java b/src/main/java/net/micode/notes/MainActivity.java deleted file mode 100644 index 8091753..0000000 --- a/src/main/java/net/micode/notes/MainActivity.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.micode.notes; - -import android.os.Bundle; - -import androidx.activity.EdgeToEdge; -import androidx.appcompat.app.AppCompatActivity; -import androidx.core.graphics.Insets; -import androidx.core.view.ViewCompat; -import androidx.core.view.WindowInsetsCompat; - -public class MainActivity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - EdgeToEdge.enable(this); - setContentView(R.layout.activity_main); - ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { - Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); - v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); - return insets; - }); - } -} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/data/Contact.java b/src/main/java/net/micode/notes/data/Contact.java deleted file mode 100644 index 6a4f1d5..0000000 --- a/src/main/java/net/micode/notes/data/Contact.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.data; - -import android.content.Context; -import android.database.Cursor; -import android.provider.ContactsContract.CommonDataKinds.Phone; -import android.provider.ContactsContract.Data; -import android.telephony.PhoneNumberUtils; -import android.util.Log; - -import java.util.HashMap; - -/** - * 联系人工具类,用于根据电话号码获取联系人姓名 - *

- * 该类提供了获取联系人信息的静态方法,并使用缓存机制提高查询效率 - *

- */ -public class Contact { - /** - * 联系人缓存,用于存储已查询过的电话号码和对应联系人姓名 - */ - private static HashMap sContactCache; - /** - * 日志标签 - */ - private static final String TAG = "Contact"; - - /** - * 用于查询联系人的选择条件,根据电话号码匹配联系人 - */ - private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER - + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" - + " AND " + Data.RAW_CONTACT_ID + " IN " - + "(SELECT raw_contact_id " - + " FROM phone_lookup" - + " WHERE min_match = '+')"; - - /** - * 根据电话号码获取联系人姓名 - *

- * 该方法会先检查缓存,如果缓存中存在则直接返回,否则查询联系人数据库 - *

- * @param context 上下文对象 - * @param phoneNumber 电话号码 - * @return 联系人姓名,若未找到则返回null - */ - public static String getContact(Context context, String phoneNumber) { - if(sContactCache == null) { - sContactCache = new HashMap(); - } - - if(sContactCache.containsKey(phoneNumber)) { - return sContactCache.get(phoneNumber); - } - - String selection = CALLER_ID_SELECTION.replace("+", - PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); - Cursor cursor = context.getContentResolver().query( - Data.CONTENT_URI, - new String [] { Phone.DISPLAY_NAME }, - selection, - new String[] { phoneNumber }, - null); - - if (cursor != null && cursor.moveToFirst()) { - try { - String name = cursor.getString(0); - sContactCache.put(phoneNumber, name); - return name; - } catch (IndexOutOfBoundsException e) { - Log.e(TAG, " Cursor get string error " + e.toString()); - return null; - } finally { - cursor.close(); - } - } else { - Log.d(TAG, "No contact matched with number:" + phoneNumber); - return null; - } - } -} diff --git a/src/main/java/net/micode/notes/data/Notes.java b/src/main/java/net/micode/notes/data/Notes.java deleted file mode 100644 index 297b7dc..0000000 --- a/src/main/java/net/micode/notes/data/Notes.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.data; - -import android.net.Uri; - -/** - * 便签应用的核心数据模型类,定义了便签系统的常量、URI和数据结构 - *

- * 该类包含了便签应用的核心数据定义,包括便签类型、系统文件夹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"; - - /** - * 便签或文件夹被删除的时间 - *

类型: INTEGER (long)

- *

0表示未被删除,其他值表示删除时间戳

- */ - public static final String DELETED_DATE = "deleted_date"; - } - - 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 4edf21d..0000000 --- a/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java +++ /dev/null @@ -1,533 +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 = 7; - - /** - * 数据库表名常量定义 - */ - 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," + - NoteColumns.DELETED_DATE + " 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("DROP TRIGGER IF EXISTS record_deleted_date_on_trash"); - db.execSQL("DROP TRIGGER IF EXISTS clear_deleted_date_on_restore"); - - 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); - - // 创建记录删除时间触发器 - db.execSQL("CREATE TRIGGER record_deleted_date_on_trash " + - " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + - " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + - " AND old." + NoteColumns.PARENT_ID + "!=" + Notes.ID_TRASH_FOLER + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.DELETED_DATE + "=strftime('%s','now') * 1000" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.ID + ";" + - " END"); - - // 创建清除删除时间触发器 - db.execSQL("CREATE TRIGGER clear_deleted_date_on_restore " + - " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + - " WHEN new." + NoteColumns.PARENT_ID + "!=" + Notes.ID_TRASH_FOLER + - " AND old." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.DELETED_DATE + "=0" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.ID + ";" + - " END"); - } - - /** - * 初始化系统文件夹(通话记录文件夹、根目录、临时文件夹、回收站) - * @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++; - } - - // 版本6升级到版本7:添加删除时间字段和相关触发器 - if (oldVersion == 6) { - upgradeToV7(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"); - } - - /** - * 升级到版本7:添加删除时间字段和相关触发器,用于最近删除功能 - * @param db 数据库实例 - */ - private void upgradeToV7(SQLiteDatabase db) { - // 添加DELETED_DATE字段,用于记录便签被删除的时间 - db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.DELETED_DATE - + " INTEGER NOT NULL DEFAULT 0"); - - // 创建触发器:当便签被移动到回收站时,自动记录删除时间 - db.execSQL("CREATE TRIGGER record_deleted_date_on_trash " + - " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + - " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + - " AND old." + NoteColumns.PARENT_ID + "!=" + Notes.ID_TRASH_FOLER + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.DELETED_DATE + "=strftime('%s','now') * 1000" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.ID + ";" + - " END"); - - // 创建触发器:当便签从回收站恢复时,自动清除删除时间 - db.execSQL("CREATE TRIGGER clear_deleted_date_on_restore " + - " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + - " WHEN new." + NoteColumns.PARENT_ID + "!=" + Notes.ID_TRASH_FOLER + - " AND old." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.DELETED_DATE + "=0" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.ID + ";" + - " END"); - } -} \ 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 ceb1020..0000000 --- a/src/main/java/net/micode/notes/data/NotesProvider.java +++ /dev/null @@ -1,424 +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 { - // 支持Android搜索框架的标准参数名"query"和当前实现使用的"pattern" - searchString = uri.getQueryParameter(SearchManager.QUERY); - if (TextUtils.isEmpty(searchString)) { - 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 mDataList; - -/** - * 构造函数,创建一个新的SqlNote对象 - * - * @param context 上下文对象 - */ - public SqlNote(Context context) { - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = true; - mId = INVALID_ID; - mAlertDate = 0; - mBgColorId = ResourceParser.getDefaultBgId(context); - mCreatedDate = System.currentTimeMillis(); - mHasAttachment = 0; - mModifiedDate = System.currentTimeMillis(); - mParentId = 0; - mSnippet = ""; - mType = Notes.TYPE_NOTE; - mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; - mWidgetType = Notes.TYPE_WIDGET_INVALIDE; - mOriginParent = 0; - mVersion = 0; - mDiffNoteValues = new ContentValues(); - mDataList = new ArrayList(); - } - -/** - * 构造函数,从Cursor对象创建SqlNote对象 - * - * @param context 上下文对象 - * @param c Cursor对象,包含笔记数据 - */ - public SqlNote(Context context, Cursor c) { - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(c); - mDataList = new ArrayList(); - if (mType == Notes.TYPE_NOTE) - loadDataContent(); - mDiffNoteValues = new ContentValues(); - } - -/** - * 构造函数,根据ID从数据库加载SqlNote对象 - * - * @param context 上下文对象 - * @param id 笔记ID - */ - public SqlNote(Context context, long id) { - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(id); - mDataList = new ArrayList(); - if (mType == Notes.TYPE_NOTE) - loadDataContent(); - mDiffNoteValues = new ContentValues(); - - } - -/** - * 根据ID从数据库加载笔记数据 - * - * @param id 笔记ID - */ - private void loadFromCursor(long id) { - Cursor c = null; - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", - new String[] { - String.valueOf(id) - }, null); - if (c != null) { - c.moveToNext(); - loadFromCursor(c); - } else { - Log.w(TAG, "loadFromCursor: cursor = null"); - } - } finally { - if (c != null) - c.close(); - } - } - -/** - * 从Cursor对象加载笔记数据 - * - * @param c Cursor对象,包含笔记数据 - */ - private void loadFromCursor(Cursor c) { - mId = c.getLong(ID_COLUMN); - mAlertDate = c.getLong(ALERTED_DATE_COLUMN); - mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); - mCreatedDate = c.getLong(CREATED_DATE_COLUMN); - mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); - mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); - mParentId = c.getLong(PARENT_ID_COLUMN); - mSnippet = c.getString(SNIPPET_COLUMN); - mType = c.getInt(TYPE_COLUMN); - mWidgetId = c.getInt(WIDGET_ID_COLUMN); - mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); - mVersion = c.getLong(VERSION_COLUMN); - } - -/** - * 加载笔记的内容数据 - */ - private void loadDataContent() { - Cursor c = null; - mDataList.clear(); - try { - c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, - "(note_id=?)", new String[] { - String.valueOf(mId) - }, null); - if (c != null) { - if (c.getCount() == 0) { - Log.w(TAG, "it seems that the note has not data"); - return; - } - while (c.moveToNext()) { - SqlData data = new SqlData(mContext, c); - mDataList.add(data); - } - } else { - Log.w(TAG, "loadDataContent: cursor = null"); - } - } finally { - if (c != null) - c.close(); - } - } - -/** - * 从JSON对象设置笔记内容 - * - * @param js JSON对象,包含GTask格式的笔记数据 - * @return 设置成功返回true,否则返回false - */ - public boolean setContent(JSONObject js) { - try { - JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { - Log.w(TAG, "cannot set system folder"); - } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { - // for folder we can only update the snnipet and type - String snippet = note.has(NoteColumns.SNIPPET) ? note - .getString(NoteColumns.SNIPPET) : ""; - if (mIsCreate || !mSnippet.equals(snippet)) { - mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); - } - mSnippet = snippet; - - int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) - : Notes.TYPE_NOTE; - if (mIsCreate || mType != type) { - mDiffNoteValues.put(NoteColumns.TYPE, type); - } - mType = type; - } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { - JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; - if (mIsCreate || mId != id) { - mDiffNoteValues.put(NoteColumns.ID, id); - } - mId = id; - - long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note - .getLong(NoteColumns.ALERTED_DATE) : 0; - if (mIsCreate || mAlertDate != alertDate) { - mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); - } - mAlertDate = alertDate; - - int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note - .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); - if (mIsCreate || mBgColorId != bgColorId) { - mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); - } - mBgColorId = bgColorId; - - long createDate = note.has(NoteColumns.CREATED_DATE) ? note - .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); - if (mIsCreate || mCreatedDate != createDate) { - mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); - } - mCreatedDate = createDate; - - int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note - .getInt(NoteColumns.HAS_ATTACHMENT) : 0; - if (mIsCreate || mHasAttachment != hasAttachment) { - mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); - } - mHasAttachment = hasAttachment; - - long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note - .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); - if (mIsCreate || mModifiedDate != modifiedDate) { - mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); - } - mModifiedDate = modifiedDate; - - long parentId = note.has(NoteColumns.PARENT_ID) ? note - .getLong(NoteColumns.PARENT_ID) : 0; - if (mIsCreate || mParentId != parentId) { - mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); - } - mParentId = parentId; - - String snippet = note.has(NoteColumns.SNIPPET) ? note - .getString(NoteColumns.SNIPPET) : ""; - if (mIsCreate || !mSnippet.equals(snippet)) { - mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); - } - mSnippet = snippet; - - int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) - : Notes.TYPE_NOTE; - if (mIsCreate || mType != type) { - mDiffNoteValues.put(NoteColumns.TYPE, type); - } - mType = type; - - int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) - : AppWidgetManager.INVALID_APPWIDGET_ID; - if (mIsCreate || mWidgetId != widgetId) { - mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); - } - mWidgetId = widgetId; - - int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note - .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; - if (mIsCreate || mWidgetType != widgetType) { - mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); - } - mWidgetType = widgetType; - - long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note - .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; - if (mIsCreate || mOriginParent != originParent) { - mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); - } - mOriginParent = originParent; - - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - SqlData sqlData = null; - if (data.has(DataColumns.ID)) { - long dataId = data.getLong(DataColumns.ID); - for (SqlData temp : mDataList) { - if (dataId == temp.getId()) { - sqlData = temp; - } - } - } - - if (sqlData == null) { - sqlData = new SqlData(mContext); - mDataList.add(sqlData); - } - - sqlData.setContent(data); - } - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return false; - } - return true; - } - -/** - * 获取笔记内容的JSON表示 - * - * @return 包含笔记数据的JSON对象,如果获取失败返回null - */ - public JSONObject getContent() { - try { - JSONObject js = new JSONObject(); - - if (mIsCreate) { - Log.e(TAG, "it seems that we haven't created this in database yet"); - return null; - } - - JSONObject note = new JSONObject(); - if (mType == Notes.TYPE_NOTE) { - note.put(NoteColumns.ID, mId); - note.put(NoteColumns.ALERTED_DATE, mAlertDate); - note.put(NoteColumns.BG_COLOR_ID, mBgColorId); - note.put(NoteColumns.CREATED_DATE, mCreatedDate); - note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); - note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); - note.put(NoteColumns.PARENT_ID, mParentId); - note.put(NoteColumns.SNIPPET, mSnippet); - note.put(NoteColumns.TYPE, mType); - note.put(NoteColumns.WIDGET_ID, mWidgetId); - note.put(NoteColumns.WIDGET_TYPE, mWidgetType); - note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); - js.put(GTaskStringUtils.META_HEAD_NOTE, note); - - JSONArray dataArray = new JSONArray(); - for (SqlData sqlData : mDataList) { - JSONObject data = sqlData.getContent(); - if (data != null) { - dataArray.put(data); - } - } - js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); - } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { - note.put(NoteColumns.ID, mId); - note.put(NoteColumns.TYPE, mType); - note.put(NoteColumns.SNIPPET, mSnippet); - js.put(GTaskStringUtils.META_HEAD_NOTE, note); - } - - return js; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - return null; - } - -/** - * 设置笔记的父文件夹ID - * - * @param id 父文件夹ID - */ - public void setParentId(long id) { - mParentId = id; - mDiffNoteValues.put(NoteColumns.PARENT_ID, id); - } - -/** - * 设置笔记的Google Task ID - * - * @param gid Google Task ID - */ - public void setGtaskId(String gid) { - mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); - } - -/** - * 设置笔记的同步ID - * - * @param syncId 同步ID - */ - public void setSyncId(long syncId) { - mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); - } - -/** - * 重置本地修改标记 - */ - public void resetLocalModified() { - mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); - } - -/** - * 获取笔记ID - * - * @return 笔记ID - */ - public long getId() { - return mId; - } - -/** - * 获取父文件夹ID - * - * @return 父文件夹ID - */ - public long getParentId() { - return mParentId; - } - -/** - * 获取笔记摘要 - * - * @return 笔记摘要 - */ - public String getSnippet() { - return mSnippet; - } - -/** - * 判断是否为笔记类型(非文件夹类型) - * - * @return 是笔记类型返回true,否则返回false - */ - public boolean isNoteType() { - return mType == Notes.TYPE_NOTE; - } - -/** - * 将笔记数据提交到本地数据库 - * - * @param validateVersion 是否验证版本,true表示需要进行版本检查以避免冲突 - * @throws ActionFailureException 如果创建笔记失败 - * @throws IllegalStateException 如果更新笔记时ID无效 - */ - public void commit(boolean validateVersion) { - if (mIsCreate) { - if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { - mDiffNoteValues.remove(NoteColumns.ID); - } - - Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); - try { - mId = Long.valueOf(uri.getPathSegments().get(1)); - } catch (NumberFormatException e) { - Log.e(TAG, "Get note id error :" + e.toString()); - throw new ActionFailureException("create note failed"); - } - if (mId == 0) { - throw new IllegalStateException("Create thread id failed"); - } - - if (mType == Notes.TYPE_NOTE) { - for (SqlData sqlData : mDataList) { - sqlData.commit(mId, false, -1); - } - } - } else { - if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { - Log.e(TAG, "No such note"); - throw new IllegalStateException("Try to update note with invalid id"); - } - if (mDiffNoteValues.size() > 0) { - mVersion ++; - int result = 0; - if (!validateVersion) { - result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" - + NoteColumns.ID + "=?)", new String[] { - String.valueOf(mId) - }); - } else { - result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" - + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", - new String[] { - String.valueOf(mId), String.valueOf(mVersion) - }); - } - if (result == 0) { - Log.w(TAG, "there is no update. maybe user updates note when syncing"); - } - } - - if (mType == Notes.TYPE_NOTE) { - for (SqlData sqlData : mDataList) { - sqlData.commit(mId, validateVersion, mVersion); - } - } - } - - // refresh local info - loadFromCursor(mId); - if (mType == Notes.TYPE_NOTE) - loadDataContent(); - - mDiffNoteValues.clear(); - mIsCreate = false; - } -} diff --git a/src/main/java/net/micode/notes/gtask/data/Task.java b/src/main/java/net/micode/notes/gtask/data/Task.java deleted file mode 100644 index a9d2764..0000000 --- a/src/main/java/net/micode/notes/gtask/data/Task.java +++ /dev/null @@ -1,483 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.data; - -import android.database.Cursor; -import android.text.TextUtils; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.DataConstants; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - - -/** - * Task类是Node类的子类,用于表示Google Tasks中的任务项。 - *

- * 在小米笔记与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 mChildren; - -/** - * 构造函数,创建一个新的TaskList对象 - */ - public TaskList() { - super(); - mChildren = new ArrayList(); - mIndex = 1; - } - -/** - * 获取创建任务列表的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, 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 getChildTaskList() { - return this.mChildren; - } - -/** - * 设置任务列表的索引位置 - * - * @param index 新的索引位置 - */ - public void setIndex(int index) { - this.mIndex = index; - } - -/** - * 获取任务列表的索引位置 - * - * @return 任务列表的索引位置 - */ - public int getIndex() { - return this.mIndex; - } -} diff --git a/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java b/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java deleted file mode 100644 index 7d7892c..0000000 --- a/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.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; - -/** - * ActionFailureException是GTask同步过程中用于表示操作失败的自定义异常类 - *

- * 当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 { - - /** - * GTask同步通知的唯一ID - */ - private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; - - /** - * OnCompleteListener是GTask同步完成时的回调接口 - */ - public interface OnCompleteListener { - /** - * 当GTask同步完成时调用此方法 - */ - void onComplete(); - } - - /** - * Android应用上下文对象 - */ - private Context mContext; - - /** - * 通知管理器,用于显示同步进度和结果通知 - */ - private NotificationManager mNotifiManager; - - /** - * GTask管理器实例,负责执行实际的同步操作 - */ - private GTaskManager mTaskManager; - - /** - * 同步完成监听器,用于在同步结束后回调通知 - */ - private OnCompleteListener mOnCompleteListener; - - /** - * GTaskASyncTask构造函数 - * - * @param context 应用上下文 - * @param listener 同步完成监听器 - */ - public GTaskASyncTask(Context context, OnCompleteListener listener) { - mContext = context; - mOnCompleteListener = listener; - mNotifiManager = (NotificationManager) mContext - .getSystemService(Context.NOTIFICATION_SERVICE); - mTaskManager = GTaskManager.getInstance(); - } - - /** - * 取消当前正在进行的GTask同步操作 - */ - public void cancelSync() { - mTaskManager.cancelSync(); - } - - /** - * 发布同步进度更新 - * - * @param message 进度消息内容 - */ - public void publishProgess(String message) { - publishProgress(new String[] { - message - }); - } - -// - /* 显示GTask同步通知 - * - * @param tickerId 通知标题的字符串资源ID; - * @param content 通知内容 - */ -// private void showNotification(int tickerId, String content) { -// Notification notification = new Notification(R.drawable.notification, mContext -// .getString(tickerId), System.currentTimeMillis()); - // notification.defaults = Notification.DEFAULT_LIGHTS; -// notification.flags = Notification.FLAG_AUTO_CANCEL; - // PendingIntent pendingIntent; -// if (tickerId != R.string.ticker_success) { -// pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, -// NotesPreferenceActivity.class), 0); -// - // } else { - // pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, -// NotesListActivity.class), 0); -// } -// notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, -// pendingIntent); -// mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); -// } -private void showNotification(int tickerId, String content) { - PendingIntent pendingIntent; - if (tickerId != R.string.ticker_success) { - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE); - } else { - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE); - } - Notification.Builder builder = new Notification.Builder(mContext) - .setAutoCancel(true) - .setContentTitle(mContext.getString(R.string.app_name)) - .setContentText(content) - .setContentIntent(pendingIntent) - .setWhen(System.currentTimeMillis()) - .setOngoing(true); - Notification notification=builder.getNotification(); - mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); -} - - /** - * 在后台线程执行GTask同步操作 - * - * @param unused 未使用的参数 - * @return 同步结果状态码 - */ - @Override - protected Integer doInBackground(Void... unused) { - publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity - .getSyncAccountName(mContext))); - return mTaskManager.sync(mContext, this); - } - - /** - * 当后台任务发布进度更新时调用 - * - * @param progress 进度消息数组 - */ - @Override - protected void onProgressUpdate(String... progress) { - showNotification(R.string.ticker_syncing, progress[0]); - if (mContext instanceof GTaskSyncService) { - ((GTaskSyncService) mContext).sendBroadcast(progress[0]); - } - } - - /** - * 当后台任务执行完成后调用 - * - * @param result 同步结果状态码 - */ - @Override - protected void onPostExecute(Integer result) { - if (result == GTaskManager.STATE_SUCCESS) { - showNotification(R.string.ticker_success, mContext.getString( - R.string.success_sync_account, mTaskManager.getSyncAccount())); - NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); - } else if (result == GTaskManager.STATE_NETWORK_ERROR) { - showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); - } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { - showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); - } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { - showNotification(R.string.ticker_cancel, mContext - .getString(R.string.error_sync_cancelled)); - } - if (mOnCompleteListener != null) { - new Thread(new Runnable() { - - public void run() { - mOnCompleteListener.onComplete(); - } - }).start(); - } - } -} diff --git a/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java b/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java deleted file mode 100644 index 776a6a5..0000000 --- a/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java +++ /dev/null @@ -1,782 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.remote; - -import android.accounts.Account; -import android.accounts.AccountManager; -import android.accounts.AccountManagerFuture; -import android.app.Activity; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; - -import net.micode.notes.gtask.data.Node; -import net.micode.notes.gtask.data.Task; -import net.micode.notes.gtask.data.TaskList; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.gtask.exception.NetworkFailureException; -import net.micode.notes.tool.GTaskStringUtils; -import net.micode.notes.ui.NotesPreferenceActivity; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.cookie.Cookie; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.LinkedList; -import java.util.List; -import java.util.zip.GZIPInputStream; -import java.util.zip.Inflater; -import java.util.zip.InflaterInputStream; - - -/** - * GTaskClient是GTask同步模块的核心客户端类,负责与Google Tasks服务器进行交互 - *

- * 该类提供了以下主要功能: - * 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 accountManagerFuture = accountManager.getAuthToken(account, - "goanna_mobile", null, activity, null, null); - try { - Bundle authTokenBundle = accountManagerFuture.getResult(); - authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); - if (invalidateToken) { - accountManager.invalidateAuthToken("com.google", authToken); - loginGoogleAccount(activity, false); - } - } catch (Exception e) { - Log.e(TAG, "get auth token failed"); - authToken = null; - } - - return authToken; - } - - /** - * 尝试登录Google Tasks - *

- * 如果登录失败,会尝试使令牌失效并重新登录 - *

- * - * @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 cookies = mHttpClient.getCookieStore().getCookies(); - boolean hasAuthCookie = false; - for (Cookie cookie : cookies) { - if (cookie.getName().contains("GTL")) { - hasAuthCookie = true; - } - } - if (!hasAuthCookie) { - Log.w(TAG, "it seems that there is no auth cookie"); - } - - // get the client version - 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); - mClientVersion = js.getLong("v"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return false; - } catch (Exception e) { - // simply catch all exceptions - Log.e(TAG, "httpget gtask_url failed"); - return false; - } - - return true; - } - - /** - * 获取下一个操作ID - * - * @return 操作ID - */ - private int getActionId() { - return mActionId++; - } - - /** - * 创建HTTP POST请求对象 - * - * @return HttpPost请求对象 - */ - private HttpPost createHttpPost() { - HttpPost httpPost = new HttpPost(mPostUrl); - httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); - httpPost.setHeader("AT", "1"); - return httpPost; - } - - /** - * 获取HTTP响应内容 - *

- * 支持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 list = new LinkedList(); - list.add(new BasicNameValuePair("r", js.toString())); - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); - httpPost.setEntity(entity); - - // execute the post - HttpResponse response = mHttpClient.execute(httpPost); - String jsString = getResponseContent(response.getEntity()); - return new JSONObject(jsString); - - } catch (ClientProtocolException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); - } catch (IOException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("unable to convert response content to jsonobject"); - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("error occurs when posting request"); - } - } - - /** - * 创建新任务 - * - * @param task 要创建的任务对象 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果任务创建失败 - */ - public void createTask(Task task) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // action_list - actionList.put(task.getCreateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // post - JSONObject jsResponse = postRequest(jsPost); - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create task: handing jsonobject failed"); - } - } - - /** - * 创建新任务列表 - * - * @param tasklist 要创建的任务列表对象 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果任务列表创建失败 - */ - public void createTaskList(TaskList tasklist) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // action_list - actionList.put(tasklist.getCreateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // post - JSONObject jsResponse = postRequest(jsPost); - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create tasklist: handing jsonobject failed"); - } - } - - /** - * 提交批量更新操作 - * - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果更新提交失败 - */ - public void commitUpdate() throws NetworkFailureException { - if (mUpdateArray != null) { - try { - JSONObject jsPost = new JSONObject(); - - // action_list - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - postRequest(jsPost); - mUpdateArray = null; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("commit update: handing jsonobject failed"); - } - } - } - - /** - * 添加节点更新操作到批量更新数组 - *

- * 如果更新数组中的操作数量超过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 mGTaskListHashMap; - - /** - * 所有远程任务的HashMap,键为任务的GID - */ - private HashMap mGTaskHashMap; - - /** - * 元数据的HashMap,键为相关节点的GID - */ - private HashMap mMetaHashMap; - - /** - * 存储元数据的任务列表 - */ - private TaskList mMetaList; - - /** - * 本地已删除笔记的ID集合 - */ - private HashSet mLocalDeleteIdMap; - - /** - * 远程GID到本地NID的映射 - */ - private HashMap mGidToNid; - - /** - * 本地NID到远程GID的映射 - */ - private HashMap mNidToGid; - - /** - * 私有构造方法,初始化GTaskManager的内部状态和集合 - */ - private GTaskManager() { - mSyncing = false; - mCancelled = false; - mGTaskListHashMap = new HashMap(); - mGTaskHashMap = new HashMap(); - mMetaHashMap = new HashMap(); - mMetaList = null; - mLocalDeleteIdMap = new HashSet(); - mGidToNid = new HashMap(); - mNidToGid = new HashMap(); - } - - /** - * 获取GTaskManager的单例实例 - * @return GTaskManager的单例实例 - */ - public static synchronized GTaskManager getInstance() { - if (mInstance == null) { - mInstance = new GTaskManager(); - } - return mInstance; - } - - /** - * 设置用于Google登录的Activity上下文 - * @param activity 用于获取认证令牌的Activity实例 - */ - public synchronized void setActivityContext(Activity activity) { - mActivity = activity; - } - - /** - * 执行GTask同步操作,协调本地笔记与Google Tasks服务器之间的数据同步 - * @param context 应用上下文 - * @param asyncTask 用于发布同步进度的异步任务实例 - * @return 同步结果状态: - * - {@link #STATE_SUCCESS}:同步成功 - * - {@link #STATE_NETWORK_ERROR}:网络错误 - * - {@link #STATE_INTERNAL_ERROR}:内部错误 - * - {@link #STATE_SYNC_IN_PROGRESS}:同步已在进行中 - * - {@link #STATE_SYNC_CANCELLED}:同步被取消 - */ - public int sync(Context context, GTaskASyncTask asyncTask) { - if (mSyncing) { - Log.d(TAG, "Sync is in progress"); - return STATE_SYNC_IN_PROGRESS; - } - mContext = context; - mContentResolver = mContext.getContentResolver(); - mSyncing = true; - mCancelled = false; - mGTaskListHashMap.clear(); - mGTaskHashMap.clear(); - mMetaHashMap.clear(); - mLocalDeleteIdMap.clear(); - mGidToNid.clear(); - mNidToGid.clear(); - - try { - GTaskClient client = GTaskClient.getInstance(); - client.resetUpdateArray(); - - // login google task - if (!mCancelled) { - if (!client.login(mActivity)) { - throw new NetworkFailureException("login google task failed"); - } - } - - // get the task list from google - asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); - initGTaskList(); - - // do content sync work - asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); - syncContent(); - } catch (NetworkFailureException e) { - Log.e(TAG, e.toString()); - return STATE_NETWORK_ERROR; - } catch (ActionFailureException e) { - Log.e(TAG, e.toString()); - return STATE_INTERNAL_ERROR; - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return STATE_INTERNAL_ERROR; - } finally { - mGTaskListHashMap.clear(); - mGTaskHashMap.clear(); - mMetaHashMap.clear(); - mLocalDeleteIdMap.clear(); - mGidToNid.clear(); - mNidToGid.clear(); - mSyncing = false; - } - - return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; - } - - /** - * 初始化远程任务列表,从Google Tasks服务器获取所有任务列表和任务 - * @throws NetworkFailureException 网络操作失败时抛出 - */ - private void initGTaskList() throws NetworkFailureException { - if (mCancelled) - return; - GTaskClient client = GTaskClient.getInstance(); - try { - JSONArray jsTaskLists = client.getTaskLists(); - - // init meta list first - mMetaList = null; - for (int i = 0; i < jsTaskLists.length(); i++) { - JSONObject object = jsTaskLists.getJSONObject(i); - String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); - - if (name - .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { - mMetaList = new TaskList(); - mMetaList.setContentByRemoteJSON(object); - - // load meta data - JSONArray jsMetas = client.getTaskList(gid); - for (int j = 0; j < jsMetas.length(); j++) { - object = (JSONObject) jsMetas.getJSONObject(j); - MetaData metaData = new MetaData(); - metaData.setContentByRemoteJSON(object); - if (metaData.isWorthSaving()) { - mMetaList.addChildTask(metaData); - if (metaData.getGid() != null) { - mMetaHashMap.put(metaData.getRelatedGid(), metaData); - } - } - } - } - } - - // create meta list if not existed - if (mMetaList == null) { - mMetaList = new TaskList(); - mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META); - GTaskClient.getInstance().createTaskList(mMetaList); - } - - // init task list - for (int i = 0; i < jsTaskLists.length(); i++) { - JSONObject object = jsTaskLists.getJSONObject(i); - String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); - - if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) - && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META)) { - TaskList tasklist = new TaskList(); - tasklist.setContentByRemoteJSON(object); - mGTaskListHashMap.put(gid, tasklist); - mGTaskHashMap.put(gid, tasklist); - - // load tasks - JSONArray jsTasks = client.getTaskList(gid); - for (int j = 0; j < jsTasks.length(); j++) { - object = (JSONObject) jsTasks.getJSONObject(j); - gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - Task task = new Task(); - task.setContentByRemoteJSON(object); - if (task.isWorthSaving()) { - task.setMetaInfo(mMetaHashMap.get(gid)); - tasklist.addChildTask(task); - mGTaskHashMap.put(gid, task); - } - } - } - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("initGTaskList: handing JSONObject failed"); - } - } - - /** - * 同步本地和远程内容,处理本地删除、文件夹和笔记的同步 - * @throws NetworkFailureException 网络操作失败时抛出 - */ - private void syncContent() throws NetworkFailureException { - int syncType; - Cursor c = null; - String gid; - Node node; - - mLocalDeleteIdMap.clear(); - - if (mCancelled) { - return; - } - - // for local deleted note - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type<>? AND parent_id=?)", new String[] { - String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) - }, null); - if (c != null) { - while (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); - } - - mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); - } - } else { - Log.w(TAG, "failed to query trash folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // sync folder first - syncFolder(); - - // for note existing in database - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type=? AND parent_id<>?)", new String[] { - String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) - }, NoteColumns.TYPE + " DESC"); - if (c != null) { - while (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); - mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); - syncType = node.getSyncAction(c); - } else { - if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { - // local add - syncType = Node.SYNC_ACTION_ADD_REMOTE; - } else { - // remote delete - syncType = Node.SYNC_ACTION_DEL_LOCAL; - } - } - doContentSync(syncType, node, c); - } - } else { - Log.w(TAG, "failed to query existing note in database"); - } - - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // go through remaining items - Iterator> iter = mGTaskHashMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - node = entry.getValue(); - doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); - } - - // mCancelled can be set by another thread, so we neet to check one by - // one - // clear local delete table - if (!mCancelled) { - if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { - throw new ActionFailureException("failed to batch-delete local deleted notes"); - } - } - - // refresh local sync id - if (!mCancelled) { - GTaskClient.getInstance().commitUpdate(); - refreshLocalSyncId(); - } - - } - - /** - * 同步文件夹,包括根文件夹、通话记录文件夹和普通文件夹 - * @throws NetworkFailureException 网络操作失败时抛出 - */ - private void syncFolder() throws NetworkFailureException { - Cursor c = null; - String gid; - Node node; - int syncType; - - if (mCancelled) { - return; - } - - // for root folder - try { - c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, - Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); - if (c != null) { - c.moveToNext(); - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); - mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); - // for system folder, only update remote name if necessary - if (!node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) - doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); - } else { - doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); - } - } else { - Log.w(TAG, "failed to query root folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // for call-note folder - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", - new String[] { - String.valueOf(Notes.ID_CALL_RECORD_FOLDER) - }, null); - if (c != null) { - if (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); - mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); - // for system folder, only update remote name if - // necessary - if (!node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_CALL_NOTE)) - doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); - } else { - doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); - } - } - } else { - Log.w(TAG, "failed to query call note folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // for local existing folders - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type=? AND parent_id<>?)", new String[] { - String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) - }, NoteColumns.TYPE + " DESC"); - if (c != null) { - while (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); - mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); - syncType = node.getSyncAction(c); - } else { - if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { - // local add - syncType = Node.SYNC_ACTION_ADD_REMOTE; - } else { - // remote delete - syncType = Node.SYNC_ACTION_DEL_LOCAL; - } - } - doContentSync(syncType, node, c); - } - } else { - Log.w(TAG, "failed to query existing folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // for remote add folders - Iterator> iter = mGTaskListHashMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - gid = entry.getKey(); - node = entry.getValue(); - if (mGTaskHashMap.containsKey(gid)) { - mGTaskHashMap.remove(gid); - doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); - } - } - - if (!mCancelled) - GTaskClient.getInstance().commitUpdate(); - } - - /** - * 根据同步类型执行不同的同步操作 - * @param syncType 同步类型,来自{@link Node}类的同步操作常量 - * @param node 要同步的节点(可以是TaskList或Task) - * @param c 本地数据库游标,用于获取本地数据 - * @throws NetworkFailureException 网络操作失败时抛出 - */ - private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { - if (mCancelled) { - return; - } - - MetaData meta; - switch (syncType) { - case Node.SYNC_ACTION_ADD_LOCAL: - addLocalNode(node); - break; - case Node.SYNC_ACTION_ADD_REMOTE: - addRemoteNode(node, c); - break; - case Node.SYNC_ACTION_DEL_LOCAL: - meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN)); - if (meta != null) { - GTaskClient.getInstance().deleteNode(meta); - } - mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); - break; - case Node.SYNC_ACTION_DEL_REMOTE: - meta = mMetaHashMap.get(node.getGid()); - if (meta != null) { - GTaskClient.getInstance().deleteNode(meta); - } - GTaskClient.getInstance().deleteNode(node); - break; - case Node.SYNC_ACTION_UPDATE_LOCAL: - updateLocalNode(node, c); - break; - case Node.SYNC_ACTION_UPDATE_REMOTE: - updateRemoteNode(node, c); - break; - case Node.SYNC_ACTION_UPDATE_CONFLICT: - // merging both modifications maybe a good idea - // right now just use local update simply - updateRemoteNode(node, c); - break; - case Node.SYNC_ACTION_NONE: - break; - case Node.SYNC_ACTION_ERROR: - default: - throw new ActionFailureException("unkown sync action type"); - } - } - - /** - * 将远程节点添加到本地数据库 - * @param node 要添加的远程节点 - * @throws NetworkFailureException 网络操作失败时抛出 - */ - private void addLocalNode(Node node) throws NetworkFailureException { - if (mCancelled) { - return; - } - - SqlNote sqlNote; - if (node instanceof TaskList) { - if (node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { - sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); - } else if (node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { - sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); - } else { - sqlNote = new SqlNote(mContext); - sqlNote.setContent(node.getLocalJSONFromContent()); - sqlNote.setParentId(Notes.ID_ROOT_FOLDER); - } - } else { - sqlNote = new SqlNote(mContext); - JSONObject js = node.getLocalJSONFromContent(); - try { - if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { - JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - if (note.has(NoteColumns.ID)) { - long id = note.getLong(NoteColumns.ID); - if (DataUtils.existInNoteDatabase(mContentResolver, id)) { - // the id is not available, have to create a new one - note.remove(NoteColumns.ID); - } - } - } - - if (js.has(GTaskStringUtils.META_HEAD_DATA)) { - JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - if (data.has(DataColumns.ID)) { - long dataId = data.getLong(DataColumns.ID); - if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { - // the data id is not available, have to create - // a new one - data.remove(DataColumns.ID); - } - } - } - - } - } catch (JSONException e) { - Log.w(TAG, e.toString()); - e.printStackTrace(); - } - sqlNote.setContent(js); - - Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); - if (parentId == null) { - Log.e(TAG, "cannot find task's parent id locally"); - throw new ActionFailureException("cannot add local node"); - } - sqlNote.setParentId(parentId.longValue()); - } - - // create the local node - sqlNote.setGtaskId(node.getGid()); - sqlNote.commit(false); - - // update gid-nid mapping - mGidToNid.put(node.getGid(), sqlNote.getId()); - mNidToGid.put(sqlNote.getId(), node.getGid()); - - // update meta - updateRemoteMeta(node.getGid(), sqlNote); - } - - /** - * 更新本地节点,将远程节点的内容更新到本地数据库 - * @param node 要同步的远程节点 - * @param c 本地数据库游标,用于获取本地数据 - * @throws NetworkFailureException 网络操作失败时抛出 - */ - private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { - if (mCancelled) { - return; - } - - SqlNote sqlNote; - // update the note locally - sqlNote = new SqlNote(mContext, c); - sqlNote.setContent(node.getLocalJSONFromContent()); - - Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) - : new Long(Notes.ID_ROOT_FOLDER); - if (parentId == null) { - Log.e(TAG, "cannot find task's parent id locally"); - throw new ActionFailureException("cannot update local node"); - } - sqlNote.setParentId(parentId.longValue()); - sqlNote.commit(true); - - // update meta info - updateRemoteMeta(node.getGid(), sqlNote); - } - - /** - * 将本地节点添加到远程服务器 - * @param node 要同步的远程节点(可以为null,表示创建新节点) - * @param c 本地数据库游标,用于获取本地数据 - * @throws NetworkFailureException 网络操作失败时抛出 - */ - private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { - if (mCancelled) { - return; - } - - SqlNote sqlNote = new SqlNote(mContext, c); - Node n; - - // update remotely - if (sqlNote.isNoteType()) { - Task task = new Task(); - task.setContentByLocalJSON(sqlNote.getContent()); - - String parentGid = mNidToGid.get(sqlNote.getParentId()); - if (parentGid == null) { - Log.e(TAG, "cannot find task's parent tasklist"); - throw new ActionFailureException("cannot add remote task"); - } - mGTaskListHashMap.get(parentGid).addChildTask(task); - - GTaskClient.getInstance().createTask(task); - n = (Node) task; - - // add meta - updateRemoteMeta(task.getGid(), sqlNote); - } else { - TaskList tasklist = null; - - // we need to skip folder if it has already existed - String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX; - if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) - folderName += GTaskStringUtils.FOLDER_DEFAULT; - else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER) - folderName += GTaskStringUtils.FOLDER_CALL_NOTE; - else - folderName += sqlNote.getSnippet(); - - Iterator> iter = mGTaskListHashMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - String gid = entry.getKey(); - TaskList list = entry.getValue(); - - if (list.getName().equals(folderName)) { - tasklist = list; - if (mGTaskHashMap.containsKey(gid)) { - mGTaskHashMap.remove(gid); - } - break; - } - } - - // no match we can add now - if (tasklist == null) { - tasklist = new TaskList(); - tasklist.setContentByLocalJSON(sqlNote.getContent()); - GTaskClient.getInstance().createTaskList(tasklist); - mGTaskListHashMap.put(tasklist.getGid(), tasklist); - } - n = (Node) tasklist; - } - - // update local note - sqlNote.setGtaskId(n.getGid()); - sqlNote.commit(false); - sqlNote.resetLocalModified(); - sqlNote.commit(true); - - // gid-id mapping - mGidToNid.put(n.getGid(), sqlNote.getId()); - mNidToGid.put(sqlNote.getId(), n.getGid()); - } - - /** - * 更新远程节点,将本地节点的内容更新到远程服务器 - * @param node 要更新的远程节点 - * @param c 本地数据库游标,用于获取本地数据 - * @throws NetworkFailureException 网络操作失败时抛出 - */ - private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { - if (mCancelled) { - return; - } - - SqlNote sqlNote = new SqlNote(mContext, c); - - // update remotely - node.setContentByLocalJSON(sqlNote.getContent()); - GTaskClient.getInstance().addUpdateNode(node); - - // update meta - updateRemoteMeta(node.getGid(), sqlNote); - - // move task if necessary - if (sqlNote.isNoteType()) { - Task task = (Task) node; - TaskList preParentList = task.getParent(); - - String curParentGid = mNidToGid.get(sqlNote.getParentId()); - if (curParentGid == null) { - Log.e(TAG, "cannot find task's parent tasklist"); - throw new ActionFailureException("cannot update remote task"); - } - TaskList curParentList = mGTaskListHashMap.get(curParentGid); - - if (preParentList != curParentList) { - preParentList.removeChildTask(task); - curParentList.addChildTask(task); - GTaskClient.getInstance().moveTask(task, preParentList, curParentList); - } - } - - // clear local modified flag - sqlNote.resetLocalModified(); - sqlNote.commit(true); - } - - /** - * 更新远程元数据,将本地笔记的元数据信息同步到远程服务器 - * @param gid 远程节点的GID - * @param sqlNote 本地笔记对象 - * @throws NetworkFailureException 网络操作失败时抛出 - */ - private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { - if (sqlNote != null && sqlNote.isNoteType()) { - MetaData metaData = mMetaHashMap.get(gid); - if (metaData != null) { - metaData.setMeta(gid, sqlNote.getContent()); - GTaskClient.getInstance().addUpdateNode(metaData); - } else { - metaData = new MetaData(); - metaData.setMeta(gid, sqlNote.getContent()); - mMetaList.addChildTask(metaData); - mMetaHashMap.put(gid, metaData); - GTaskClient.getInstance().createTask(metaData); - } - } - } - - /** - * 刷新本地同步ID,根据远程数据更新本地节点的同步时间戳 - * @throws NetworkFailureException 网络操作失败时抛出 - */ - private void refreshLocalSyncId() throws NetworkFailureException { - if (mCancelled) { - return; - } - - // get the latest gtask list - mGTaskHashMap.clear(); - mGTaskListHashMap.clear(); - mMetaHashMap.clear(); - initGTaskList(); - - Cursor c = null; - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type<>? AND parent_id<>?)", new String[] { - String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) - }, NoteColumns.TYPE + " DESC"); - if (c != null) { - while (c.moveToNext()) { - String gid = c.getString(SqlNote.GTASK_ID_COLUMN); - Node node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - ContentValues values = new ContentValues(); - values.put(NoteColumns.SYNC_ID, node.getLastModified()); - mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, - c.getLong(SqlNote.ID_COLUMN)), values, null, null); - } else { - Log.e(TAG, "something is missed"); - throw new ActionFailureException( - "some local items don't have gid after sync"); - } - } - } else { - Log.w(TAG, "failed to query local note to refresh sync id"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - } - - /** - * 获取当前同步账户的名称 - * @return 同步账户名称 - */ - public String getSyncAccount() { - return GTaskClient.getInstance().getSyncAccount().name; - } - - /** - * 取消当前正在进行的同步操作 - */ - public void cancelSync() { - mCancelled = true; - } -} diff --git a/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java b/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java deleted file mode 100644 index 512df71..0000000 --- a/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.gtask.remote; - -import android.app.Activity; -import android.app.Service; -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.os.IBinder; - -/** - * GTaskSyncService是GTask同步的服务类,负责管理GTask同步的启动、取消和进度通知 - *

- * 该服务提供了以下主要功能: - * 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 operationList = new ArrayList(); - ContentProviderOperation.Builder builder = null; - - if(mTextDataValues.size() > 0) { - mTextDataValues.put(DataColumns.NOTE_ID, noteId); - if (mTextDataId == 0) { - mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); - Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, - mTextDataValues); - try { - setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); - } catch (NumberFormatException e) { - Log.e(TAG, "Insert new text data fail with noteId" + noteId); - mTextDataValues.clear(); - return null; - } - } else { - builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mTextDataId)); - builder.withValues(mTextDataValues); - operationList.add(builder.build()); - } - mTextDataValues.clear(); - } - - if(mCallDataValues.size() > 0) { - mCallDataValues.put(DataColumns.NOTE_ID, noteId); - if (mCallDataId == 0) { - mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); - Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, - mCallDataValues); - try { - setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); - } catch (NumberFormatException e) { - Log.e(TAG, "Insert new call data fail with noteId" + noteId); - mCallDataValues.clear(); - return null; - } - } else { - builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mCallDataId)); - builder.withValues(mCallDataValues); - operationList.add(builder.build()); - } - mCallDataValues.clear(); - } - - if (operationList.size() > 0) { - try { - ContentProviderResult[] results = context.getContentResolver().applyBatch( - Notes.AUTHORITY, operationList); - return (results == null || results.length == 0 || results[0] == null) ? null - : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); - } catch (RemoteException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); - return null; - } catch (OperationApplicationException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); - return null; - } - } - return null; - } - } -} diff --git a/src/main/java/net/micode/notes/model/NoteTemplate.java b/src/main/java/net/micode/notes/model/NoteTemplate.java deleted file mode 100644 index c956f7d..0000000 --- a/src/main/java/net/micode/notes/model/NoteTemplate.java +++ /dev/null @@ -1,119 +0,0 @@ -package net.micode.notes.model; - -import android.content.Context; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; -import android.text.TextUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.List; - -/** - * 笔记模板数据模型类,用于存储和管理笔记模板 - */ -public class NoteTemplate { - public static final String TYPE_SYSTEM = "system"; - public static final String TYPE_CUSTOM = "custom"; - - private long id; - private String name; - private String content; - private String type; - private long createTime; - private long updateTime; - - public NoteTemplate() { - this.createTime = System.currentTimeMillis(); - this.updateTime = System.currentTimeMillis(); - } - - public NoteTemplate(long id, String name, String content, String type, long createTime, long updateTime) { - this.id = id; - this.name = name; - this.content = content; - this.type = type; - this.createTime = createTime; - this.updateTime = updateTime; - } - - // Getters and Setters - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public long getCreateTime() { - return createTime; - } - - public void setCreateTime(long createTime) { - this.createTime = createTime; - } - - public long getUpdateTime() { - return updateTime; - } - - public void setUpdateTime(long updateTime) { - this.updateTime = updateTime; - } - - /** - * 将模板对象转换为JSON对象 - */ - public JSONObject toJson() throws JSONException { - JSONObject json = new JSONObject(); - json.put("id", id); - json.put("name", name); - json.put("content", content); - json.put("type", type); - json.put("createTime", createTime); - json.put("updateTime", updateTime); - return json; - } - - /** - * 从JSON对象创建模板对象 - */ - public static NoteTemplate fromJson(JSONObject json) throws JSONException { - NoteTemplate template = new NoteTemplate(); - template.setId(json.getLong("id")); - template.setName(json.getString("name")); - template.setContent(json.getString("content")); - template.setType(json.getString("type")); - template.setCreateTime(json.getLong("createTime")); - template.setUpdateTime(json.getLong("updateTime")); - return template; - } -} diff --git a/src/main/java/net/micode/notes/model/RecentlyDeletedManager.java b/src/main/java/net/micode/notes/model/RecentlyDeletedManager.java deleted file mode 100644 index c025468..0000000 --- a/src/main/java/net/micode/notes/model/RecentlyDeletedManager.java +++ /dev/null @@ -1,230 +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.ContentResolver; -import android.content.Context; -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.tool.DataUtils; - -import java.util.HashSet; - -/** - * 最近删除管理器,负责管理最近删除的便签和文件夹 - * 采用单例模式设计,提供获取最近删除项、恢复项、永久删除项、清空回收站等功能 - */ -public class RecentlyDeletedManager { - // 默认保留天数,超过此天数的已删除项将被自动清理 - public static final int DEFAULT_RETENTION_DAYS = 30; - // 清理任务间隔(每天) - public static final long CLEANUP_INTERVAL = 24 * 60 * 60 * 1000; - - private Context mContext; - private ContentResolver mContentResolver; - - // 单例实例 - private static RecentlyDeletedManager sInstance; - // 日志标签 - private static final String TAG = "RecentlyDeletedManager"; - - /** - * 私有构造方法,防止外部实例化 - * @param context 上下文对象 - */ - private RecentlyDeletedManager(Context context) { - mContext = context.getApplicationContext(); - mContentResolver = mContext.getContentResolver(); - } - - /** - * 获取单例实例 - * @param context 上下文对象 - * @return 最近删除管理器实例 - */ - public static synchronized RecentlyDeletedManager getInstance(Context context) { - if (sInstance == null) { - sInstance = new RecentlyDeletedManager(context); - } - return sInstance; - } - - /** - * 获取最近删除的项列表 - * @return 最近删除项的游标,按删除时间倒序排列 - */ - public Cursor getRecentlyDeletedItems() { - // 查询条件:已删除(DELETED_DATE > 0)且位于回收站文件夹 - String selection = NoteColumns.DELETED_DATE + " > 0 AND " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER; - // 按删除时间倒序排序 - String sortOrder = NoteColumns.DELETED_DATE + " DESC"; - - try { - return mContentResolver.query( - Notes.CONTENT_NOTE_URI, - null, // 查询所有列 - selection, - null, - sortOrder - ); - } catch (Exception e) { - Log.e(TAG, "Failed to get recently deleted items", e); - return null; - } - } - - /** - * 恢复指定项 - * @param itemIds 要恢复的项ID数组 - * @return 成功恢复的项数量 - */ - public int restoreItems(long[] itemIds) { - if (itemIds == null || itemIds.length == 0) { - return 0; - } - - int restoredCount = 0; - - for (long itemId : itemIds) { - try { - // 获取原父文件夹ID - String[] projection = {NoteColumns.ORIGIN_PARENT_ID}; - String selection = NoteColumns.ID + "=" + itemId; - - Cursor cursor = mContentResolver.query( - Notes.CONTENT_NOTE_URI, - projection, - selection, - null, - null - ); - - if (cursor != null && cursor.moveToFirst()) { - long originParentId = cursor.getLong(0); - cursor.close(); - - // 如果原父文件夹不存在或已被删除,使用根文件夹 - long targetParentId = originParentId != Notes.ID_TRASH_FOLER ? originParentId : Notes.ID_ROOT_FOLDER; - - // 使用现有的batchMoveToFolder方法来恢复项目 - HashSet ids = new HashSet(); - ids.add(itemId); - if (DataUtils.batchMoveToFolder(mContentResolver, ids, targetParentId)) { - restoredCount++; - } - } else if (cursor != null) { - cursor.close(); - } - } catch (Exception e) { - Log.e(TAG, "Failed to restore item: " + itemId, e); - } - } - - return restoredCount; - } - - /** - * 永久删除指定项 - * @param itemIds 要永久删除的项ID数组 - * @return 成功永久删除的项数量 - */ - public int permanentlyDeleteItems(long[] itemIds) { - if (itemIds == null || itemIds.length == 0) { - return 0; - } - - int deletedCount = 0; - - for (long itemId : itemIds) { - try { - int rowsAffected = mContentResolver.delete( - Notes.CONTENT_NOTE_URI, - NoteColumns.ID + "=" + itemId, - null - ); - - if (rowsAffected > 0) { - deletedCount++; - } - } catch (Exception e) { - Log.e(TAG, "Failed to permanently delete item: " + itemId, e); - } - } - - return deletedCount; - } - - /** - * 清空回收站 - * @return 成功清空的项数量 - */ - public int emptyTrash() { - try { - // 删除所有已删除且位于回收站的项 - String selection = NoteColumns.DELETED_DATE + " > 0 AND " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER; - - return mContentResolver.delete( - Notes.CONTENT_NOTE_URI, - selection, - null - ); - } catch (Exception e) { - Log.e(TAG, "Failed to empty trash", e); - return 0; - } - } - - /** - * 清理超过保留天数的项 - * @param retentionDays 保留天数 - * @return 成功清理的项数量 - */ - public int cleanupOldItems(int retentionDays) { - if (retentionDays < 0) { - retentionDays = DEFAULT_RETENTION_DAYS; - } - - try { - // 计算清理阈值:当前时间减去保留天数(毫秒) - long cleanupThreshold = System.currentTimeMillis() - (retentionDays * 24 * 60 * 60 * 1000); - - // 删除条件:已删除且删除时间小于清理阈值 - String selection = NoteColumns.DELETED_DATE + " > 0 AND " + NoteColumns.DELETED_DATE + " < " + cleanupThreshold; - - return mContentResolver.delete( - Notes.CONTENT_NOTE_URI, - selection, - null - ); - } catch (Exception e) { - Log.e(TAG, "Failed to cleanup old items", e); - return 0; - } - } - - /** - * 启动自动清理任务 - * 注意:此方法在当前实现中仅作为占位符,实际自动清理逻辑由TrashCleanupWorker实现 - */ - public void startAutoCleanup() { - // 自动清理任务由TrashCleanupWorker处理,此处预留接口 - Log.d(TAG, "Auto cleanup task is managed by TrashCleanupWorker"); - } -} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/model/TemplateManager.java b/src/main/java/net/micode/notes/model/TemplateManager.java deleted file mode 100644 index be93fc8..0000000 --- a/src/main/java/net/micode/notes/model/TemplateManager.java +++ /dev/null @@ -1,271 +0,0 @@ -package net.micode.notes.model; - -import android.content.Context; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; -import android.text.TextUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.List; - -/** - * 模板管理类,用于管理笔记模板的存储、加载、添加、删除等操作 - */ -public class TemplateManager { - private static final String PREF_TEMPLATES = "note_templates"; - private static final String PREF_TEMPLATE_ID_COUNTER = "template_id_counter"; - private static TemplateManager sInstance; - private Context mContext; - private List mTemplates; - - private TemplateManager(Context context) { - mContext = context.getApplicationContext(); - loadTemplates(); - } - - public static synchronized TemplateManager getInstance(Context context) { - if (sInstance == null) { - sInstance = new TemplateManager(context); - } - return sInstance; - } - - /** - * 加载所有模板,包括系统模板和自定义模板 - */ - private void loadTemplates() { - mTemplates = new ArrayList<>(); - - // 先添加系统模板 - addSystemTemplates(); - - // 然后加载自定义模板 - loadCustomTemplates(); - } - - /** - * 添加系统模板 - */ - private void addSystemTemplates() { - // 会议记录模板 - NoteTemplate meetingTemplate = new NoteTemplate(); - meetingTemplate.setId(1); - meetingTemplate.setName("会议记录"); - meetingTemplate.setContent("会议记录

" + - "会议主题
" + - "会议时间
" + - "会议地点
" + - "参会人员
" + - "主持人

" + - "会议议程
" + - "1.
" + - "2.
" + - "3.

" + - "会议内容

" + - "决议事项
" + - "1.
" + - "2.
" + - "3.

" + - "行动项
" + - "任务负责人截止日期状态

" + - "

" + - "下次会议
" + - "时间
" + - "主题
"); - meetingTemplate.setType(NoteTemplate.TYPE_SYSTEM); - mTemplates.add(meetingTemplate); - - // 待办事项模板 - NoteTemplate todoTemplate = new NoteTemplate(); - todoTemplate.setId(2); - todoTemplate.setName("待办事项"); - todoTemplate.setContent("待办事项

" + - "日期

" + - "今日待办
" + - "☐
" + - "☐
" + - "☐
" + - "☐
" + - "☐

" + - "重要事项
" + - "⭐
" + - "⭐

" + - "已完成
" + - "✓
" + - "✓
" + - "✓
"); - todoTemplate.setType(NoteTemplate.TYPE_SYSTEM); - mTemplates.add(todoTemplate); - - // 购物清单模板 - NoteTemplate shoppingTemplate = new NoteTemplate(); - shoppingTemplate.setId(3); - shoppingTemplate.setName("购物清单"); - shoppingTemplate.setContent("购物清单

" + - "日期
" + - "商店
" + - "预算

" + - "清单
" + - "物品数量单价备注状态
" + - " ☐
" + - " ☐
" + - " ☐
" + - " ☐
" + - " ☐

" + - "总计
" + - "实际花费
" + - "节省/超支
"); - shoppingTemplate.setType(NoteTemplate.TYPE_SYSTEM); - mTemplates.add(shoppingTemplate); - } - - /** - * 加载自定义模板 - */ - private void loadCustomTemplates() { - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); - String templatesJson = prefs.getString(PREF_TEMPLATES, "[]"); - - try { - JSONArray jsonArray = new JSONArray(templatesJson); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject json = jsonArray.getJSONObject(i); - NoteTemplate template = NoteTemplate.fromJson(json); - mTemplates.add(template); - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - - /** - * 保存自定义模板到SharedPreferences - */ - private void saveCustomTemplates() { - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); - SharedPreferences.Editor editor = prefs.edit(); - - JSONArray jsonArray = new JSONArray(); - for (NoteTemplate template : mTemplates) { - if (NoteTemplate.TYPE_CUSTOM.equals(template.getType())) { - try { - jsonArray.put(template.toJson()); - } catch (JSONException e) { - e.printStackTrace(); - } - } - } - - editor.putString(PREF_TEMPLATES, jsonArray.toString()); - editor.apply(); - } - - /** - * 获取所有模板 - */ - public List getAllTemplates() { - return new ArrayList<>(mTemplates); - } - - /** - * 获取系统模板 - */ - public List getSystemTemplates() { - List systemTemplates = new ArrayList<>(); - for (NoteTemplate template : mTemplates) { - if (NoteTemplate.TYPE_SYSTEM.equals(template.getType())) { - systemTemplates.add(template); - } - } - return systemTemplates; - } - - /** - * 获取自定义模板 - */ - public List getCustomTemplates() { - List customTemplates = new ArrayList<>(); - for (NoteTemplate template : mTemplates) { - if (NoteTemplate.TYPE_CUSTOM.equals(template.getType())) { - customTemplates.add(template); - } - } - return customTemplates; - } - - /** - * 根据ID获取模板 - */ - public NoteTemplate getTemplateById(long id) { - for (NoteTemplate template : mTemplates) { - if (template.getId() == id) { - return template; - } - } - return null; - } - - /** - * 添加自定义模板 - */ - public void addCustomTemplate(NoteTemplate template) { - // 生成唯一ID - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); - long id = prefs.getLong(PREF_TEMPLATE_ID_COUNTER, 1000); - - template.setId(id); - template.setType(NoteTemplate.TYPE_CUSTOM); - template.setCreateTime(System.currentTimeMillis()); - template.setUpdateTime(System.currentTimeMillis()); - - mTemplates.add(template); - - // 更新ID计数器 - prefs.edit().putLong(PREF_TEMPLATE_ID_COUNTER, id + 1).apply(); - - // 保存自定义模板 - saveCustomTemplates(); - } - - /** - * 删除自定义模板 - */ - public boolean deleteCustomTemplate(long id) { - NoteTemplate templateToRemove = null; - for (NoteTemplate template : mTemplates) { - if (template.getId() == id && NoteTemplate.TYPE_CUSTOM.equals(template.getType())) { - templateToRemove = template; - break; - } - } - - if (templateToRemove != null) { - mTemplates.remove(templateToRemove); - saveCustomTemplates(); - return true; - } - return false; - } - - /** - * 更新自定义模板 - */ - public boolean updateCustomTemplate(NoteTemplate updatedTemplate) { - for (int i = 0; i < mTemplates.size(); i++) { - NoteTemplate template = mTemplates.get(i); - if (template.getId() == updatedTemplate.getId() && - NoteTemplate.TYPE_CUSTOM.equals(template.getType())) { - - updatedTemplate.setUpdateTime(System.currentTimeMillis()); - mTemplates.set(i, updatedTemplate); - saveCustomTemplates(); - return true; - } - } - return false; - } -} diff --git a/src/main/java/net/micode/notes/model/WorkingNote.java b/src/main/java/net/micode/notes/model/WorkingNote.java deleted file mode 100644 index c495432..0000000 --- a/src/main/java/net/micode/notes/model/WorkingNote.java +++ /dev/null @@ -1,766 +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.appwidget.AppWidgetManager; -import android.content.ContentUris; -import android.content.Context; -import android.database.Cursor; -import android.text.TextUtils; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.CallNote; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.DataConstants; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.data.Notes.TextNote; -import net.micode.notes.tool.DataUtils; -import net.micode.notes.tool.ResourceParser.NoteBgResources; -import java.util.HashSet; - - -/** - * 工作笔记类,负责管理笔记的业务逻辑和UI状态。 - *

- * 该类是笔记应用的业务逻辑封装类,提供了笔记的创建、加载、保存等功能, - * 负责管理笔记的UI状态和业务逻辑,是UI层与数据层之间的桥梁。 - *

- */ -public class WorkingNote { - /** - * 内部笔记数据对象 - */ - private Note mNote; - - /** - * 笔记ID - */ - private long mNoteId; - - /** - * 笔记内容 - */ - private String mContent; - - /** - * 笔记模式(普通模式或清单模式) - */ - private int mMode; - - /** - * 提醒日期时间戳 - */ - private long mAlertDate; - - /** - * 最后修改日期时间戳 - */ - private long mModifiedDate; - - /** - * 背景颜色ID - */ - private int mBgColorId; - - /** - * 小部件ID - */ - private int mWidgetId; - - /** - * 小部件类型 - */ - private int mWidgetType; - - /** - * 文件夹ID - */ - private long mFolderId; - - /** - * 应用上下文 - */ - private Context mContext; - - /** - * 日志标签 - */ - private static final String TAG = WorkingNote.class.getSimpleName(); - - /** - * 删除标记 - */ - private boolean mIsDeleted; - - /** - * 笔记设置变更监听器 - */ - private NoteSettingChangedListener mNoteSettingStatusListener; - - /** - * 数据查询投影,用于从ContentResolver获取笔记数据 - */ - public static final String[] DATA_PROJECTION = new String[] { - DataColumns.ID, - DataColumns.CONTENT, - DataColumns.MIME_TYPE, - DataColumns.DATA1, - DataColumns.DATA2, - DataColumns.DATA3, - DataColumns.DATA4, - }; - - /** - * 笔记查询投影,用于从ContentResolver获取笔记基本信息 - */ - public static final String[] NOTE_PROJECTION = new String[] { - NoteColumns.PARENT_ID, - NoteColumns.ALERTED_DATE, - NoteColumns.BG_COLOR_ID, - NoteColumns.WIDGET_ID, - NoteColumns.WIDGET_TYPE, - NoteColumns.MODIFIED_DATE - }; - - /** - * 数据查询结果列索引:数据ID - */ - private static final int DATA_ID_COLUMN = 0; - - /** - * 数据查询结果列索引:数据内容 - */ - private static final int DATA_CONTENT_COLUMN = 1; - - /** - * 数据查询结果列索引:数据类型 - */ - private static final int DATA_MIME_TYPE_COLUMN = 2; - - /** - * 数据查询结果列索引:数据模式 - */ - private static final int DATA_MODE_COLUMN = 3; - - /** - * 笔记查询结果列索引:父文件夹ID - */ - private static final int NOTE_PARENT_ID_COLUMN = 0; - - /** - * 笔记查询结果列索引:提醒日期 - */ - private static final int NOTE_ALERTED_DATE_COLUMN = 1; - - /** - * 笔记查询结果列索引:背景颜色ID - */ - private static final int NOTE_BG_COLOR_ID_COLUMN = 2; - - /** - * 笔记查询结果列索引:小部件ID - */ - private static final int NOTE_WIDGET_ID_COLUMN = 3; - - /** - * 笔记查询结果列索引:小部件类型 - */ - private static final int NOTE_WIDGET_TYPE_COLUMN = 4; - - /** - * 笔记查询结果列索引:修改日期 - */ - private static final int NOTE_MODIFIED_DATE_COLUMN = 5; - - // New note construct - /** - * 构造新笔记的私有构造方法 - *

- * 初始化一个新的工作笔记对象,设置默认属性值。 - *

- * - * @param context 应用上下文 - * @param folderId 笔记所属文件夹ID - */ - private WorkingNote(Context context, long folderId) { - mContext = context; - mAlertDate = 0; - mModifiedDate = System.currentTimeMillis(); - mFolderId = folderId; - mNote = new Note(); - mNoteId = 0; - mIsDeleted = false; - mMode = 0; - mWidgetType = Notes.TYPE_WIDGET_INVALIDE; - } - - // Existing note construct - /** - * 构造现有笔记的私有构造方法 - *

- * 根据笔记ID初始化一个工作笔记对象,并从数据库加载笔记数据。 - *

- * - * @param context 应用上下文 - * @param noteId 笔记ID - * @param folderId 笔记所属文件夹ID - */ - private WorkingNote(Context context, long noteId, long folderId) { - mContext = context; - mNoteId = noteId; - mFolderId = folderId; - mIsDeleted = false; - mNote = new Note(); - loadNote(); - } - - /** - * 从数据库加载笔记基本信息 - *

- * 从ContentResolver中查询并加载笔记的基本信息,包括文件夹ID、背景颜色、 - * 小部件信息、提醒日期和修改日期等。 - *

- */ - private void loadNote() { - Cursor cursor = mContext.getContentResolver().query( - ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, - null, null); - - if (cursor != null) { - if (cursor.moveToFirst()) { - mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); - mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); - mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); - mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN); - mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN); - mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); - } - cursor.close(); - } else { - Log.e(TAG, "No note with id:" + mNoteId); - throw new IllegalArgumentException("Unable to find note with id " + mNoteId); - } - loadNoteData(); - } - - /** - * 从数据库加载笔记详细数据 - *

- * 从ContentResolver中查询并加载笔记的详细数据,包括文本内容和模式等。 - *

- */ - private void loadNoteData() { - Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, - DataColumns.NOTE_ID + "=?", new String[] { - String.valueOf(mNoteId) - }, null); - - if (cursor != null) { - if (cursor.moveToFirst()) { - do { - String type = cursor.getString(DATA_MIME_TYPE_COLUMN); - if (DataConstants.NOTE.equals(type)) { - mContent = cursor.getString(DATA_CONTENT_COLUMN); - mMode = cursor.getInt(DATA_MODE_COLUMN); - mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); - } else if (DataConstants.CALL_NOTE.equals(type)) { - mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); - } else { - Log.d(TAG, "Wrong note type with type:" + type); - } - } while (cursor.moveToNext()); - } - cursor.close(); - } else { - Log.e(TAG, "No data with id:" + mNoteId); - throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); - } - } - - /** - * 创建空笔记的静态工厂方法 - *

- * 创建一个新的空工作笔记对象,并设置默认属性值。 - *

- * - * @param context 应用上下文 - * @param folderId 笔记所属文件夹ID - * @param widgetId 小部件ID - * @param widgetType 小部件类型 - * @param defaultBgColorId 默认背景颜色ID - * @return 创建的空工作笔记 - */ - public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, - int widgetType, int defaultBgColorId) { - WorkingNote note = new WorkingNote(context, folderId); - note.setBgColorId(defaultBgColorId); - note.setWidgetId(widgetId); - note.setWidgetType(widgetType); - return note; - } - - /** - * 加载现有笔记的静态工厂方法 - *

- * 根据笔记ID加载一个现有的工作笔记对象。 - *

- * - * @param context 应用上下文 - * @param id 笔记ID - * @return 加载的工作笔记 - */ - public static WorkingNote load(Context context, long id) { - return new WorkingNote(context, id, 0); - } - - /** - * 保存笔记到数据库 - *

- * 将当前工作笔记保存到数据库中。如果笔记不存在,则创建新笔记; - * 如果笔记已存在,则更新现有笔记。 - * 如果笔记内容为空且已存在于数据库,则将其移动到回收站。 - *

- * - * @return 保存成功返回true,否则返回false - */ - public synchronized boolean saveNote() { - if (isWorthSaving()) { - if (!existInDatabase()) { - if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { - Log.e(TAG, "Create new note fail with id:" + mNoteId); - return false; - } - } - - mNote.syncNote(mContext, mNoteId); - - /** - * Update widget content if there exist any widget of this note - */ - if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID - && mWidgetType != Notes.TYPE_WIDGET_INVALIDE - && mNoteSettingStatusListener != null) { - mNoteSettingStatusListener.onWidgetChanged(); - } - return true; - } else { - // 添加删除逻辑:如果笔记内容为空且已存在于数据库,则将其移动到回收站 - if (existInDatabase() && TextUtils.isEmpty(mContent)) { - HashSet ids = new HashSet(); - ids.add(mNoteId); - // 无论是否在同步模式,都将空便签移动到回收站 - if (!DataUtils.batchMoveToFolder(mContext.getContentResolver(), ids, Notes.ID_TRASH_FOLER)) { - Log.e(TAG, "Move empty note to trash error"); - } - mIsDeleted = true; - } - return false; - } - } - - /** - * 检查笔记是否存在于数据库 - *

- * 检查当前工作笔记是否已存在于数据库中。 - *

- * - * @return 存在返回true,否则返回false - */ - public boolean existInDatabase() { - return mNoteId > 0; - } - - /** - * 检查笔记是否值得保存 - *

- * 检查当前工作笔记是否值得保存到数据库中。如果笔记已删除、 - * 内容为空,或者存在于数据库但未修改,则不值得保存。 - *

- * - * @return 值得保存返回true,否则返回false - */ - private boolean isWorthSaving() { - if (mIsDeleted || TextUtils.isEmpty(mContent) - || (existInDatabase() && !mNote.isLocalModified())) { - return false; - } else { - return true; - } - } - - /** - * 设置笔记设置变更监听器 - *

- * 设置笔记设置变更监听器,用于监听笔记设置的变化,如背景颜色、 - * 提醒日期、小部件等的变化。 - *

- * - * @param l 监听器实例 - */ - public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { - mNoteSettingStatusListener = l; - } - - /** - * 设置提醒日期 - *

- * 设置笔记的提醒日期,并通知监听器。 - *

- * - * @param date 提醒日期时间戳 - * @param set 是否设置提醒 - */ - public void setAlertDate(long date, boolean set) { - if (date != mAlertDate) { - mAlertDate = date; - mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); - } - if (mNoteSettingStatusListener != null) { - mNoteSettingStatusListener.onClockAlertChanged(date, set); - } - } - - /** - * 标记笔记是否删除 - *

- * 标记笔记是否已删除,并通知监听器。 - *

- * - * @param mark 删除标记 - */ - public void markDeleted(boolean mark) { - mIsDeleted = mark; - if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID - && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { - mNoteSettingStatusListener.onWidgetChanged(); - } - } - - /** - * 设置笔记背景颜色ID - *

- * 设置笔记的背景颜色ID,并通知监听器。 - *

- * - * @param id 背景颜色ID - */ - public void setBgColorId(int id) { - if (id != mBgColorId) { - mBgColorId = id; - if (mNoteSettingStatusListener != null) { - mNoteSettingStatusListener.onBackgroundColorChanged(); - } - mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); - } - } - - /** - * 设置笔记的清单模式 - *

- * 设置笔记的模式(普通模式或清单模式),并通知监听器。 - *

- * - * @param mode 清单模式 - */ - public void setCheckListMode(int mode) { - if (mMode != mode) { - if (mNoteSettingStatusListener != null) { - mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); - } - mMode = mode; - mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); - } - } - - /** - * 设置小部件类型 - *

- * 设置与当前笔记关联的小部件类型。 - *

- * - * @param type 小部件类型 - */ - public void setWidgetType(int type) { - if (type != mWidgetType) { - mWidgetType = type; - mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); - } - } - - /** - * 设置小部件ID - *

- * 设置与当前笔记关联的小部件ID。 - *

- * - * @param id 小部件ID - */ - public void setWidgetId(int id) { - if (id != mWidgetId) { - mWidgetId = id; - mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); - } - } - - /** - * 设置笔记的基本属性值 - *

- * 直接调用内部Note对象的setNoteValue方法,用于更新笔记的基本属性。 - *

- * - * @param key 属性键名,对应NoteColumns中的字段名 - * @param value 属性值 - */ - public void setNoteValue(String key, String value) { - mNote.setNoteValue(key, value); - } - - /** - * 设置笔记内容 - *

- * 设置笔记的文本内容,支持富文本格式。 - *

- * - * @param text 笔记内容,支持Spannable等富文本格式 - */ - public void setWorkingText(CharSequence text) { - String textStr = text.toString(); - if (!TextUtils.equals(mContent, textStr)) { - mContent = textStr; - mNote.setTextData(DataColumns.CONTENT, mContent); - } - } - - /** - * 设置笔记内容(字符串重载) - *

- * 设置笔记的文本内容。 - *

- * - * @param text 笔记内容 - */ - public void setWorkingText(String text) { - setWorkingText((CharSequence) text); - } - - /** - * 将笔记转换为通话笔记 - *

- * 将当前笔记转换为通话笔记,并设置通话相关信息,如电话号码和通话日期。 - *

- * - * @param phoneNumber 电话号码 - * @param callDate 通话日期 - */ - public void convertToCallNote(String phoneNumber, long callDate) { - mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); - mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); - mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); - } - - /** - * 检查笔记是否有闹钟提醒 - *

- * 检查当前笔记是否设置了提醒日期。 - *

- * - * @return 有提醒返回true,否则返回false - */ - public boolean hasClockAlert() { - return (mAlertDate > 0 ? true : false); - } - - /** - * 获取笔记内容 - *

- * 获取当前笔记的文本内容。 - *

- * - * @return 笔记内容 - */ - public String getContent() { - return mContent; - } - - /** - * 获取提醒日期 - *

- * 获取当前笔记的提醒日期时间戳。 - *

- * - * @return 提醒日期时间戳 - */ - public long getAlertDate() { - return mAlertDate; - } - - /** - * 获取修改日期 - *

- * 获取当前笔记的最后修改日期时间戳。 - *

- * - * @return 修改日期时间戳 - */ - public long getModifiedDate() { - return mModifiedDate; - } - - /** - * 获取背景颜色资源ID - *

- * 根据背景颜色ID获取对应的背景颜色资源ID。 - *

- * - * @return 背景颜色资源ID - */ - public int getBgColorResId() { - return NoteBgResources.getNoteBgResource(mBgColorId); - } - - /** - * 获取背景颜色ID - *

- * 获取当前笔记的背景颜色ID。 - *

- * - * @return 背景颜色ID - */ - public int getBgColorId() { - return mBgColorId; - } - - /** - * 获取标题背景资源ID - *

- * 根据背景颜色ID获取对应的标题背景资源ID。 - *

- * - * @return 标题背景资源ID - */ - public int getTitleBgResId() { - return NoteBgResources.getNoteTitleBgResource(mBgColorId); - } - - /** - * 获取清单模式 - *

- * 获取当前笔记的模式(普通模式或清单模式)。 - *

- * - * @return 清单模式 - */ - public int getCheckListMode() { - return mMode; - } - - /** - * 获取笔记ID - *

- * 获取当前笔记的ID。 - *

- * - * @return 笔记ID - */ - public long getNoteId() { - return mNoteId; - } - - /** - * 获取文件夹ID - *

- * 获取当前笔记所属的文件夹ID。 - *

- * - * @return 文件夹ID - */ - public long getFolderId() { - return mFolderId; - } - - /** - * 获取小部件ID - *

- * 获取与当前笔记关联的小部件ID。 - *

- * - * @return 小部件ID - */ - public int getWidgetId() { - return mWidgetId; - } - - /** - * 获取小部件类型 - *

- * 获取与当前笔记关联的小部件类型。 - *

- * - * @return 小部件类型 - */ - public int getWidgetType() { - return mWidgetType; - } - - /** - * 笔记设置变更监听器,用于监听笔记设置的变化。 - *

- * 该接口定义了笔记设置变化的回调方法,如背景颜色、提醒日期、 - * 小部件等的变化回调。 - *

- */ - public interface NoteSettingChangedListener { - /** - * 当笔记背景颜色改变时调用 - *

- * 当笔记的背景颜色发生变化时,会调用该方法。 - *

- */ - void onBackgroundColorChanged(); - - /** - * 当笔记闹钟设置改变时调用 - *

- * 当笔记的提醒日期发生变化时,会调用该方法。 - *

- * - * @param date 闹钟日期时间戳 - * @param set 是否设置闹钟 - */ - void onClockAlertChanged(long date, boolean set); - - /** - * 当笔记小部件改变时调用 - *

- * 当与笔记关联的小部件发生变化时,会调用该方法。 - *

- */ - void onWidgetChanged(); - - /** - * 当笔记在清单模式和普通模式之间切换时调用 - *

- * 当笔记的模式在普通模式和清单模式之间切换时,会调用该方法。 - *

- * - * @param oldMode 切换前的模式 - * @param newMode 切换后的新模式 - */ - void onCheckListModeChanged(int oldMode, int newMode); - } -} diff --git a/src/main/java/net/micode/notes/tool/BackupUtils.java b/src/main/java/net/micode/notes/tool/BackupUtils.java deleted file mode 100644 index 8f2e96e..0000000 --- a/src/main/java/net/micode/notes/tool/BackupUtils.java +++ /dev/null @@ -1,490 +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.database.Cursor; -import android.os.Environment; -import android.text.TextUtils; -import android.text.format.DateFormat; -import android.util.Log; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.DataConstants; -import net.micode.notes.data.Notes.NoteColumns; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; - - -/** - * 备份工具类,负责将笔记导出为文本文件。 - *

- * 该类采用单例模式实现,提供了将笔记内容导出为用户可读文本格式的功能, - * 支持将不同文件夹的笔记分类导出,并处理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/DataUtils.java b/src/main/java/net/micode/notes/tool/DataUtils.java deleted file mode 100644 index 6d84777..0000000 --- a/src/main/java/net/micode/notes/tool/DataUtils.java +++ /dev/null @@ -1,453 +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.ContentProviderOperation; -import android.content.ContentProviderResult; -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.OperationApplicationException; -import android.database.Cursor; -import android.os.RemoteException; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.CallNote; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; - -import java.util.ArrayList; -import java.util.HashSet; - - -/** - * 数据工具类,提供笔记数据的批量操作和查询功能。 - *

- * 该类包含了笔记数据的批量删除、移动、查询等静态方法, - * 主要用于处理笔记应用中的数据操作,与ContentResolver进行交互。 - *

- */ -public class DataUtils { - /** - * 日志标签 - */ - public static final String TAG = DataUtils.class.getSimpleName(); - /** - * 批量删除笔记 - *

- * 根据提供的笔记ID集合,批量删除对应的笔记。 - * 系统根文件夹(ID_ROOT_FOLDER)不会被删除。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param ids 要删除的笔记ID集合 - * @return 删除成功返回true,否则返回false - */ - public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { - if (ids == null) { - Log.d(TAG, "the ids is null"); - return true; - } - if (ids.size() == 0) { - Log.d(TAG, "no id is in the hashset"); - return true; - } - - ArrayList operationList = new ArrayList(); - for (long id : ids) { - if(id == Notes.ID_ROOT_FOLDER) { - Log.e(TAG, "Don't delete system folder root"); - continue; - } - ContentProviderOperation.Builder builder = ContentProviderOperation - .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); - operationList.add(builder.build()); - } - try { - ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); - if (results == null || results.length == 0 || results[0] == null) { - Log.d(TAG, "delete notes failed, ids:" + ids.toString()); - return false; - } - return true; - } catch (RemoteException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); - } catch (OperationApplicationException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); - } - return false; - } - - /** - * 将笔记移动到指定文件夹 - *

- * 更新笔记的父文件夹ID和原始父文件夹ID,并标记为本地修改。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param id 要移动的笔记ID - * @param srcFolderId 源文件夹ID - * @param desFolderId 目标文件夹ID - */ - public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { - ContentValues values = new ContentValues(); - values.put(NoteColumns.PARENT_ID, desFolderId); - values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); - values.put(NoteColumns.LOCAL_MODIFIED, 1); - resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); - } - - /** - * 批量将笔记移动到指定文件夹 - *

- * 根据提供的笔记ID集合,批量更新笔记的父文件夹ID。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param ids 要移动的笔记ID集合 - * @param folderId 目标文件夹ID - * @return 移动成功返回true,否则返回false - */ - public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, - long folderId) { - if (ids == null) { - Log.d(TAG, "the ids is null"); - return true; - } - - ArrayList operationList = new ArrayList(); - for (long id : ids) { - ContentProviderOperation.Builder builder = ContentProviderOperation - .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); - builder.withValue(NoteColumns.PARENT_ID, folderId); - builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); - operationList.add(builder.build()); - } - - try { - ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); - if (results == null || results.length == 0 || results[0] == null) { - Log.d(TAG, "delete notes failed, ids:" + ids.toString()); - return false; - } - return true; - } catch (RemoteException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); - } catch (OperationApplicationException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); - } - return false; - } - - /** - * 获取用户文件夹数量 - *

- * 查询并返回除系统文件夹外的所有用户文件夹数量。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @return 用户文件夹数量 - */ - public static int getUserFolderCount(ContentResolver resolver) { - Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI, - new String[] { "COUNT(*)" }, - NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", - new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, - null); - - int count = 0; - if(cursor != null) { - if(cursor.moveToFirst()) { - try { - count = cursor.getInt(0); - } catch (IndexOutOfBoundsException e) { - Log.e(TAG, "get folder count failed:" + e.toString()); - } finally { - cursor.close(); - } - } - } - return count; - } - - /** - * 检查笔记在数据库中是否可见 - *

- * 检查指定ID和类型的笔记是否存在于数据库中,且不在垃圾箱中。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param noteId 笔记ID - * @param type 笔记类型 - * @return 可见返回true,否则返回false - */ - public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { - Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), - null, - NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, - new String [] {String.valueOf(type)}, - null); - - boolean exist = false; - if (cursor != null) { - if (cursor.getCount() > 0) { - exist = true; - } - cursor.close(); - } - return exist; - } - - /** - * 检查笔记是否存在于数据库中 - *

- * 根据笔记ID检查笔记是否存在于数据库中。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param noteId 笔记ID - * @return 存在返回true,否则返回false - */ - public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { - Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), - null, null, null, null); - - boolean exist = false; - if (cursor != null) { - if (cursor.getCount() > 0) { - exist = true; - } - cursor.close(); - } - return exist; - } - - /** - * 检查数据是否存在于数据库中 - *

- * 根据数据ID检查数据是否存在于数据库中。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param dataId 数据ID - * @return 存在返回true,否则返回false - */ - public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { - Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), - null, null, null, null); - - boolean exist = false; - if (cursor != null) { - if (cursor.getCount() > 0) { - exist = true; - } - cursor.close(); - } - return exist; - } - - /** - * 检查可见文件夹名称是否存在 - *

- * 检查指定名称的文件夹是否存在于数据库中,且不在垃圾箱中。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param name 文件夹名称 - * @return 存在返回true,否则返回false - */ - public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { - return checkVisibleFolderName(resolver, name, Notes.ID_ROOT_FOLDER); - } - - /** - * 检查可见文件夹名称是否存在(重载方法,支持指定父文件夹ID) - *

- * 检查指定名称的文件夹是否存在于指定父文件夹下,且不在垃圾箱中。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param name 文件夹名称 - * @param parentId 父文件夹ID - * @return 存在返回true,否则返回false - */ - public static boolean checkVisibleFolderName(ContentResolver resolver, String name, long parentId) { - Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, - NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + - " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + - " AND " + NoteColumns.PARENT_ID + "=?" + - " AND " + NoteColumns.SNIPPET + "=?", - new String[] { String.valueOf(parentId), name }, null); - boolean exist = false; - if(cursor != null) { - if(cursor.getCount() > 0) { - exist = true; - } - cursor.close(); - } - return exist; - } - - /** - * 获取文件夹中笔记的小部件属性 - *

- * 查询并返回指定文件夹下所有笔记的小部件ID和类型。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param folderId 文件夹ID - * @return 小部件属性集合,如果没有则返回null - */ - public static HashSet getFolderNoteWidget(ContentResolver resolver, long folderId) { - Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, - new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, - NoteColumns.PARENT_ID + "=?", - new String[] { String.valueOf(folderId) }, - null); - - HashSet set = null; - if (c != null) { - if (c.moveToFirst()) { - set = new HashSet(); - do { - try { - AppWidgetAttribute widget = new AppWidgetAttribute(); - widget.widgetId = c.getInt(0); - widget.widgetType = c.getInt(1); - set.add(widget); - } catch (IndexOutOfBoundsException e) { - Log.e(TAG, e.toString()); - } - } while (c.moveToNext()); - } - c.close(); - } - return set; - } - - /** - * 根据笔记ID获取电话号码 - *

- * 查询并返回通话笔记中存储的电话号码。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param noteId 通话笔记ID - * @return 电话号码,如果没有则返回空字符串 - */ - public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { - Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, - new String [] { CallNote.PHONE_NUMBER }, - CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", - new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, - null); - - if (cursor != null && cursor.moveToFirst()) { - try { - return cursor.getString(0); - } catch (IndexOutOfBoundsException e) { - Log.e(TAG, "Get call number fails " + e.toString()); - } finally { - cursor.close(); - } - } - return ""; - } - - /** - * 根据电话号码和通话日期获取笔记ID - *

- * 查询并返回匹配指定电话号码和通话日期的通话笔记ID。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param phoneNumber 电话号码 - * @param callDate 通话日期时间戳 - * @return 笔记ID,如果没有找到则返回0 - */ - public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { - Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, - new String [] { CallNote.NOTE_ID }, - CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" - + CallNote.PHONE_NUMBER + ",?)", - new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, - null); - - if (cursor != null) { - if (cursor.moveToFirst()) { - try { - return cursor.getLong(0); - } catch (IndexOutOfBoundsException e) { - Log.e(TAG, "Get call note id fails " + e.toString()); - } - } - cursor.close(); - } - return 0; - } - - /** - * 根据笔记ID获取摘要 - *

- * 查询并返回指定笔记ID的摘要内容。 - * 如果笔记不存在,将抛出IllegalArgumentException异常。 - *

- * - * @param resolver ContentResolver实例,用于与内容提供者交互 - * @param noteId 笔记ID - * @return 笔记摘要 - * @throws IllegalArgumentException 如果笔记不存在 - */ - public static String getSnippetById(ContentResolver resolver, long noteId) { - Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, - new String [] { NoteColumns.SNIPPET }, - NoteColumns.ID + "=?", - new String [] { String.valueOf(noteId)}, - null); - - if (cursor != null) { - String snippet = ""; - if (cursor.moveToFirst()) { - snippet = cursor.getString(0); - } - cursor.close(); - return snippet; - } - throw new IllegalArgumentException("Note is not found with id: " + noteId); - } - - /** - * 格式化笔记摘要 - *

- * 对笔记摘要进行格式化处理,去除首尾空格,并只保留第一行内容。 - *

- * - * @param snippet 原始摘要内容 - * @return 格式化后的摘要内容 - */ - public static String getFormattedSnippet(String snippet) { - if (snippet != null) { - snippet = snippet.trim(); - int index = snippet.indexOf('\n'); - if (index != -1) { - snippet = snippet.substring(0, index); - } - } - return snippet; - } -} 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/ui/NoteEditActivity.java b/src/main/java/net/micode/notes/ui/NoteEditActivity.java deleted file mode 100644 index 184fe3b..0000000 --- a/src/main/java/net/micode/notes/ui/NoteEditActivity.java +++ /dev/null @@ -1,1389 +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.AlarmManager; -import android.app.AlertDialog; -import android.app.PendingIntent; -import android.app.SearchManager; -import android.appwidget.AppWidgetManager; -import android.content.ContentUris; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.SharedPreferences; -import android.graphics.Paint; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.text.Html; -import android.text.Spannable; -import android.text.SpannableString; -import android.text.TextUtils; -import android.text.format.DateUtils; -import android.text.style.BackgroundColorSpan; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.WindowManager; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.CompoundButton.OnCheckedChangeListener; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.database.Cursor; -import android.content.ContentResolver; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.NoteColumns; -import android.widget.LinearLayout; -import android.widget.TextView; -import android.widget.Toast; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.TextNote; -import net.micode.notes.model.WorkingNote; -import net.micode.notes.model.WorkingNote.NoteSettingChangedListener; -import net.micode.notes.tool.DataUtils; -import net.micode.notes.tool.ResourceParser; -import net.micode.notes.tool.ResourceParser.TextAppearanceResources; -import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener; -import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; -import net.micode.notes.widget.NoteWidgetProvider_2x; -import net.micode.notes.widget.NoteWidgetProvider_4x; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -/** - * 笔记编辑活动类,负责处理笔记的创建、编辑和保存操作。 - *

- * 该类实现了笔记编辑界面的所有功能,包括文本编辑、背景颜色设置、字体大小调整、 - * 提醒设置、分享等功能,同时支持普通文本模式和清单模式的切换。 - *

- */ -public class NoteEditActivity extends Activity implements OnClickListener, - NoteSettingChangedListener, OnTextViewChangeListener { - /** - * 头部视图持有者类,用于缓存头部视图的控件引用 - */ - private class HeadViewHolder { - public TextView tvModified; - - public ImageView ivAlertIcon; - - public TextView tvAlertDate; - - public ImageButton ibSetBgColor; - } - - /** 背景颜色选择按钮映射表,将按钮ID映射到颜色ID */ - private static final Map sBgSelectorBtnsMap = new HashMap(); - static { - sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); - sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); - sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); - sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); - sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); - } - - /** 背景颜色选择高亮映射表,将颜色ID映射到高亮视图ID */ - private static final Map sBgSelectorSelectionMap = new HashMap(); - static { - sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); - sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); - sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); - sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); - sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); - } - - /** 字体大小按钮映射表,将按钮ID映射到字体大小ID */ - private static final Map sFontSizeBtnsMap = new HashMap(); - static { - sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); - sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); - sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); - sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); - } - - /** 字体大小选择高亮映射表,将字体大小ID映射到高亮视图ID */ - private static final Map sFontSelectorSelectionMap = new HashMap(); - static { - sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); - sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); - sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select); - sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); - } - - /** 日志标签 */ - private static final String TAG = "NoteEditActivity"; - - /** 头部视图持有者 */ - private HeadViewHolder mNoteHeaderHolder; - - /** 头部视图面板 */ - private View mHeadViewPanel; - - /** 粗体按钮 */ - private Button mBtnBold; - /** 斜体按钮 */ - private Button mBtnItalic; - /** 下划线按钮 */ - private Button mBtnUnderline; - /** 字体颜色按钮 */ - private Button mBtnTextColor; - - /** 背景颜色选择器视图 */ - private View mNoteBgColorSelector; - /** 字体颜色选择器视图 */ - private View mNoteTextColorSelector; - - /** 字体大小选择器视图 */ - private View mFontSizeSelector; - - /** 笔记编辑文本框 */ - private NoteEditText mNoteEditor; - - /** 笔记编辑面板 */ - private View mNoteEditorPanel; - - /** 工作笔记对象,用于处理笔记数据 */ - private WorkingNote mWorkingNote; - - /** 共享偏好设置 */ - private SharedPreferences mSharedPrefs; - /** 字体大小ID */ - private int mFontSizeId; - - /** 字体大小偏好设置键 */ - private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; - - /** 快捷图标标题最大长度 */ - private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; - - /** 已选中标记 */ - public static final String TAG_CHECKED = String.valueOf('\u221A'); - /** 未选中标记 */ - public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); - - /** 清单模式下的编辑文本列表 */ - private LinearLayout mEditTextList; - - /** 用户查询字符串 */ - private String mUserQuery; - /** 查询正则表达式模式 */ - private Pattern mPattern; - - /** - * 活动创建时调用,初始化界面和状态 - * - * @param savedInstanceState 保存的实例状态 - */ - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - this.setContentView(R.layout.note_edit); - - if (savedInstanceState == null && !initActivityState(getIntent())) { - finish(); - return; - } - initResources(); - } - - /** - * Current activity may be killed when the memory is low. Once it is killed, for another time - * user load this activity, we should restore the former state - */ - @Override - protected void onRestoreInstanceState(Bundle savedInstanceState) { - super.onRestoreInstanceState(savedInstanceState); - if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); - if (!initActivityState(intent)) { - finish(); - return; - } - Log.d(TAG, "Restoring from killed activity"); - } - } - - /** - * 初始化活动状态,根据传入的Intent处理不同的操作 - * - * @param intent 包含操作信息的Intent - * @return 初始化是否成功 - */ - private boolean initActivityState(Intent intent) { - /** - * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id, - * then jump to the NotesListActivity - */ - mWorkingNote = null; - if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { - long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); - mUserQuery = ""; - - /** - * Starting from the searched result - */ - if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) { - noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); - mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); - } - - if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { - Intent jump = new Intent(this, NotesListActivity.class); - startActivity(jump); - showToast(R.string.error_note_not_exist); - finish(); - return false; - } else { - mWorkingNote = WorkingNote.load(this, noteId); - if (mWorkingNote == null) { - Log.e(TAG, "load note failed with note id" + noteId); - finish(); - return false; - } - } - getWindow().setSoftInputMode( - WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN - | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); - } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) { - // New note - long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); - int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, - AppWidgetManager.INVALID_APPWIDGET_ID); - int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, - Notes.TYPE_WIDGET_INVALIDE); - int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, - ResourceParser.getDefaultBgId(this)); - - // Parse call-record note - String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); - long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0); - if (callDate != 0 && phoneNumber != null) { - if (TextUtils.isEmpty(phoneNumber)) { - Log.w(TAG, "The call record number is null"); - } - long noteId = 0; - if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(), - phoneNumber, callDate)) > 0) { - mWorkingNote = WorkingNote.load(this, noteId); - if (mWorkingNote == null) { - Log.e(TAG, "load call note failed with note id" + noteId); - finish(); - return false; - } - } else { - mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, - widgetType, bgResId); - mWorkingNote.convertToCallNote(phoneNumber, callDate); - } - } else { - mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, - bgResId); - } - - getWindow().setSoftInputMode( - WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE - | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); - } else { - Log.e(TAG, "Intent not specified action, should not support"); - finish(); - return false; - } - mWorkingNote.setOnSettingStatusChangedListener(this); - return true; - } - - /** - * 活动恢复时调用,初始化笔记屏幕 - */ - @Override - protected void onResume() { - super.onResume(); - initNoteScreen(); - } - - /** - * 初始化笔记屏幕显示,包括字体样式、显示模式、背景颜色等 - */ - private void initNoteScreen() { - mNoteEditor.setTextAppearance(this, TextAppearanceResources - .getTexAppearanceResource(mFontSizeId)); - if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { - switchToListMode(mWorkingNote.getContent()); - } else { - // 解析HTML格式的富文本内容,添加null检查防止闪退 - String content = mWorkingNote.getContent(); - CharSequence htmlContent = Html.fromHtml(content == null ? "" : content); - mNoteEditor.setText(getHighlightQueryResult(htmlContent, mUserQuery)); - mNoteEditor.setSelection(mNoteEditor.getText().length()); - } - for (Integer id : sBgSelectorSelectionMap.keySet()) { - findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); - } - mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); - mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); - - mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, - mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE - | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME - | DateUtils.FORMAT_SHOW_YEAR)); - - /** - * TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker - * is not ready - */ - showAlertHeader(); - } - - /** - * 显示提醒头部信息,包括提醒图标和提醒时间 - */ - private void showAlertHeader() { - if (mWorkingNote.hasClockAlert()) { - long time = System.currentTimeMillis(); - if (time > mWorkingNote.getAlertDate()) { - mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); - } else { - mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( - mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS)); - } - mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); - mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); - } else { - mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); - mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); - }; - } - - /** - * 处理活动收到的新Intent - * - * @param intent 新的Intent对象 - */ - @Override - protected void onNewIntent(Intent intent) { - super.onNewIntent(intent); - initActivityState(intent); - } - - /** - * 保存活动状态,当活动可能被销毁时调用 - * - * @param outState 用于保存状态的Bundle对象 - */ - @Override - protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - /** - * For new note without note id, we should firstly save it to - * generate a id. If the editing note is not worth saving, there - * is no id which is equivalent to create new note - */ - if (!mWorkingNote.existInDatabase()) { - saveNote(); - } - outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); - Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); - } - - /** - * 分发触摸事件,当点击外部区域时关闭颜色选择器和字体大小选择器 - * - * @param ev 触摸事件对象 - * @return 事件是否被消费 - */ - @Override - public boolean dispatchTouchEvent(MotionEvent ev) { - if (mNoteBgColorSelector.getVisibility() == View.VISIBLE - && !inRangeOfView(mNoteBgColorSelector, ev)) { - mNoteBgColorSelector.setVisibility(View.GONE); - return true; - } - - if (mNoteTextColorSelector.getVisibility() == View.VISIBLE - && !inRangeOfView(mNoteTextColorSelector, ev)) { - mNoteTextColorSelector.setVisibility(View.GONE); - return true; - } - - if (mFontSizeSelector.getVisibility() == View.VISIBLE - && !inRangeOfView(mFontSizeSelector, ev)) { - mFontSizeSelector.setVisibility(View.GONE); - return true; - } - return super.dispatchTouchEvent(ev); - } - - /** - * 检查触摸事件是否在指定视图范围内 - * - * @param view 要检查的视图 - * @param ev 触摸事件对象 - * @return 触摸事件是否在视图范围内 - */ - private boolean inRangeOfView(View view, MotionEvent ev) { - int []location = new int[2]; - view.getLocationOnScreen(location); - int x = location[0]; - int y = location[1]; - if (ev.getX() < x - || ev.getX() > (x + view.getWidth()) - || ev.getY() < y - || ev.getY() > (y + view.getHeight())) { - return false; - } - return true; - } - - /** - * 初始化资源,包括视图、事件监听器等 - */ - private void initResources() { - mHeadViewPanel = findViewById(R.id.note_title); - mNoteHeaderHolder = new HeadViewHolder(); - mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); - mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); - mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); - mNoteHeaderHolder.ibSetBgColor = (ImageButton) findViewById(R.id.btn_set_bg_color); - mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); - mNoteEditor = (NoteEditText) findViewById(R.id.note_edit_view); - mNoteEditorPanel = findViewById(R.id.sv_note_edit); - mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector); - for (int id : sBgSelectorBtnsMap.keySet()) { - ImageView iv = (ImageView) findViewById(id); - iv.setOnClickListener(this); - } - - // 初始化富文本按钮 - mBtnBold = findViewById(R.id.btn_bold); - mBtnItalic = findViewById(R.id.btn_italic); - mBtnUnderline = findViewById(R.id.btn_underline); - mBtnTextColor = findViewById(R.id.btn_set_text_color); - mBtnBold.setOnClickListener(this); - mBtnItalic.setOnClickListener(this); - mBtnUnderline.setOnClickListener(this); - mBtnTextColor.setOnClickListener(this); - - mFontSizeSelector = findViewById(R.id.font_size_selector); - mNoteTextColorSelector = findViewById(R.id.note_text_color_selector); - - // 初始化字体颜色选择器的颜色选项 - ImageView ivTextBlack = findViewById(R.id.iv_text_black); - ImageView ivTextWhite = findViewById(R.id.iv_text_white); - ImageView ivTextRed = findViewById(R.id.iv_text_red); - ImageView ivTextBlue = findViewById(R.id.iv_text_blue); - ivTextBlack.setOnClickListener(this); - ivTextWhite.setOnClickListener(this); - ivTextRed.setOnClickListener(this); - ivTextBlue.setOnClickListener(this); - for (int id : sFontSizeBtnsMap.keySet()) { - View view = findViewById(id); - view.setOnClickListener(this); - }; - mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); - mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); - /** - * 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(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { - mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; - } - mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); - - // 将光标改为文本选中光标 - mNoteEditor.setTextIsSelectable(true); - } - - /** - * 活动暂停时调用,保存笔记并清除设置状态 - */ - @Override - protected void onPause() { - super.onPause(); - if(saveNote()) { - Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length()); - } - clearSettingState(); - } - - /** - * 更新小组件,根据笔记的小组件类型发送更新广播 - */ - private void updateWidget() { - Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { - intent.setClass(this, NoteWidgetProvider_2x.class); - } else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) { - intent.setClass(this, NoteWidgetProvider_4x.class); - } else { - Log.e(TAG, "Unspported widget type"); - return; - } - - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { - mWorkingNote.getWidgetId() - }); - - sendBroadcast(intent); - setResult(RESULT_OK, intent); - } - - /** - * 处理视图的点击事件 - * - * @param v 被点击的视图对象 - */ - public void onClick(View v) { - int id = v.getId(); - if (id == R.id.btn_set_bg_color) { - // 显示背景颜色选择器,隐藏其他选择器 - mNoteBgColorSelector.setVisibility(View.VISIBLE); - mNoteTextColorSelector.setVisibility(View.GONE); - findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( - View.VISIBLE); - } else if (id == R.id.btn_set_text_color) { - // 显示字体颜色选择器,隐藏其他选择器 - mNoteTextColorSelector.setVisibility(View.VISIBLE); - mNoteBgColorSelector.setVisibility(View.GONE); - } else if (sBgSelectorBtnsMap.containsKey(id)) { - // 处理背景颜色选择 - findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( - View.GONE); - mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); - mNoteBgColorSelector.setVisibility(View.GONE); - } else if (id == R.id.iv_text_black) { - // 应用黑色字体 - mNoteEditor.applyTextColor(0xFF000000); - mNoteTextColorSelector.setVisibility(View.GONE); - } else if (id == R.id.iv_text_white) { - // 应用白色字体 - mNoteEditor.applyTextColor(0xFFFFFFFF); - mNoteTextColorSelector.setVisibility(View.GONE); - } else if (id == R.id.iv_text_red) { - // 应用红色字体 - mNoteEditor.applyTextColor(0xFFFF0000); - mNoteTextColorSelector.setVisibility(View.GONE); - } else if (id == R.id.iv_text_blue) { - // 应用蓝色字体 - mNoteEditor.applyTextColor(0xFF0000FF); - mNoteTextColorSelector.setVisibility(View.GONE); - } else if (sFontSizeBtnsMap.containsKey(id)) { - // 处理字体大小选择 - findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); - mFontSizeId = sFontSizeBtnsMap.get(id); - mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); - findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); - if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { - getWorkingText(); - switchToListMode(mWorkingNote.getContent()); - } else { - mNoteEditor.setTextAppearance(this, - TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); - } - mFontSizeSelector.setVisibility(View.GONE); - } else if (id == R.id.btn_bold) { - // 应用粗体 - mNoteEditor.applyBold(); - } else if (id == R.id.btn_italic) { - // 应用斜体 - mNoteEditor.applyItalic(); - } else if (id == R.id.btn_underline) { - // 应用下划线 - mNoteEditor.applyUnderline(); - } - } - - /** - * 处理返回按钮点击事件 - *

- * 先尝试清除设置状态,如果成功则不执行返回操作,否则保存笔记并执行返回 - *

- */ - @Override - public void onBackPressed() { - if(clearSettingState()) { - return; - } - - saveNote(); - super.onBackPressed(); - } - - /** - * 清除设置状态,隐藏所有设置选择器 - * - * @return 如果有设置选择器被隐藏,则返回true;否则返回false - */ - private boolean clearSettingState() { - if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { - mNoteBgColorSelector.setVisibility(View.GONE); - return true; - } else if (mNoteTextColorSelector.getVisibility() == View.VISIBLE) { - mNoteTextColorSelector.setVisibility(View.GONE); - return true; - } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) { - mFontSizeSelector.setVisibility(View.GONE); - return true; - } - return false; - } - - /** - * 背景颜色改变时调用的回调方法 - *

- * 显示当前选中的背景颜色,并更新头部面板和编辑面板的背景资源 - *

- */ - public void onBackgroundColorChanged() { - findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( - View.VISIBLE); - mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); - mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); - } - - /** - * 准备选项菜单,在菜单显示前调用 - *

- * 根据笔记类型和当前状态动态配置菜单项,包括加载不同的菜单资源、 - * 设置菜单标题和控制菜单项的可见性 - *

- * - * @param menu 要准备的菜单对象 - * @return 是否成功准备菜单 - */ - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - if (isFinishing()) { - return true; - } - clearSettingState(); - menu.clear(); - if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { - getMenuInflater().inflate(R.menu.call_note_edit, menu); - } else { - getMenuInflater().inflate(R.menu.note_edit, menu); - } - if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { - menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); - } else { - menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); - } - if (mWorkingNote.hasClockAlert()) { - menu.findItem(R.id.menu_alert).setVisible(false); - } else { - menu.findItem(R.id.menu_delete_remind).setVisible(false); - } - return true; - } - - /** - * 处理菜单选项选择事件 - *

- * 该方法处理各种菜单选项的点击事件,包括创建新笔记、删除笔记、设置字体大小、 - * 切换列表模式、分享笔记、发送到桌面、设置提醒等功能 - *

- * @param item 被选择的菜单项 - * @return 总是返回true,表示事件已被处理 - */ - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.menu_new_note: - createNewNote(); - break; - case R.id.menu_delete: - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle(getString(R.string.alert_title_delete)); - builder.setIcon(android.R.drawable.ic_dialog_alert); - builder.setMessage(getString(R.string.alert_message_delete_note)); - builder.setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - deleteCurrentNote(); - finish(); - } - }); - builder.setNegativeButton(android.R.string.cancel, null); - builder.show(); - break; - case R.id.menu_font_size: - mFontSizeSelector.setVisibility(View.VISIBLE); - findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); - break; - case R.id.menu_list_mode: - mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ? - TextNote.MODE_CHECK_LIST : 0); - break; - case R.id.menu_share: - getWorkingText(); - sendTo(this, mWorkingNote.getContent()); - break; - case R.id.menu_send_to_desktop: - sendToDesktop(); - break; - case R.id.menu_alert: - setReminder(); - break; - case R.id.menu_delete_remind: - mWorkingNote.setAlertDate(0, false); - break; - case R.id.menu_lock: - showPasswordDialogForLock(); - break; - case R.id.menu_unlock: - showPasswordDialogForUnlock(); - break; - default: - break; - } - return true; - } - - /** - * 设置笔记的提醒时间 - *

- * 该方法显示一个日期时间选择对话框,让用户选择提醒时间, - * 并将选择的时间设置到当前编辑的笔记中 - *

- */ - private void setReminder() { - DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); - d.setOnDateTimeSetListener(new OnDateTimeSetListener() { - public void OnDateTimeSet(AlertDialog dialog, long date) { - mWorkingNote.setAlertDate(date , true); - } - }); - d.show(); - } - - /** - * 分享笔记到支持{@link Intent#ACTION_SEND}动作和{@text/plain}类型的应用 - *

- * 该方法创建一个分享意图,将笔记内容发送给其他支持文本分享的应用程序 - *

- * @param context 上下文对象 - * @param info 要分享的笔记内容 - */ - private void sendTo(Context context, String info) { - Intent intent = new Intent(Intent.ACTION_SEND); - intent.putExtra(Intent.EXTRA_TEXT, info); - intent.setType("text/plain"); - context.startActivity(intent); - } - - /** - * 显示密码输入对话框用于锁定笔记 - *

- * 该方法用于显示一个密码输入对话框,让用户输入密码来锁定当前编辑的笔记 - *

- */ - private void showPasswordDialogForLock() { - final EditText passwordEditText = new EditText(this); - passwordEditText.setHint(R.string.hint_enter_password); - passwordEditText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); - - new AlertDialog.Builder(this) - .setTitle(R.string.dialog_enter_password) - .setView(passwordEditText) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - String password = passwordEditText.getText().toString(); - if (!TextUtils.isEmpty(password)) { - lockCurrentNote(password); - } - } - }) - .setNegativeButton(android.R.string.cancel, null) - .show(); - } - - /** - * 显示密码输入对话框用于解锁笔记 - *

- * 该方法用于显示一个密码输入对话框,让用户输入密码来解锁当前编辑的笔记 - *

- */ - private void showPasswordDialogForUnlock() { - final EditText passwordEditText = new EditText(this); - passwordEditText.setHint(R.string.hint_enter_password); - passwordEditText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); - - new AlertDialog.Builder(this) - .setTitle(R.string.dialog_enter_password) - .setView(passwordEditText) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - String password = passwordEditText.getText().toString(); - if (!TextUtils.isEmpty(password)) { - unlockCurrentNote(password); - } - } - }) - .setNegativeButton(android.R.string.cancel, null) - .show(); - } - - /** - * 锁定当前笔记 - *

- * 该方法用于锁定当前编辑的笔记,更新其锁定状态、密码和锁定类型 - *

- * @param password 用于锁定的密码 - */ - private void lockCurrentNote(String password) { - // 设置锁定状态为1(已锁定) - mWorkingNote.setNoteValue(NoteColumns.IS_LOCKED, "1"); - // 设置加密后的密码 - mWorkingNote.setNoteValue(NoteColumns.LOCK_PASSWORD, encryptPassword(password)); - // 设置锁定类型为笔记类型 - mWorkingNote.setNoteValue(NoteColumns.LOCK_TYPE, String.valueOf(Notes.LOCK_TYPE_NOTE)); - // 保存笔记 - saveNote(); - // 显示提示信息 - Toast.makeText(this, getString(R.string.message_note_locked), Toast.LENGTH_SHORT).show(); - } - - /** - * 解锁当前笔记 - *

- * 该方法用于解锁当前编辑的笔记,更新其锁定状态和密码 - *

- * @param password 用于解锁的密码 - */ - private void unlockCurrentNote(String password) { - // 使用ContentResolver直接查询数据库获取加密密码 - String[] projection = {NoteColumns.LOCK_PASSWORD}; - String selection = NoteColumns.ID + "=?"; - String[] selectionArgs = {String.valueOf(mWorkingNote.getNoteId())}; - - Cursor cursor = getContentResolver().query(Notes.CONTENT_NOTE_URI, projection, selection, selectionArgs, null); - String encryptedPassword = null; - - if (cursor != null && cursor.moveToFirst()) { - encryptedPassword = cursor.getString(0); - cursor.close(); - } - - // 验证密码是否正确 - if (encryptedPassword != null && encryptedPassword.equals(encryptPassword(password))) { - // 密码正确,设置锁定状态为0(未锁定) - mWorkingNote.setNoteValue(NoteColumns.IS_LOCKED, "0"); - // 清空密码 - mWorkingNote.setNoteValue(NoteColumns.LOCK_PASSWORD, ""); - // 保存笔记 - saveNote(); - // 显示提示信息 - Toast.makeText(this, getString(R.string.message_note_unlocked), Toast.LENGTH_SHORT).show(); - } else { - // 密码错误,显示错误信息 - Toast.makeText(this, getString(R.string.error_wrong_password), Toast.LENGTH_SHORT).show(); - } - } - - /** - * 加密密码 - *

- * 该方法使用Base64和ANDROID_ID对密码进行加密 - *

- * @param password 原始密码 - * @return 加密后的密码 - */ - private String encryptPassword(String password) { - try { - // 获取设备的ANDROID_ID作为加密密钥 - String androidId = android.provider.Settings.Secure.getString(getContentResolver(), - android.provider.Settings.Secure.ANDROID_ID); - // 使用简单的加密算法:将密码与ANDROID_ID拼接后进行Base64编码 - String combined = password + androidId; - return android.util.Base64.encodeToString(combined.getBytes(), android.util.Base64.DEFAULT); - } catch (Exception e) { - Log.e(TAG, "Password encryption failed", e); - return password; // 加密失败时返回原始密码 - } - } - - /** - * 创建新笔记 - *

- * 该方法先保存当前编辑的笔记,然后结束当前活动并启动一个新的NoteEditActivity - * 来创建新笔记,确保笔记保存在同一文件夹中 - *

- */ - private void createNewNote() { - // Firstly, save current editing notes - saveNote(); - - // For safety, start a new NoteEditActivity - finish(); - Intent intent = new Intent(this, NoteEditActivity.class); - intent.setAction(Intent.ACTION_INSERT_OR_EDIT); - intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); - startActivity(intent); - } - - /** - * 删除当前编辑的笔记 - *

- * 该方法根据笔记是否存在于数据库中进行处理: - * 1. 如果笔记存在,将其ID添加到待删除列表 - * 2. 如果不是同步模式,直接删除笔记 - * 3. 如果是同步模式,将笔记移动到垃圾桶 - *

- */ - private void deleteCurrentNote() { - if (mWorkingNote.existInDatabase()) { - HashSet ids = new HashSet(); - long id = mWorkingNote.getNoteId(); - if (id != Notes.ID_ROOT_FOLDER) { - ids.add(id); - } else { - Log.d(TAG, "Wrong note id, should not happen"); - } - if (!isSyncMode()) { - if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) { - Log.e(TAG, "Delete Note error"); - } - } else { - if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) { - Log.e(TAG, "Move notes to trash folder error, should not happens"); - } - } - } - mWorkingNote.markDeleted(true); - } - - /** - * 检查是否启用了同步模式 - *

- * 该方法通过检查同步账户名称是否存在来判断是否启用了同步模式 - *

- * @return 如果启用了同步模式返回true,否则返回false - */ - private boolean isSyncMode() { - return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; - } - - /** - * 处理时钟提醒的变化 - *

- * 该方法用于设置或取消笔记的时钟提醒, - * 如果笔记未保存,会先保存笔记,然后根据参数设置或取消闹钟 - *

- * @param date 提醒时间的时间戳 - * @param set 如果为true则设置提醒,为false则取消提醒 - */ - public void onClockAlertChanged(long date, boolean set) { - // 用户可能会为未保存的笔记设置时钟,所以在设置提醒时钟之前,我们应该先保存笔记 - if (!mWorkingNote.existInDatabase()) { - saveNote(); - } - if (mWorkingNote.getNoteId() > 0) { - Intent intent = new Intent(this, AlarmReceiver.class); - intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId())); - PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); - AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE)); - showAlertHeader(); - if(!set) { - alarmManager.cancel(pendingIntent); - } else { - alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); - } - } else { - /** - * There is the condition that user has input nothing (the note is - * not worthy saving), we have no note id, remind the user that he - * should input something - */ - Log.e(TAG, "Clock alert setting error"); - showToast(R.string.error_note_empty_for_clock); - } - } - - /** - * 更新小部件 - *

- * 该方法调用updateWidget()方法来更新桌面小部件的内容 - *

- */ - public void onWidgetChanged() { - updateWidget(); - } - - /** - * 处理编辑文本的删除操作 - *

- * 该方法处理用户在编辑文本时按下删除键的操作,特别是在列表模式下: - * 1. 检查是否只有一个编辑文本项,如果是则直接返回 - * 2. 将索引大于当前删除项的所有编辑文本项的索引减1 - * 3. 从列表中移除指定索引的视图 - * 4. 将被删除的文本追加到前一个或第一个编辑文本项中 - * 5. 设置焦点并将光标移动到追加文本的开始位置 - *

- * @param index 要删除的编辑文本项的索引 - * @param text 被删除的文本内容 - */ - public void onEditTextDelete(int index, String text) { - int childCount = mEditTextList.getChildCount(); - if (childCount == 1) { - return; - } - - for (int i = index + 1; i < childCount; i++) { - ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) - .setIndex(i - 1); - } - - mEditTextList.removeViewAt(index); - NoteEditText edit = null; - if(index == 0) { - edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById( - R.id.et_edit_text); - } else { - edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById( - R.id.et_edit_text); - } - int length = edit.length(); - edit.append(text); - edit.requestFocus(); - edit.setSelection(length); - } - - /** - * 处理编辑文本的回车操作 - *

- * 该方法处理用户在编辑文本时按下回车键的操作,在指定索引位置插入新的编辑文本项 - *

- * @param index 插入新编辑文本项的索引位置 - * @param text 新编辑文本项的内容 - */ - public void onEditTextEnter(int index, String text) { - // 不应该发生的情况,用于调试检查 - if(index > mEditTextList.getChildCount()) { - Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); - } - - View view = getListItem(text, index); - mEditTextList.addView(view, index); - NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); - edit.requestFocus(); - edit.setSelection(0); - for (int i = index + 1; i < mEditTextList.getChildCount(); i++) { - ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) - .setIndex(i); - } - } - - /** - * 切换到列表模式 - *

- * 该方法将笔记从普通文本模式切换到列表模式, - * 将文本内容按行分割并创建对应的列表项,最后添加一个空的列表项用于继续输入 - *

- * @param text 当前笔记的文本内容 - */ - private void switchToListMode(String text) { - mEditTextList.removeAllViews(); - String[] items = text.split("\n"); - int index = 0; - for (String item : items) { - if(!TextUtils.isEmpty(item)) { - mEditTextList.addView(getListItem(item, index)); - index++; - } - } - mEditTextList.addView(getListItem("", index)); - mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); - - mNoteEditor.setVisibility(View.GONE); - mEditTextList.setVisibility(View.VISIBLE); - } - - /** - * 获取带有高亮查询结果的文本 - *

- * 该方法在完整文本中查找用户查询的内容,并为匹配项添加背景高亮效果 - *

- * @param fullText 完整的文本内容,支持CharSequence类型 - * @param userQuery 用户查询的内容 - * @return 带有高亮查询结果的Spannable对象 - */ - private Spannable getHighlightQueryResult(CharSequence fullText, String userQuery) { - SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); - if (!TextUtils.isEmpty(userQuery)) { - mPattern = Pattern.compile(userQuery); - Matcher m = mPattern.matcher(fullText); - int start = 0; - while (m.find(start)) { - spannable.setSpan( - new BackgroundColorSpan(this.getResources().getColor( - R.color.user_query_highlight)), m.start(), m.end(), - Spannable.SPAN_INCLUSIVE_EXCLUSIVE); - start = m.end(); - } - } - return spannable; - } - - /** - * 获取列表模式下的列表项视图 - *

- * 该方法创建并配置列表模式下的列表项视图,包括: - * 1. 加载列表项布局 - * 2. 设置编辑文本的字体大小 - * 3. 配置复选框的选中状态变化监听器 - * 4. 根据项目文本的标签设置初始选中状态和文本样式 - * 5. 设置文本变化监听器和索引 - * 6. 应用查询高亮效果 - *

- * @param item 列表项的文本内容 - * @param index 列表项的索引 - * @return 配置好的列表项视图 - */ - private View getListItem(String item, int index) { - View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); - final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); - edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); - CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); - cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); - } else { - edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); - } - } - }); - - if (item.startsWith(TAG_CHECKED)) { - cb.setChecked(true); - edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); - item = item.substring(TAG_CHECKED.length(), item.length()).trim(); - } else if (item.startsWith(TAG_UNCHECKED)) { - cb.setChecked(false); - edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); - item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); - } - - edit.setOnTextViewChangeListener(this); - edit.setIndex(index); - edit.setText(getHighlightQueryResult(item, mUserQuery)); - return view; - } - - /** - * 处理文本变化事件 - *

- * 该方法在列表模式下处理编辑文本的内容变化事件, - * 根据文本是否为空来控制对应列表项中复选框的显示或隐藏 - *

- * @param index 编辑文本项的索引 - * @param hasText 编辑文本是否包含内容 - */ - public void onTextChange(int index, boolean hasText) { - if (index >= mEditTextList.getChildCount()) { - Log.e(TAG, "Wrong index, should not happen"); - return; - } - if(hasText) { - mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE); - } else { - mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE); - } - } - - /** - * 处理检查列表模式的变化 - *

- * 该方法在笔记的普通文本模式和检查列表模式之间切换时被调用, - * 根据新的模式执行相应的视图切换和数据处理操作 - *

- * @param oldMode 旧的模式 - * @param newMode 新的模式 - */ - public void onCheckListModeChanged(int oldMode, int newMode) { - if (newMode == TextNote.MODE_CHECK_LIST) { - switchToListMode(mNoteEditor.getText().toString()); - } else { - if (!getWorkingText()) { - mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ", - "")); - } - mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); - mEditTextList.setVisibility(View.GONE); - mNoteEditor.setVisibility(View.VISIBLE); - } - } - - /** - * 获取当前工作笔记的文本内容 - *

- * 该方法根据当前笔记的模式(普通文本或检查列表)获取相应的文本内容: - * 1. 如果是检查列表模式,遍历所有列表项,收集文本内容并添加相应的标签(已完成或未完成) - * 2. 如果是普通文本模式,直接获取编辑框的文本内容 - *

- * @return 是否包含已完成的列表项 - */ - private boolean getWorkingText() { - boolean hasChecked = false; - if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < mEditTextList.getChildCount(); i++) { - View view = mEditTextList.getChildAt(i); - NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); - if (!TextUtils.isEmpty(edit.getText())) { - if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) { - sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n"); - hasChecked = true; - } else { - sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n"); - } - } - } - mWorkingNote.setWorkingText(sb.toString()); - } else { - // 保留富文本格式,将 Spanned 转换为 HTML 字符串保存 - mWorkingNote.setWorkingText(Html.toHtml(mNoteEditor.getText())); - } - return hasChecked; - } - - /** - * 保存当前工作笔记 - *

- * 该方法首先获取当前工作笔记的最新文本内容,然后调用mWorkingNote的saveNote方法将其保存到数据库中。 - * 如果保存成功,会设置返回结果为RESULT_OK,用于标识创建/编辑状态,以便在返回列表视图时正确定位。 - *

- * @return 保存是否成功 - */ - private boolean saveNote() { - getWorkingText(); - boolean saved = mWorkingNote.saveNote(); - if (saved) { - /** - * There are two modes from List view to edit view, open one note, - * create/edit a node. Opening node requires to the original - * position in the list when back from edit view, while creating a - * new node requires to the top of the list. This code - * {@link #RESULT_OK} is used to identify the create/edit state - */ - setResult(RESULT_OK); - } - return saved; - } - - /** - * 将当前编辑的笔记发送到桌面创建快捷方式 - *

- * 该方法执行以下操作: - * 1. 在发送前确保当前编辑的笔记已保存在数据库中,如果是新笔记则先保存 - * 2. 创建一个快捷方式Intent,包含打开该笔记的相关信息 - * 3. 设置快捷方式的名称、图标等属性 - * 4. 发送广播来创建桌面快捷方式 - * 5. 如果笔记为空或保存失败,显示错误提示 - *

- */ - private void sendToDesktop() { - // 在发送到桌面之前,确保当前编辑的笔记已存在于数据库中。对于新笔记,首先保存它 - if (!mWorkingNote.existInDatabase()) { - saveNote(); - } - - if (mWorkingNote.getNoteId() > 0) { - Intent sender = new Intent(); - Intent shortcutIntent = new Intent(this, NoteEditActivity.class); - shortcutIntent.setAction(Intent.ACTION_VIEW); - shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); - sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); - sender.putExtra(Intent.EXTRA_SHORTCUT_NAME, - makeShortcutIconTitle(mWorkingNote.getContent())); - sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, - Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app)); - sender.putExtra("duplicate", true); - sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); - showToast(R.string.info_note_enter_desktop); - sendBroadcast(sender); - } else { - /** - * There is the condition that user has input nothing (the note is - * not worthy saving), we have no note id, remind the user that he - * should input something - */ - Log.e(TAG, "Send to desktop error"); - showToast(R.string.error_note_empty_for_send_to_desktop); - } - } - - /** - * 生成快捷方式图标的标题 - *

- * 该方法将笔记内容转换为适合作为快捷方式标题的格式: - * 1. 移除检查列表模式下的状态标签(已完成和未完成标签) - * 2. 如果内容长度超过最大限制,则截断为指定长度 - *

- * @param content 笔记的原始内容 - * @return 处理后的快捷方式标题 - */ - private String makeShortcutIconTitle(String content) { - content = content.replace(TAG_CHECKED, ""); - content = content.replace(TAG_UNCHECKED, ""); - return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0, - SHORTCUT_ICON_TITLE_MAX_LEN) : content; - } - - /** - * 显示短时长的Toast提示信息 - *

- * 该方法是showToast(int resId, int duration)的便捷重载版本, - * 默认使用Toast.LENGTH_SHORT作为显示时长 - *

- * @param resId 提示信息的字符串资源ID - */ - private void showToast(int resId) { - showToast(resId, Toast.LENGTH_SHORT); - } - - /** - * 显示Toast提示信息 - *

- * 该方法使用Android系统的Toast机制显示指定的提示信息 - *

- * @param resId 提示信息的字符串资源ID - * @param duration 显示时长,可以是Toast.LENGTH_SHORT或Toast.LENGTH_LONG - */ - private void showToast(int resId, int duration) { - Toast.makeText(this, resId, duration).show(); - } -} diff --git a/src/main/java/net/micode/notes/ui/NoteEditText.java b/src/main/java/net/micode/notes/ui/NoteEditText.java deleted file mode 100644 index 5a6842e..0000000 --- a/src/main/java/net/micode/notes/ui/NoteEditText.java +++ /dev/null @@ -1,429 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.ui; - -import android.content.Context; -import android.graphics.Rect; -import android.text.Layout; -import android.text.Selection; -import android.text.Spannable; -import android.text.SpannableStringBuilder; -import android.text.Spanned; -import android.text.TextUtils; -import android.text.style.StyleSpan; -import android.text.style.URLSpan; -import android.text.style.UnderlineSpan; -import android.text.style.ForegroundColorSpan; -import android.graphics.Typeface; -import android.util.AttributeSet; -import android.util.Log; -import android.view.ContextMenu; -import android.view.KeyEvent; -import android.view.MenuItem; -import android.view.MenuItem.OnMenuItemClickListener; -import android.view.MotionEvent; -import android.widget.EditText; - -import net.micode.notes.R; - -import java.util.HashMap; -import java.util.Map; - -/** - * 自定义笔记编辑文本框 - *

- * 该类继承自EditText,用于小米便签应用中的笔记编辑,支持链接识别、键盘事件处理 - * 和文本视图变化监听等功能 - *

- */ -public class NoteEditText extends EditText { - /** - * 日志标签 - */ - private static final String TAG = "NoteEditText"; - - /** - * 当前编辑框的索引 - */ - private int mIndex; - - /** - * 删除操作前的选择起始位置 - */ - private int mSelectionStartBeforeDelete; - - /** - * 电话链接协议 - */ - private static final String SCHEME_TEL = "tel:" ; - - /** - * HTTP链接协议 - */ - private static final String SCHEME_HTTP = "http:" ; - - /** - * 邮件链接协议 - */ - private static final String SCHEME_EMAIL = "mailto:" ; - - /** - * 链接协议与资源ID的映射表 - */ - private static final Map sSchemaActionResMap = new HashMap(); - static { - sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); - sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); - sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); - } - - /** - * 文本视图变化监听器接口 - *

- * 由{@link NoteEditActivity}调用,用于处理编辑框的删除或添加 - *

- */ - public interface OnTextViewChangeListener { - /** - * 当按下{@link KeyEvent#KEYCODE_DEL}且文本为空时,删除当前编辑框 - */ - void onEditTextDelete(int index, String text); - - /** - * 当按下{@link KeyEvent#KEYCODE_ENTER}时,在当前编辑框后添加新的编辑框 - */ - void onEditTextEnter(int index, String text); - - /** - * 当文本变化时,隐藏或显示项目选项 - */ - void onTextChange(int index, boolean hasText); - } - - /** - * 文本视图变化监听器实例 - */ - private OnTextViewChangeListener mOnTextViewChangeListener; - - /** - * 构造函数,创建笔记编辑文本框 - * @param context 上下文对象 - */ - public NoteEditText(Context context) { - super(context, null); - mIndex = 0; - } - - /** - * 设置编辑框索引 - * @param index 编辑框索引 - */ - public void setIndex(int index) { - mIndex = index; - } - - /** - * 设置文本视图变化监听器 - * @param listener 文本视图变化监听器 - */ - public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { - mOnTextViewChangeListener = listener; - } - - /** - * 构造函数,创建笔记编辑文本框 - * @param context 上下文对象 - * @param attrs 属性集合 - */ - public NoteEditText(Context context, AttributeSet attrs) { - super(context, attrs, android.R.attr.editTextStyle); - } - - /** - * 构造函数,创建笔记编辑文本框 - * @param context 上下文对象 - * @param attrs 属性集合 - * @param defStyle 默认样式 - */ - public NoteEditText(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - // TODO Auto-generated constructor stub - } - - /** - * 处理触摸事件 - *

- * 当用户点击编辑框时,将光标定位到点击位置 - *

- * @param event 触摸事件 - * @return 事件是否被处理 - */ - @Override - public boolean onTouchEvent(MotionEvent event) { - switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: - - int x = (int) event.getX(); - int y = (int) event.getY(); - x -= getTotalPaddingLeft(); - y -= getTotalPaddingTop(); - x += getScrollX(); - y += getScrollY(); - - Layout layout = getLayout(); - int line = layout.getLineForVertical(y); - int off = layout.getOffsetForHorizontal(line, x); - Selection.setSelection(getText(), off); - break; - } - - return super.onTouchEvent(event); - } - - /** - * 处理按键按下事件 - *

- * 监听回车键和删除键的按下事件 - *

- * @param keyCode 按键代码 - * @param event 按键事件 - * @return 事件是否被处理 - */ - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - switch (keyCode) { - case KeyEvent.KEYCODE_ENTER: - if (mOnTextViewChangeListener != null) { - return false; - } - break; - case KeyEvent.KEYCODE_DEL: - mSelectionStartBeforeDelete = getSelectionStart(); - break; - default: - break; - } - return super.onKeyDown(keyCode, event); - } - - /** - * 处理按键释放事件 - *

- * 监听删除键和回车键的释放事件,实现编辑框的删除和添加功能 - *

- * @param keyCode 按键代码 - * @param event 按键事件 - * @return 事件是否被处理 - */ - @Override - public boolean onKeyUp(int keyCode, KeyEvent event) { - switch(keyCode) { - case KeyEvent.KEYCODE_DEL: - if (mOnTextViewChangeListener != null) { - if (0 == mSelectionStartBeforeDelete && mIndex != 0) { - mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); - return true; - } - } else { - Log.d(TAG, "OnTextViewChangeListener was not seted"); - } - break; - case KeyEvent.KEYCODE_ENTER: - if (mOnTextViewChangeListener != null) { - int selectionStart = getSelectionStart(); - String text = getText().subSequence(selectionStart, length()).toString(); - setText(getText().subSequence(0, selectionStart)); - mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); - } else { - Log.d(TAG, "OnTextViewChangeListener was not seted"); - } - break; - default: - break; - } - return super.onKeyUp(keyCode, event); - } - - /** - * 处理焦点变化事件 - *

- * 当编辑框失去焦点且文本为空时,通知监听器隐藏项目选项 - * 当编辑框获得焦点或文本不为空时,通知监听器显示项目选项 - *

- * @param focused 是否获得焦点 - * @param direction 焦点变化方向 - * @param previouslyFocusedRect 之前焦点所在的矩形区域 - */ - @Override - protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { - if (mOnTextViewChangeListener != null) { - if (!focused && TextUtils.isEmpty(getText())) { - mOnTextViewChangeListener.onTextChange(mIndex, false); - } else { - mOnTextViewChangeListener.onTextChange(mIndex, true); - } - } - super.onFocusChanged(focused, direction, previouslyFocusedRect); - } - - /** - * 创建上下文菜单 - *

- * 当选中的文本包含链接时,创建相应的链接操作菜单 - *

- * @param menu 上下文菜单 - */ - @Override - protected void onCreateContextMenu(ContextMenu menu) { - if (getText() instanceof Spanned) { - int selStart = getSelectionStart(); - int selEnd = getSelectionEnd(); - - int min = Math.min(selStart, selEnd); - int max = Math.max(selStart, selEnd); - - final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); - if (urls.length == 1) { - int defaultResId = 0; - for(String schema: sSchemaActionResMap.keySet()) { - if(urls[0].getURL().indexOf(schema) >= 0) { - defaultResId = sSchemaActionResMap.get(schema); - break; - } - } - - if (defaultResId == 0) { - defaultResId = R.string.note_link_other; - } - - menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( - new OnMenuItemClickListener() { - public boolean onMenuItemClick(MenuItem item) { - // goto a new intent - urls[0].onClick(NoteEditText.this); - return true; - } - }); - } - } - super.onCreateContextMenu(menu); - } - - /** - * 应用粗体格式到选中文本 - */ - public void applyBold() { - applyStyle(Typeface.BOLD); - } - - /** - * 应用斜体格式到选中文本 - */ - public void applyItalic() { - applyStyle(Typeface.ITALIC); - } - - /** - * 应用下划线格式到选中文本 - */ - public void applyUnderline() { - SpannableStringBuilder ssb = new SpannableStringBuilder(getText()); - int start = getSelectionStart(); - int end = getSelectionEnd(); - - if (start != end) { - // 检查是否已存在下划线样式 - UnderlineSpan[] existingUnderlines = ssb.getSpans(start, end, UnderlineSpan.class); - if (existingUnderlines.length > 0) { - // 移除下划线 - for (UnderlineSpan span : existingUnderlines) { - ssb.removeSpan(span); - } - } else { - // 添加下划线 - ssb.setSpan(new UnderlineSpan(), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); - } - setText(ssb); - setSelection(start, end); - } - } - - /** - * 应用指定颜色到选中文本 - * @param color 要应用的颜色值 - */ - public void applyTextColor(int color) { - SpannableStringBuilder ssb = new SpannableStringBuilder(getText()); - int start = getSelectionStart(); - int end = getSelectionEnd(); - - if (start != end) { - // 移除已有的文字颜色 - ForegroundColorSpan[] existingSpans = ssb.getSpans(start, end, ForegroundColorSpan.class); - for (ForegroundColorSpan span : existingSpans) { - ssb.removeSpan(span); - } - - // 添加新的文字颜色 - ssb.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); - - setText(ssb); - setSelection(start, end); - } - } - - /** - * 应用字体样式到选中文本 - */ - private void applyStyle(int style) { - SpannableStringBuilder ssb = new SpannableStringBuilder(getText()); - int start = getSelectionStart(); - int end = getSelectionEnd(); - - if (start != end) { - // 获取当前选中文本的所有样式 - StyleSpan[] existingSpans = ssb.getSpans(start, end, StyleSpan.class); - - // 计算当前选中文本的总样式 - int currentStyle = Typeface.NORMAL; - if (existingSpans.length > 0) { - // 如果有样式,取第一个样式(假设所有样式一致) - currentStyle = existingSpans[0].getStyle(); - } - - // 计算新的字体样式 - int newStyle; - if ((currentStyle & style) != 0) { - // 移除该样式 - newStyle = currentStyle & ~style; - } else { - // 添加该样式 - newStyle = currentStyle | style; - } - - // 移除旧的样式 - for (StyleSpan span : existingSpans) { - ssb.removeSpan(span); - } - - // 添加新的样式 - ssb.setSpan(new StyleSpan(newStyle), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); - setText(ssb); - setSelection(start, end); - } - } -} diff --git a/src/main/java/net/micode/notes/ui/NoteItemData.java b/src/main/java/net/micode/notes/ui/NoteItemData.java deleted file mode 100644 index 2dcdedf..0000000 --- a/src/main/java/net/micode/notes/ui/NoteItemData.java +++ /dev/null @@ -1,600 +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.text.TextUtils; - -import net.micode.notes.data.Contact; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.tool.DataUtils; - - -/** - * 笔记列表项数据类 - *

- * 该类用于存储和管理小米便签应用中笔记列表项的数据,包括笔记的基本信息、 - * 文件夹信息、提醒信息等 - *

- */ -public class NoteItemData { - /** - * 笔记数据查询的投影列数组 - *

- * 定义了从数据库查询笔记数据时需要获取的列 - *

- */ - static final String [] PROJECTION = 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.PINNED, - NoteColumns.IS_LOCKED, - NoteColumns.LOCK_PASSWORD, - NoteColumns.LOCK_TYPE, - NoteColumns.DELETED_DATE, - }; - - /** - * 查询结果中笔记ID列的索引 - */ - private static final int ID_COLUMN = 0; - - /** - * 查询结果中提醒日期列的索引 - */ - private static final int ALERTED_DATE_COLUMN = 1; - - /** - * 查询结果中背景颜色ID列的索引 - */ - private static final int BG_COLOR_ID_COLUMN = 2; - - /** - * 查询结果中创建日期列的索引 - */ - private static final int CREATED_DATE_COLUMN = 3; - - /** - * 查询结果中是否有附件列的索引 - */ - private static final int HAS_ATTACHMENT_COLUMN = 4; - - /** - * 查询结果中修改日期列的索引 - */ - private static final int MODIFIED_DATE_COLUMN = 5; - - /** - * 查询结果中笔记数量列的索引 - */ - private static final int NOTES_COUNT_COLUMN = 6; - - /** - * 查询结果中父文件夹ID列的索引 - */ - private static final int PARENT_ID_COLUMN = 7; - - /** - * 查询结果中笔记摘要列的索引 - */ - private static final int SNIPPET_COLUMN = 8; - - /** - * 查询结果中笔记类型列的索引 - */ - private static final int TYPE_COLUMN = 9; - - /** - * 查询结果中小组件ID列的索引 - */ - private static final int WIDGET_ID_COLUMN = 10; - - /** - * 查询结果中小组件类型列的索引 - */ - private static final int WIDGET_TYPE_COLUMN = 11; - - /** - * 查询结果中置顶状态列的索引 - */ - private static final int PINNED_COLUMN = 12; - - /** - * 查询结果中锁定状态列的索引 - */ - private static final int IS_LOCKED_COLUMN = 13; - - /** - * 查询结果中锁定密码列的索引 - */ - private static final int LOCK_PASSWORD_COLUMN = 14; - - /** - * 查询结果中锁定类型列的索引 - */ - private static final int LOCK_TYPE_COLUMN = 15; - - /** - * 查询结果中删除日期列的索引 - */ - private static final int DELETED_DATE_COLUMN = 16; - - /** - * 笔记ID - */ - private long mId; - - /** - * 置顶状态 - */ - private boolean mPinned; - - /** - * 锁定状态 - */ - private boolean mIsLocked; - - /** - * 锁定密码 - */ - private String mLockPassword; - - /** - * 锁定类型 - */ - private int mLockType; - - /** - * 提醒日期 - */ - private long mAlertDate; - - /** - * 背景颜色ID - */ - private int mBgColorId; - - /** - * 创建日期 - */ - private long mCreatedDate; - - /** - * 是否有附件 - */ - private boolean mHasAttachment; - - /** - * 修改日期 - */ - private long mModifiedDate; - - /** - * 删除日期 - */ - private long mDeletedDate; - - /** - * 笔记数量(用于文件夹) - */ - private int mNotesCount; - - /** - * 父文件夹ID - */ - private long mParentId; - - /** - * 笔记摘要 - */ - private String mSnippet; - - /** - * 笔记类型 - */ - private int mType; - - /** - * 小组件ID - */ - private int mWidgetId; - - /** - * 小组件类型 - */ - private int mWidgetType; - - /** - * 联系人名称(用于通话记录) - */ - private String mName; - - /** - * 电话号码(用于通话记录) - */ - private String mPhoneNumber; - - /** - * 是否为最后一项 - */ - private boolean mIsLastItem; - - /** - * 是否为第一项 - */ - private boolean mIsFirstItem; - - /** - * 是否为唯一一项 - */ - private boolean mIsOnlyOneItem; - - /** - * 是否为文件夹后的唯一笔记 - */ - private boolean mIsOneNoteFollowingFolder; - - /** - * 是否为文件夹后的多个笔记 - */ - private boolean mIsMultiNotesFollowingFolder; - - /** - * 构造函数,从游标中初始化笔记列表项数据 - * @param context 上下文对象 - * @param cursor 包含笔记数据的游标 - */ - public NoteItemData(Context context, Cursor cursor) { - mId = cursor.getLong(ID_COLUMN); - mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); - mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); - mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); - mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; - mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); - mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); - mParentId = cursor.getLong(PARENT_ID_COLUMN); - mSnippet = cursor.getString(SNIPPET_COLUMN); - // 先替换标签,保留HTML格式以便在列表中显示富文本 - mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( - NoteEditActivity.TAG_UNCHECKED, ""); - mType = cursor.getInt(TYPE_COLUMN); - mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); - mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); - mPinned = (cursor.getInt(PINNED_COLUMN) > 0) ? true : false; - mIsLocked = (cursor.getInt(IS_LOCKED_COLUMN) > 0) ? true : false; - mLockPassword = cursor.getString(LOCK_PASSWORD_COLUMN); - mLockType = cursor.getInt(LOCK_TYPE_COLUMN); - mDeletedDate = cursor.getLong(DELETED_DATE_COLUMN); - - mPhoneNumber = ""; - if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { - mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); - if (!TextUtils.isEmpty(mPhoneNumber)) { - mName = Contact.getContact(context, mPhoneNumber); - if (mName == null) { - mName = mPhoneNumber; - } - } - } - - if (mName == null) { - mName = ""; - } - checkPostion(cursor); - } - - /** - * 检查当前项在列表中的位置 - *

- * 该方法用于判断当前项是否为第一项、最后一项、唯一一项,以及是否为文件夹后的笔记 - *

- * @param cursor 包含笔记数据的游标 - */ - private void checkPostion(Cursor cursor) { - mIsLastItem = cursor.isLast() ? true : false; - mIsFirstItem = cursor.isFirst() ? true : false; - mIsOnlyOneItem = (cursor.getCount() == 1); - mIsMultiNotesFollowingFolder = false; - mIsOneNoteFollowingFolder = false; - - if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { - int position = cursor.getPosition(); - if (cursor.moveToPrevious()) { - if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER - || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { - if (cursor.getCount() > (position + 1)) { - mIsMultiNotesFollowingFolder = true; - } else { - mIsOneNoteFollowingFolder = true; - } - } - if (!cursor.moveToNext()) { - throw new IllegalStateException("cursor move to previous but can't move back"); - } - } - } - } - - /** - * 判断是否为文件夹后的唯一笔记 - * @return 是否为文件夹后的唯一笔记 - */ - public boolean isOneFollowingFolder() { - return mIsOneNoteFollowingFolder; - } - - /** - * 判断是否为文件夹后的多个笔记 - * @return 是否为文件夹后的多个笔记 - */ - public boolean isMultiFollowingFolder() { - return mIsMultiNotesFollowingFolder; - } - - /** - * 判断是否为最后一项 - * @return 是否为最后一项 - */ - public boolean isLast() { - return mIsLastItem; - } - - /** - * 获取通话记录联系人名称 - * @return 通话记录联系人名称 - */ - public String getCallName() { - return mName; - } - - /** - * 判断是否为第一项 - * @return 是否为第一项 - */ - public boolean isFirst() { - return mIsFirstItem; - } - - /** - * 判断是否为唯一一项 - * @return 是否为唯一一项 - */ - public boolean isSingle() { - return mIsOnlyOneItem; - } - - /** - * 获取笔记ID - * @return 笔记ID - */ - public long getId() { - return mId; - } - - /** - * 获取提醒日期 - * @return 提醒日期,以毫秒为单位 - */ - public long getAlertDate() { - return mAlertDate; - } - - /** - * 获取创建日期 - * @return 创建日期,以毫秒为单位 - */ - public long getCreatedDate() { - return mCreatedDate; - } - - /** - * 判断是否有附件 - * @return 是否有附件 - */ - public boolean hasAttachment() { - return mHasAttachment; - } - - /** - * 获取修改日期 - * @return 修改日期,以毫秒为单位 - */ - public long getModifiedDate() { - return mModifiedDate; - } - - /** - * 获取背景颜色ID - * @return 背景颜色ID - */ - public int getBgColorId() { - return mBgColorId; - } - - /** - * 获取父文件夹ID - * @return 父文件夹ID - */ - public long getParentId() { - return mParentId; - } - - /** - * 获取笔记数量(用于文件夹) - * @return 笔记数量 - */ - public int getNotesCount() { - return mNotesCount; - } - - /** - * 获取文件夹ID - * @return 文件夹ID - */ - public long getFolderId () { - return mParentId; - } - - /** - * 获取笔记类型 - * @return 笔记类型 - */ - public int getType() { - return mType; - } - - /** - * 获取小组件类型 - * @return 小组件类型 - */ - public int getWidgetType() { - return mWidgetType; - } - - /** - * 获取小组件ID - * @return 小组件ID - */ - public int getWidgetId() { - return mWidgetId; - } - - /** - * 获取笔记摘要 - * @return 笔记摘要 - */ - public String getSnippet() { - return mSnippet; - } - - /** - * 判断是否有提醒 - * @return 是否有提醒 - */ - public boolean hasAlert() { - return (mAlertDate > 0); - } - - /** - * 判断是否为通话记录 - * @return 是否为通话记录 - */ - public boolean isCallRecord() { - return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); - } - - /** - * 获取置顶状态 - * @return 置顶状态,true表示已置顶,false表示未置顶 - */ - public boolean isPinned() { - return mPinned; - } - - /** - * 设置置顶状态 - * @param pinned 置顶状态,true表示置顶,false表示取消置顶 - */ - public void setPinned(boolean pinned) { - mPinned = pinned; - } - - /** - * 获取锁定状态 - * @return 锁定状态,true表示已锁定,false表示未锁定 - */ - public boolean isLocked() { - return mIsLocked; - } - - /** - * 设置锁定状态 - * @param locked 锁定状态,true表示锁定,false表示解锁 - */ - public void setLocked(boolean locked) { - mIsLocked = locked; - } - - /** - * 获取锁定密码 - * @return 锁定密码 - */ - public String getLockPassword() { - return mLockPassword; - } - - /** - * 设置锁定密码 - * @param password 锁定密码 - */ - public void setLockPassword(String password) { - mLockPassword = password; - } - - /** - * 获取锁定类型 - * @return 锁定类型,0表示笔记,1表示文件夹 - */ - public int getLockType() { - return mLockType; - } - - /** - * 设置锁定类型 - * @param type 锁定类型,0表示笔记,1表示文件夹 - */ - public void setLockType(int type) { - mLockType = type; - } - - /** - * 获取删除日期 - * @return 删除日期,以毫秒为单位 - */ - public long getDeletedDate() { - return mDeletedDate; - } - - /** - * 判断是否为已删除项 - * @return 是否已删除,true表示已删除,false表示未删除 - */ - public boolean isDeleted() { - return (mDeletedDate > 0); - } - - /** - * 获取笔记类型(静态方法) - * @param cursor 包含笔记数据的游标 - * @return 笔记类型 - */ - public static int getNoteType(Cursor cursor) { - return cursor.getInt(TYPE_COLUMN); - } -} diff --git a/src/main/java/net/micode/notes/ui/NotesListActivity.java b/src/main/java/net/micode/notes/ui/NotesListActivity.java deleted file mode 100644 index ae6ab3f..0000000 --- a/src/main/java/net/micode/notes/ui/NotesListActivity.java +++ /dev/null @@ -1,1890 +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.app.Dialog; -import android.appwidget.AppWidgetManager; -import android.content.AsyncQueryHandler; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.SharedPreferences; -import android.database.Cursor; -import android.os.AsyncTask; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.text.Editable; -import android.text.TextUtils; -import android.text.TextWatcher; -import android.util.Log; -import android.view.ActionMode; -import android.view.ContextMenu; -import android.view.ContextMenu.ContextMenuInfo; -import android.view.Display; -import android.view.HapticFeedbackConstants; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.MenuItem.OnMenuItemClickListener; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.View.OnCreateContextMenuListener; -import android.view.View.OnTouchListener; -import android.view.inputmethod.InputMethodManager; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.AdapterView.OnItemLongClickListener; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ListView; -import android.widget.PopupMenu; -import android.widget.TextView; -import android.widget.Toast; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.remote.GTaskSyncService; -import net.micode.notes.model.WorkingNote; -import net.micode.notes.tool.BackupUtils; -import net.micode.notes.tool.DataUtils; -import net.micode.notes.tool.ResourceParser; -import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; -import net.micode.notes.widget.NoteWidgetProvider_2x; -import net.micode.notes.widget.NoteWidgetProvider_4x; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.HashSet; - -/** - * 笔记列表活动类 - *

- * 该类是应用的主界面,负责显示笔记列表,处理笔记的创建、编辑、删除等操作, - * 支持文件夹管理、笔记同步、导入导出等功能,并提供了多选模式、上下文菜单等交互方式 - *

- */ -public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { - /** 文件夹笔记列表查询令牌 */ - private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; - - /** 文件夹列表查询令牌 */ - private static final int FOLDER_LIST_QUERY_TOKEN = 1; - - /** 文件夹删除菜单ID */ - private static final int MENU_FOLDER_DELETE = 0; - - /** 文件夹查看菜单ID */ - private static final int MENU_FOLDER_VIEW = 1; - - /** 文件夹重命名菜单ID */ - private static final int MENU_FOLDER_CHANGE_NAME = 2; - - /** 偏好设置:是否添加了介绍笔记 */ - private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; - - /** - * 列表编辑状态枚举 - *

- * 定义了笔记列表的三种状态: - * 1. NOTE_LIST:根目录下的笔记列表 - * 2. SUB_FOLDER:子文件夹中的笔记列表 - * 3. CALL_RECORD_FOLDER:通话记录文件夹 - *

- */ - private enum ListEditState { - NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER - } - - /** - * 显示密码输入对话框 - *

- * 该方法用于显示一个密码输入对话框,让用户输入密码来锁定选中的笔记或文件夹 - *

- */ - private void showPasswordDialog() { - final EditText passwordEditText = new EditText(this); - passwordEditText.setHint(R.string.hint_enter_password); - passwordEditText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); - - new AlertDialog.Builder(this) - .setTitle(R.string.dialog_enter_password) - .setView(passwordEditText) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - String password = passwordEditText.getText().toString(); - if (!TextUtils.isEmpty(password)) { - toggleLockedStatus(password); - } - } - }) - .setNegativeButton(android.R.string.cancel, null) - .show(); - } - - /** - * 切换锁定状态 - *

- * 该方法用于切换选中笔记或文件夹的锁定状态,使用异步任务处理数据库操作 - *

- * @param password 用于锁定的密码 - */ - private void toggleLockedStatus(final String password) { - final HashSet selectedIds = mNotesListAdapter.getSelectedItemIds(); - final int selectedCount = mNotesListAdapter.getSelectedCount(); - - new AsyncTask() { - protected Integer doInBackground(Void... unused) { - int finalLockedStatus = -1; // 默认为-1,表示未处理 - for (Long noteId : selectedIds) { - // 查询当前便签的锁定状态 - Cursor cursor = mContentResolver.query(Notes.CONTENT_NOTE_URI, - new String[]{NoteColumns.IS_LOCKED}, - NoteColumns.ID + "=?", - new String[]{String.valueOf(noteId)}, - null); - - if (cursor != null && cursor.moveToFirst()) { - int currentLocked = cursor.getInt(0); - // 切换锁定状态 - int newLocked = currentLocked == 1 ? 0 : 1; - finalLockedStatus = newLocked; // 保存最终锁定状态 - - ContentValues values = new ContentValues(); - values.put(NoteColumns.IS_LOCKED, newLocked); - - if (newLocked == 1) { - // 如果是锁定操作,设置密码和锁定类型 - values.put(NoteColumns.LOCK_PASSWORD, encryptPassword(password)); - // 判断是笔记还是文件夹 - Cursor typeCursor = mContentResolver.query(Notes.CONTENT_NOTE_URI, - new String[]{NoteColumns.TYPE}, - NoteColumns.ID + "=?", - new String[]{String.valueOf(noteId)}, - null); - if (typeCursor != null && typeCursor.moveToFirst()) { - int type = typeCursor.getInt(0); - values.put(NoteColumns.LOCK_TYPE, type == Notes.TYPE_FOLDER ? Notes.LOCK_TYPE_FOLDER : Notes.LOCK_TYPE_NOTE); - typeCursor.close(); - } - } else { - // 如果是解锁操作,清空密码 - values.put(NoteColumns.LOCK_PASSWORD, ""); - } - - mContentResolver.update(Notes.CONTENT_NOTE_URI, - values, - NoteColumns.ID + "=?", - new String[]{String.valueOf(noteId)}); - - cursor.close(); - } - } - return finalLockedStatus; - } - - @Override - protected void onPostExecute(Integer finalLockedStatus) { - String message = finalLockedStatus == 1 ? getString(R.string.message_note_locked) : getString(R.string.message_note_unlocked); - Toast.makeText(NotesListActivity.this, message, Toast.LENGTH_SHORT).show(); - // 重新查询数据,更新列表 - startAsyncNotesListQuery(); - mModeCallBack.finishActionMode(); - } - }.execute(); - } - - /** - * 加密密码 - *

- * 该方法使用Base64和ANDROID_ID对密码进行加密 - *

- * @param password 原始密码 - * @return 加密后的密码 - */ - private String encryptPassword(String password) { - try { - // 获取设备的ANDROID_ID作为加密密钥 - String androidId = android.provider.Settings.Secure.getString(getContentResolver(), - android.provider.Settings.Secure.ANDROID_ID); - // 使用简单的加密算法:将密码与ANDROID_ID拼接后进行Base64编码 - String combined = password + androidId; - return android.util.Base64.encodeToString(combined.getBytes(), android.util.Base64.DEFAULT); - } catch (Exception e) { - Log.e(TAG, "Password encryption failed", e); - return password; // 加密失败时返回原始密码 - } - }; - - /** 当前列表编辑状态 */ - private ListEditState mState; - - /** 后台查询处理器 */ - private BackgroundQueryHandler mBackgroundQueryHandler; - - /** 笔记列表适配器 */ - private NotesListAdapter mNotesListAdapter; - - /** 笔记列表视图 */ - private ListView mNotesListView; - - /** 新建笔记按钮 */ - private Button mAddNewNote; - - // 删除不再使用的触摸事件相关变量 - // private boolean mDispatch; - // private int mOriginY; - // private int mDispatchY; - - /** 标题栏文本视图 */ - private TextView mTitleBar; - - /** 当前文件夹ID */ - private long mCurrentFolderId; - - /** 内容解析器 */ - private ContentResolver mContentResolver; - - /** 模式回调 */ - private ModeCallback mModeCallBack; - - /** 是否分发触摸事件 */ - private boolean mDispatch; - - /** 原始Y坐标 */ - private int mOriginY; - - /** 分发Y坐标 */ - private int mDispatchY; - - /** 日志标签 */ - private static final String TAG = "NotesListActivity"; - - /** 笔记列表视图滚动速率 */ - public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; - - /** 当前焦点的笔记数据项 */ - private NoteItemData mFocusNoteDataItem; - - /** 普通文件夹选择条件 */ - private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; - - /** 根文件夹选择条件 */ - private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" - + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" - + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " - + NoteColumns.NOTES_COUNT + ">0)" + " OR (" - + NoteColumns.ID + "=" + Notes.ID_TRASH_FOLER + ")"; // 添加回收站文件夹到根目录列表 - - /** 打开笔记请求码 */ - private final static int REQUEST_CODE_OPEN_NODE = 102; - /** 新建笔记请求码 */ - private final static int REQUEST_CODE_NEW_NODE = 103; - - /** - * 活动创建时调用 - *

- * 该方法完成以下工作: - * 1. 设置布局文件 - * 2. 初始化资源 - * 3. 如果是首次使用,添加介绍笔记 - *

- * @param savedInstanceState 保存的实例状态 - */ - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.note_list); - - // 上移底部系统栏,解决写便签按钮与底部系统栏之间的多余间距 - View decorView = getWindow().getDecorView(); - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { - // Android 11+ 使用新的WindowInsetsController API - android.view.WindowInsetsController insetsController = decorView.getWindowInsetsController(); - if (insetsController != null) { - // 隐藏底部导航栏 - insetsController.hide(android.view.WindowInsets.Type.navigationBars()); - // 设置系统栏行为,允许滑动显示 - insetsController.setSystemBarsBehavior( - android.view.WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE); - } - } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { - // Android 4.1-10 使用旧的系统UI可见性API - int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; - decorView.setSystemUiVisibility(uiOptions); - } - - // 添加系统UI可见性变化监听器,确保系统栏保持上移状态 - decorView.setOnSystemUiVisibilityChangeListener( - new View.OnSystemUiVisibilityChangeListener() { - @Override - public void onSystemUiVisibilityChange(int visibility) { - // 当系统UI可见性变化时,重新设置系统UI可见性 - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { - // Android 11+ 使用新API - android.view.WindowInsetsController insetsController = decorView.getWindowInsetsController(); - if (insetsController != null) { - insetsController.hide(android.view.WindowInsets.Type.navigationBars()); - } - } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { - // Android 4.1-10 使用旧API - if ((visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { - int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; - decorView.setSystemUiVisibility(uiOptions); - } - } - } - } - ); - - initResources(); - - /** - * Insert an introduction when user firstly use this application - */ - setAppInfoFromRawRes(); - - // 注册Android 13+的返回键回调 - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) { - getOnBackInvokedDispatcher().registerOnBackInvokedCallback( - android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT, - new android.window.OnBackInvokedCallback() { - @Override - public void onBackInvoked() { - handleBackPress(); - } - } - ); - } - } - - /** - * 处理活动返回结果 - *

- * 该方法在其他活动返回结果时调用,主要用于处理笔记编辑活动返回的结果 - *

- * @param requestCode 请求码 - * @param resultCode 结果码 - * @param data 返回的数据 - */ - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - if (resultCode == RESULT_OK - && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { - mNotesListAdapter.changeCursor(null); - } else { - super.onActivityResult(requestCode, resultCode, data); - } - } - - private void setAppInfoFromRawRes() { - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); - if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { - StringBuilder sb = new StringBuilder(); - InputStream in = null; - try { - in = getResources().openRawResource(R.raw.introduction); - if (in != null) { - InputStreamReader isr = new InputStreamReader(in); - BufferedReader br = new BufferedReader(isr); - char [] buf = new char[1024]; - int len = 0; - while ((len = br.read(buf)) > 0) { - sb.append(buf, 0, len); - } - } else { - Log.e(TAG, "Read introduction file error"); - return; - } - } catch (IOException e) { - e.printStackTrace(); - return; - } finally { - if(in != null) { - try { - in.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, - AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, - ResourceParser.RED); - note.setWorkingText(sb.toString()); - if (note.saveNote()) { - sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); - } else { - Log.e(TAG, "Save introduction note error"); - return; - } - } - } - - /** - * 活动开始时调用 - *

- * 该方法在活动开始时调用,主要用于启动异步笔记列表查询 - *

- */ - @Override - protected void onStart() { - super.onStart(); - startAsyncNotesListQuery(); - // 启动回收站自动清理任务 - net.micode.notes.worker.TrashCleanupWorker.doCleanup(this); - } - - /** - * 初始化资源 - *

- * 该方法完成以下工作: - * 1. 初始化内容解析器和后台查询处理器 - * 2. 设置当前文件夹ID为根文件夹ID - * 3. 初始化笔记列表视图,添加页脚,设置点击和长按监听器 - * 4. 初始化笔记列表适配器并设置给列表视图 - * 5. 初始化新建笔记按钮,设置点击和触摸监听器 - * 6. 初始化触摸事件相关变量 - * 7. 初始化标题栏和状态 - * 8. 初始化模式回调 - *

- */ - private void initResources() { - mContentResolver = this.getContentResolver(); - mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); - mCurrentFolderId = Notes.ID_ROOT_FOLDER; - mNotesListView = (ListView) findViewById(R.id.notes_list); - mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), - null, false); - mNotesListView.setOnItemClickListener(new OnListItemClickListener()); - mNotesListView.setOnItemLongClickListener(this); - mNotesListAdapter = new NotesListAdapter(this); - mNotesListView.setAdapter(mNotesListAdapter); - mAddNewNote = (Button) findViewById(R.id.btn_new_note); - mAddNewNote.setOnClickListener(this); - mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); - mDispatch = false; - mDispatchY = 0; - mOriginY = 0; - mTitleBar = (TextView) findViewById(R.id.tv_title_bar); - mState = ListEditState.NOTE_LIST; - mModeCallBack = new ModeCallback(); - } - - /** - * 多选模式回调类 - *

- * 该类实现了ListView.MultiChoiceModeListener和OnMenuItemClickListener接口, - * 用于处理多选模式下的操作,包括创建模式、更新菜单、处理菜单点击事件等 - *

- */ - private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { - /** 下拉菜单 */ - private DropdownMenu mDropDownMenu; - /** 动作模式 */ - private ActionMode mActionMode; - /** 移动菜单 */ - private MenuItem mMoveMenu; - - /** - * 创建动作模式 - *

- * 该方法完成以下工作: - * 1. 加载菜单资源 - * 2. 设置删除菜单的点击监听器 - * 3. 根据当前文件夹ID和用户文件夹数量设置移动菜单或恢复菜单的可见性 - * 4. 保存动作模式实例 - * 5. 设置列表适配器为选择模式 - * 6. 禁用列表的长按功能 - * 7. 隐藏新建笔记按钮 - * 8. 设置自定义视图 - * 9. 创建下拉菜单 - * 10. 设置下拉菜单的点击监听器 - *

- * @param mode 动作模式 - * @param menu 菜单 - * @return 是否创建成功,返回true表示成功 - */ - public boolean onCreateActionMode(ActionMode mode, Menu menu) { - getMenuInflater().inflate(R.menu.note_list_options, menu); - menu.findItem(R.id.delete).setOnMenuItemClickListener(this); - - if (mCurrentFolderId == Notes.ID_TRASH_FOLER) { - // 在回收站内部,显示恢复按钮 - MenuItem restoreMenu = menu.findItem(R.id.restore); - if (restoreMenu != null) { - restoreMenu.setVisible(true); - restoreMenu.setOnMenuItemClickListener(this); - } - // 隐藏移动按钮 - MenuItem moveMenu = menu.findItem(R.id.move); - if (moveMenu != null) { - moveMenu.setVisible(false); - } - } else { - // 在回收站外部,显示移动按钮 - mMoveMenu = menu.findItem(R.id.move); - if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER - || DataUtils.getUserFolderCount(mContentResolver) == 0) { - mMoveMenu.setVisible(false); - } else { - mMoveMenu.setVisible(true); - mMoveMenu.setOnMenuItemClickListener(this); - } - // 隐藏恢复按钮 - MenuItem restoreMenu = menu.findItem(R.id.restore); - if (restoreMenu != null) { - restoreMenu.setVisible(false); - } - } - - // 添加置顶菜单初始化 - MenuItem pinMenu = menu.findItem(R.id.pin); - if (pinMenu != null) { - pinMenu.setOnMenuItemClickListener(this); - } - // 添加锁定菜单初始化 - MenuItem lockMenu = menu.findItem(R.id.lock); - if (lockMenu != null) { - lockMenu.setOnMenuItemClickListener(this); - } - mActionMode = mode; - mNotesListAdapter.setChoiceMode(true); - mNotesListView.setLongClickable(false); - mAddNewNote.setVisibility(View.GONE); - - View customView = LayoutInflater.from(NotesListActivity.this).inflate( - R.layout.note_list_dropdown_menu, null); - mode.setCustomView(customView); - mDropDownMenu = new DropdownMenu(NotesListActivity.this, - (Button) customView.findViewById(R.id.selection_menu), - R.menu.note_list_dropdown); - mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ - public boolean onMenuItemClick(MenuItem item) { - mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); - updateMenu(); - return true; - } - - }); - return true; - } - - /** - * 更新菜单 - *

- * 该方法完成以下工作: - * 1. 获取选中的笔记数量 - * 2. 更新下拉菜单的标题,显示选中数量 - * 3. 更新全选/取消全选菜单项的状态和标题 - *

- */ - private void updateMenu() { - int selectedCount = mNotesListAdapter.getSelectedCount(); - // Update dropdown menu - String format = getResources().getString(R.string.menu_select_title, selectedCount); - mDropDownMenu.setTitle(format); - MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); - if (item != null) { - if (mNotesListAdapter.isAllSelected()) { - item.setChecked(true); - item.setTitle(R.string.menu_deselect_all); - } else { - item.setChecked(false); - item.setTitle(R.string.menu_select_all); - } - } - } - - /** - * 准备动作模式 - *

- * 该方法未实现具体功能,返回false - *

- * @param mode 动作模式 - * @param menu 菜单 - * @return 是否准备成功,返回false - */ - public boolean onPrepareActionMode(ActionMode mode, Menu menu) { - // TODO Auto-generated method stub - return false; - } - - /** - * 处理动作模式菜单项点击事件 - *

- * 该方法未实现具体功能,返回false - *

- * @param mode 动作模式 - * @param item 菜单项 - * @return 是否处理成功,返回false - */ - public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - // TODO Auto-generated method stub - return false; - } - - /** - * 销毁动作模式 - *

- * 该方法完成以下工作: - * 1. 设置列表适配器为非选择模式 - * 2. 启用列表的长按功能 - * 3. 显示新建笔记按钮 - *

- * @param mode 动作模式 - */ - public void onDestroyActionMode(ActionMode mode) { - mNotesListAdapter.setChoiceMode(false); - mNotesListView.setLongClickable(true); - mAddNewNote.setVisibility(View.VISIBLE); - } - - /** - * 结束动作模式 - *

- * 该方法调用动作模式的finish方法来结束多选模式 - *

- */ - public void finishActionMode() { - mActionMode.finish(); - } - - /** - * 列表项选中状态变化时调用 - *

- * 该方法完成以下工作: - * 1. 设置列表项的选中状态 - * 2. 更新菜单 - *

- * @param mode 动作模式 - * @param position 列表项位置 - * @param id 列表项ID - * @param checked 是否选中 - */ - public void onItemCheckedStateChanged(ActionMode mode, int position, long id, - boolean checked) { - mNotesListAdapter.setCheckedItem(position, checked); - updateMenu(); - } - - /** - * 处理菜单项点击事件 - *

- * 该方法完成以下工作: - * 1. 检查是否有选中的笔记,如果没有则显示提示 - * 2. 根据菜单项ID处理不同的操作: - * - 删除:显示删除确认对话框,点击确定后调用batchDelete方法 - * - 移动:调用startQueryDestinationFolders方法查询目标文件夹 - * - 恢复:调用batchRestore方法恢复选中的项目 - *

- * @param item 菜单项 - * @return 是否处理成功,返回true表示成功 - */ - public boolean onMenuItemClick(MenuItem item) { - if (mNotesListAdapter.getSelectedCount() == 0) { - Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), - Toast.LENGTH_SHORT).show(); - return true; - } - - switch (item.getItemId()) { - case R.id.delete: - AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); - - if (mCurrentFolderId == Notes.ID_TRASH_FOLER) { - // 在回收站内部,提示永久删除 - builder.setTitle(getString(R.string.alert_title_delete)); - builder.setIcon(android.R.drawable.ic_dialog_alert); - builder.setMessage(getString(R.string.alert_message_delete_notes_permanently, - mNotesListAdapter.getSelectedCount())); - } else { - // 在回收站外部,提示移动到回收站 - builder.setTitle(getString(R.string.alert_title_delete)); - builder.setIcon(android.R.drawable.ic_dialog_alert); - builder.setMessage(getString(R.string.alert_message_delete_notes, - mNotesListAdapter.getSelectedCount())); - } - - builder.setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int which) { - batchDelete(); - } - }); - builder.setNegativeButton(android.R.string.cancel, null); - builder.show(); - break; - case R.id.move: - startQueryDestinationFolders(); - break; - case R.id.restore: - // 恢复选中的项目 - batchRestore(); - break; - case R.id.pin: - togglePinnedStatus(); - break; - case R.id.lock: - showPasswordDialog(); - break; - default: - return false; - } - return true; - } - } - - /** - * 新建笔记按钮触摸监听器 - *

- * 该类实现了OnTouchListener接口,用于处理新建笔记按钮的触摸事件, - * 特别是处理按钮透明部分的触摸事件,将其分发给下方的列表视图 - *

- */ - private class NewNoteOnTouchListener implements OnTouchListener { - - /** - * 处理触摸事件 - *

- * 该方法完成以下工作: - * 1. 处理ACTION_DOWN事件: - * - 获取屏幕高度和新建笔记按钮高度 - * - 计算触摸事件的Y坐标 - * - 如果当前状态是SUB_FOLDER,减去标题栏高度 - * - 检查触摸点是否在按钮的透明部分(根据公式y=-0.12x+94判断) - * - 如果是,将触摸事件分发给下方的列表视图 - * 2. 处理ACTION_MOVE事件: - * - 如果已经开始分发事件,更新事件坐标并继续分发给列表视图 - * 3. 处理其他事件: - * - 如果已经开始分发事件,结束分发并将事件分发给列表视图 - *

- * @param v 被触摸的视图 - * @param event 触摸事件 - * @return 是否消费了该事件,返回true表示已消费 - */ - public boolean onTouch(View v, MotionEvent event) { - switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: { - Display display = getWindowManager().getDefaultDisplay(); - int screenHeight = display.getHeight(); - int newNoteViewHeight = mAddNewNote.getHeight(); - int start = screenHeight - newNoteViewHeight; - int eventY = start + (int) event.getY(); - /** - * Minus TitleBar's height - */ - if (mState == ListEditState.SUB_FOLDER) { - eventY -= mTitleBar.getHeight(); - start -= mTitleBar.getHeight(); - } - /** - * HACKME:When click the transparent part of "New Note" button, dispatch - * the event to the list view behind this button. The transparent part of - * "New Note" button could be expressed by formula y=-0.12x+94(Unit:pixel) - * and the line top of the button. The coordinate based on left of the "New - * Note" button. The 94 represents maximum height of the transparent part. - * Notice that, if the background of the button changes, the formula should - * also change. This is very bad, just for the UI designer's strong requirement. - */ - if (event.getY() < (event.getX() * (-0.12) + 94)) { - View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 - - mNotesListView.getFooterViewsCount()); - if (view != null && view.getBottom() > start - && (view.getTop() < (start + 94))) { - mOriginY = (int) event.getY(); - mDispatchY = eventY; - event.setLocation(event.getX(), mDispatchY); - mDispatch = true; - return mNotesListView.dispatchTouchEvent(event); - } - } - break; - } - case MotionEvent.ACTION_MOVE: { - if (mDispatch) { - mDispatchY += (int) event.getY() - mOriginY; - event.setLocation(event.getX(), mDispatchY); - return mNotesListView.dispatchTouchEvent(event); - } - break; - } - default: { - if (mDispatch) { - event.setLocation(event.getX(), mDispatchY); - mDispatch = false; - return mNotesListView.dispatchTouchEvent(event); - } - break; - } - } - return false; - } - - }; - - /** - * 启动异步笔记列表查询 - *

- * 该方法根据当前文件夹ID选择合适的查询条件,然后启动异步查询,查询结果将通过BackgroundQueryHandler返回 - *

- */ - private void startAsyncNotesListQuery() { - String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION - : NORMAL_SELECTION; - mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, - Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { - String.valueOf(mCurrentFolderId) - }, NoteColumns.PINNED + " DESC," + NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); - } - - /** - * 后台查询处理器类 - *

- * 该类继承自AsyncQueryHandler,用于处理异步查询操作, - * 主要处理两种查询: - * 1. 文件夹笔记列表查询 - * 2. 文件夹列表查询 - *

- */ - private final class BackgroundQueryHandler extends AsyncQueryHandler { - /** - * 构造函数 - * @param contentResolver 内容解析器 - */ - public BackgroundQueryHandler(ContentResolver contentResolver) { - super(contentResolver); - } - - /** - * 查询完成时调用 - *

- * 该方法根据查询令牌处理查询结果: - * 1. 如果是文件夹笔记列表查询,将结果游标设置给列表适配器 - * 2. 如果是文件夹列表查询,显示文件夹列表菜单 - *

- * @param token 查询令牌,用于标识查询类型 - * @param cookie 查询时传递的附加数据,此处未使用 - * @param cursor 查询结果游标 - */ - @Override - protected void onQueryComplete(int token, Object cookie, Cursor cursor) { - switch (token) { - case FOLDER_NOTE_LIST_QUERY_TOKEN: - mNotesListAdapter.changeCursor(cursor); - break; - case FOLDER_LIST_QUERY_TOKEN: - if (cursor != null && cursor.getCount() > 0) { - showFolderListMenu(cursor); - } else { - Log.e(TAG, "Query folder failed"); - } - break; - default: - return; - } - } - } - - private void showFolderListMenu(Cursor cursor) { - AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); - builder.setTitle(R.string.menu_title_select_folder); - final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); - builder.setAdapter(adapter, new DialogInterface.OnClickListener() { - - public void onClick(DialogInterface dialog, int which) { - DataUtils.batchMoveToFolder(mContentResolver, - mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); - Toast.makeText( - NotesListActivity.this, - getString(R.string.format_move_notes_to_folder, - mNotesListAdapter.getSelectedCount(), - adapter.getFolderName(NotesListActivity.this, which)), - Toast.LENGTH_SHORT).show(); - mModeCallBack.finishActionMode(); - } - }); - builder.show(); - } - - /** - * 创建新笔记 - *

- * 该方法通过启动NoteEditActivity来创建新笔记,并传递当前文件夹ID作为额外参数 - *

- */ - private void createNewNote() { - Intent intent = new Intent(this, NoteEditActivity.class); - intent.setAction(Intent.ACTION_INSERT_OR_EDIT); - intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); - this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); - } - - /** - * 批量删除笔记 - *

- * 该方法在异步任务中完成以下工作: - * 1. 获取选中的部件属性 - * 2. 如果当前在回收站内部,直接永久删除选中的笔记 - * 3. 如果当前不在回收站内部,将选中的笔记移动到回收站 - * 4. 更新相关部件 - * 5. 结束多选模式 - *

- */ - private void batchDelete() { - new AsyncTask>() { - protected HashSet doInBackground(Void... unused) { - HashSet widgets = mNotesListAdapter.getSelectedWidget(); - - if (mCurrentFolderId == Notes.ID_TRASH_FOLER) { - // 在回收站内部,直接永久删除 - if (!DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter.getSelectedItemIds())) { - Log.e(TAG, "Delete notes error, should not happens"); - } - } else { - // 在回收站外部,移动到回收站 - if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter - .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) { - Log.e(TAG, "Move notes to trash folder error, should not happens"); - } - } - return widgets; - } - - @Override - protected void onPostExecute(HashSet widgets) { - if (widgets != null) { - for (AppWidgetAttribute widget : widgets) { - if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID - && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { - updateWidget(widget.widgetId, widget.widgetType); - } - } - } - mModeCallBack.finishActionMode(); - } - }.execute(); - } - - /** - * 批量恢复回收站中的项目 - *

- * 该方法在异步任务中完成以下工作: - * 1. 获取选中的项目ID - * 2. 对于每个项目,查询其原始父文件夹ID - * 3. 将项目移动回原始父文件夹(如果原始父文件夹不存在或也在回收站中,则移动到根文件夹) - * 4. 更新相关部件 - * 5. 结束动作模式 - *

- */ - private void batchRestore() { - new AsyncTask>() { - protected HashSet doInBackground(Void... unused) { - HashSet widgets = mNotesListAdapter.getSelectedWidget(); - HashSet selectedIds = mNotesListAdapter.getSelectedItemIds(); - - for (Long itemId : selectedIds) { - try { - // 查询项目的原始父文件夹ID - String[] projection = {NoteColumns.ORIGIN_PARENT_ID, NoteColumns.ID}; - String selection = NoteColumns.ID + "=" + itemId; - - Cursor cursor = mContentResolver.query( - Notes.CONTENT_NOTE_URI, - projection, - selection, - null, - null - ); - - if (cursor != null && cursor.moveToFirst()) { - long originParentId = cursor.getLong(0); - long currentId = cursor.getLong(1); - cursor.close(); - - // 检查原始父文件夹是否存在且不在回收站中 - long targetParentId = originParentId; - - // 查询原始父文件夹的信息 - Cursor folderCursor = mContentResolver.query( - Notes.CONTENT_NOTE_URI, - new String[]{NoteColumns.PARENT_ID}, - NoteColumns.ID + "=" + originParentId, - null, - null - ); - - boolean isValidFolder = false; - if (folderCursor != null) { - if (folderCursor.moveToFirst()) { - long folderParentId = folderCursor.getLong(0); - // 检查原始父文件夹是否在回收站中 - if (folderParentId != Notes.ID_TRASH_FOLER) { - isValidFolder = true; - } - } - folderCursor.close(); - } - - // 如果原始父文件夹无效,使用根文件夹 - if (!isValidFolder) { - targetParentId = Notes.ID_ROOT_FOLDER; - } - - // 移动项目回原始父文件夹或根文件夹 - HashSet ids = new HashSet(); - ids.add(currentId); - if (!DataUtils.batchMoveToFolder(mContentResolver, ids, targetParentId)) { - Log.e(TAG, "Restore item error: " + currentId); - } - } else if (cursor != null) { - cursor.close(); - } - } catch (Exception e) { - Log.e(TAG, "Failed to restore item: " + itemId, e); - } - } - - return widgets; - } - - @Override - protected void onPostExecute(HashSet widgets) { - if (widgets != null) { - for (AppWidgetAttribute widget : widgets) { - if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID - && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { - updateWidget(widget.widgetId, widget.widgetType); - } - } - } - mModeCallBack.finishActionMode(); - } - }.execute(); - } - - /** - * 切换选中便签的置顶状态 - */ - private void togglePinnedStatus() { - final HashSet selectedIds = mNotesListAdapter.getSelectedItemIds(); - final int selectedCount = mNotesListAdapter.getSelectedCount(); - - new AsyncTask() { - protected Void doInBackground(Void... unused) { - for (Long noteId : selectedIds) { - // 查询当前便签的置顶状态 - Cursor cursor = mContentResolver.query(Notes.CONTENT_NOTE_URI, - new String[]{NoteColumns.PINNED}, - NoteColumns.ID + "=?", - new String[]{String.valueOf(noteId)}, - null); - - if (cursor != null && cursor.moveToFirst()) { - int currentPinned = cursor.getInt(0); - // 切换置顶状态 - int newPinned = currentPinned == 1 ? 0 : 1; - - ContentValues values = new ContentValues(); - values.put(NoteColumns.PINNED, newPinned); - - mContentResolver.update(Notes.CONTENT_NOTE_URI, - values, - NoteColumns.ID + "=?", - new String[]{String.valueOf(noteId)}); - - cursor.close(); - } - } - return null; - } - - @Override - protected void onPostExecute(Void unused) { - Toast.makeText(NotesListActivity.this, - "已更新 " + selectedCount + " 个便签", - Toast.LENGTH_SHORT).show(); - // 重新查询数据,更新列表 - startAsyncNotesListQuery(); - mModeCallBack.finishActionMode(); - } - }.execute(); - } - - /** - * 删除文件夹 - *

- * 该方法完成以下工作: - * 1. 检查文件夹ID是否为根文件夹ID,如果是则返回错误 - * 2. 获取文件夹的部件属性 - * 3. 如果文件夹在回收站外部,将其移动到回收站 - * 4. 如果文件夹在回收站内部,直接永久删除 - * 5. 更新相关部件 - *

- * @param folderId 要删除的文件夹ID - */ - private void deleteFolder(long folderId) { - if (folderId == Notes.ID_ROOT_FOLDER) { - Log.e(TAG, "Wrong folder id, should not happen " + folderId); - return; - } - - HashSet ids = new HashSet(); - ids.add(folderId); - HashSet widgets = DataUtils.getFolderNoteWidget(mContentResolver, - folderId); - - if (mCurrentFolderId == Notes.ID_TRASH_FOLER) { - // 在回收站内部,直接永久删除 - if (!DataUtils.batchDeleteNotes(mContentResolver, ids)) { - Log.e(TAG, "Delete folder error, should not happens"); - } - } else { - // 在回收站外部,移动到回收站 - DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER); - } - - if (widgets != null) { - for (AppWidgetAttribute widget : widgets) { - if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID - && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { - updateWidget(widget.widgetId, widget.widgetType); - } - } - } - } - - /** - * 打开笔记 - *

- * 该方法通过启动NoteEditActivity来打开指定的笔记,传递笔记ID作为额外参数 - *

- * @param data 要打开的笔记数据项 - */ - private void openNode(final NoteItemData data) { - // 检查笔记是否被锁定 - if (data.isLocked()) { - final EditText passwordEditText = new EditText(this); - passwordEditText.setHint(R.string.hint_enter_password); - passwordEditText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); - - new AlertDialog.Builder(this) - .setTitle(R.string.dialog_enter_password) - .setView(passwordEditText) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - String password = passwordEditText.getText().toString(); - if (!TextUtils.isEmpty(password)) { - verifyPasswordAndOpenNote(data.getId(), password); - } - } - }) - .setNegativeButton(android.R.string.cancel, null) - .show(); - } else { - // 未锁定,直接打开笔记 - Intent intent = new Intent(this, NoteEditActivity.class); - intent.setAction(Intent.ACTION_VIEW); - intent.putExtra(Intent.EXTRA_UID, data.getId()); - startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); - } - } - - /** - * 验证密码并打开笔记 - *

- * 该方法完成以下工作: - * 1. 查询笔记的加密密码 - * 2. 验证密码是否正确 - * 3. 如果正确,打开笔记;否则显示错误信息 - *

- * @param noteId 笔记ID - * @param password 用户输入的密码 - */ - private void verifyPasswordAndOpenNote(final long noteId, String password) { - // 查询笔记的加密密码 - String[] projection = {NoteColumns.LOCK_PASSWORD}; - String selection = NoteColumns.ID + "=?"; - String[] selectionArgs = {String.valueOf(noteId)}; - - Cursor cursor = getContentResolver().query(Notes.CONTENT_NOTE_URI, projection, selection, selectionArgs, null); - String encryptedPassword = null; - - if (cursor != null && cursor.moveToFirst()) { - encryptedPassword = cursor.getString(0); - cursor.close(); - } - - // 验证密码是否正确 - if (encryptedPassword != null && encryptedPassword.equals(encryptPassword(password))) { - // 密码正确,打开笔记 - Intent intent = new Intent(this, NoteEditActivity.class); - intent.setAction(Intent.ACTION_VIEW); - intent.putExtra(Intent.EXTRA_UID, noteId); - startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); - } else { - // 密码错误,显示错误信息 - Toast.makeText(this, getString(R.string.error_wrong_password), Toast.LENGTH_SHORT).show(); - } - } - - /** - * 打开文件夹 - *

- * 该方法完成以下工作: - * 1. 设置当前文件夹ID - * 2. 启动异步笔记列表查询 - * 3. 根据文件夹类型设置列表状态: - * - 如果是通话记录文件夹,设置为CALL_RECORD_FOLDER状态并隐藏新建笔记按钮 - * - 否则设置为SUB_FOLDER状态 - * 4. 设置标题栏文本和可见性 - *

- * @param data 要打开的文件夹数据项 - */ - private void openFolder(NoteItemData data) { - mCurrentFolderId = data.getId(); - startAsyncNotesListQuery(); - if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { - mState = ListEditState.CALL_RECORD_FOLDER; - mAddNewNote.setVisibility(View.GONE); - } else { - mState = ListEditState.SUB_FOLDER; - } - if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { - mTitleBar.setText(R.string.call_record_folder_name); - } else { - mTitleBar.setText(data.getSnippet()); - } - mTitleBar.setVisibility(View.VISIBLE); - } - - /** - * 处理点击事件 - *

- * 该方法处理视图的点击事件,目前只处理新建笔记按钮的点击事件 - *

- * @param v 被点击的视图 - */ - public void onClick(View v) { - switch (v.getId()) { - case R.id.btn_new_note: - createNewNote(); - break; - default: - break; - } - } - - /** - * 显示软键盘 - *

- * 该方法通过InputMethodManager显示软键盘 - *

- */ - private void showSoftInput() { - InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - if (inputMethodManager != null) { - inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - } - } - - /** - * 隐藏软键盘 - *

- * 该方法通过InputMethodManager隐藏软键盘 - *

- * @param view 用于获取窗口令牌的视图 - */ - private void hideSoftInput(View view) { - InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); - } - - /** - * 显示创建或修改文件夹对话框 - *

- * 该方法完成以下工作: - * 1. 创建对话框构建器 - * 2. 加载布局文件 - * 3. 显示软键盘 - * 4. 根据create参数设置对话框标题和编辑框内容: - * - 如果是修改文件夹,设置标题为"修改文件夹名称",并显示当前文件夹名称 - * - 如果是创建文件夹,设置标题为"创建文件夹",并清空编辑框 - * 5. 设置对话框按钮和点击事件 - * 6. 显示对话框 - * 7. 为确定按钮设置点击事件,处理文件夹的创建或修改 - * 8. 为编辑框添加文本变化监听器,当文本为空时禁用确定按钮 - *

- * @param create 是否是创建文件夹,true表示创建,false表示修改 - */ - private void showCreateOrModifyFolderDialog(final boolean create) { - final AlertDialog.Builder builder = new AlertDialog.Builder(this); - View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); - final EditText etName = (EditText) view.findViewById(R.id.et_foler_name); - showSoftInput(); - if (!create) { - if (mFocusNoteDataItem != null) { - etName.setText(mFocusNoteDataItem.getSnippet()); - builder.setTitle(getString(R.string.menu_folder_change_name)); - } else { - Log.e(TAG, "The long click data item is null"); - return; - } - } else { - etName.setText(""); - builder.setTitle(this.getString(R.string.menu_create_folder)); - } - - builder.setPositiveButton(android.R.string.ok, null); - builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - hideSoftInput(etName); - } - }); - - final Dialog dialog = builder.setView(view).show(); - final Button positive = (Button)dialog.findViewById(android.R.id.button1); - positive.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - hideSoftInput(etName); - String name = etName.getText().toString(); - if (DataUtils.checkVisibleFolderName(mContentResolver, name, mCurrentFolderId)) { - Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), - Toast.LENGTH_LONG).show(); - etName.setSelection(0, etName.length()); - return; - } - if (!create) { - if (!TextUtils.isEmpty(name)) { - ContentValues values = new ContentValues(); - values.put(NoteColumns.SNIPPET, name); - values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); - values.put(NoteColumns.LOCAL_MODIFIED, 1); - mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID - + "=?", new String[] { - String.valueOf(mFocusNoteDataItem.getId()) - }); - } - } else if (!TextUtils.isEmpty(name)) { - ContentValues values = new ContentValues(); - values.put(NoteColumns.SNIPPET, name); - values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); - values.put(NoteColumns.PARENT_ID, mCurrentFolderId); - mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); - } - dialog.dismiss(); - } - }); - - if (TextUtils.isEmpty(etName.getText())) { - positive.setEnabled(false); - } - /** - * When the name edit text is null, disable the positive button - */ - etName.addTextChangedListener(new TextWatcher() { - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - // TODO Auto-generated method stub - - } - - public void onTextChanged(CharSequence s, int start, int before, int count) { - if (TextUtils.isEmpty(etName.getText())) { - positive.setEnabled(false); - } else { - positive.setEnabled(true); - } - } - - public void afterTextChanged(Editable s) { - // TODO Auto-generated method stub - - } - }); - } - - /** - * 处理返回按钮点击事件 - *

- * 该方法根据当前状态处理返回按钮点击事件: - * 1. 如果在子文件夹中,返回根文件夹 - * 2. 如果在通话记录文件夹中,返回根文件夹并显示新建笔记按钮 - * 3. 如果在根文件夹中,调用默认的返回处理 - *

- */ - private void handleBackPress() { - switch (mState) { - case SUB_FOLDER: - // 查询当前文件夹的父文件夹ID - Cursor cursor = mContentResolver.query(Notes.CONTENT_NOTE_URI, - new String[]{NoteColumns.PARENT_ID, NoteColumns.SNIPPET}, - NoteColumns.ID + "=?", - new String[]{String.valueOf(mCurrentFolderId)}, - null); - - if (cursor != null && cursor.moveToFirst()) { - long parentId = cursor.getLong(0); - String parentName = cursor.getString(1); - cursor.close(); - - if (parentId == Notes.ID_ROOT_FOLDER) { - // 如果父文件夹是根文件夹,返回根目录 - mCurrentFolderId = Notes.ID_ROOT_FOLDER; - mState = ListEditState.NOTE_LIST; - mTitleBar.setVisibility(View.GONE); - } else { - // 否则返回上一级文件夹 - mCurrentFolderId = parentId; - mState = ListEditState.SUB_FOLDER; - mTitleBar.setText(parentName); - mTitleBar.setVisibility(View.VISIBLE); - } - startAsyncNotesListQuery(); - } - break; - case CALL_RECORD_FOLDER: - mCurrentFolderId = Notes.ID_ROOT_FOLDER; - mState = ListEditState.NOTE_LIST; - mAddNewNote.setVisibility(View.VISIBLE); - mTitleBar.setVisibility(View.GONE); - startAsyncNotesListQuery(); - break; - case NOTE_LIST: - super.onBackPressed(); - break; - default: - break; - } - } - - @Override - public void onBackPressed() { - handleBackPress(); - } - - /** - * 更新部件 - *

- * 该方法完成以下工作: - * 1. 创建广播意图 - * 2. 根据部件类型设置广播接收者: - * - 如果是2x2部件,设置接收者为NoteWidgetProvider_2x - * - 如果是4x4部件,设置接收者为NoteWidgetProvider_4x - * - 否则记录错误并返回 - * 3. 添加部件ID到意图中 - * 4. 发送广播 - * 5. 设置结果 - *

- * @param appWidgetId 部件ID - * @param appWidgetType 部件类型 - */ - private void updateWidget(int appWidgetId, int appWidgetType) { - Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - if (appWidgetType == Notes.TYPE_WIDGET_2X) { - intent.setClass(this, NoteWidgetProvider_2x.class); - } else if (appWidgetType == Notes.TYPE_WIDGET_4X) { - intent.setClass(this, NoteWidgetProvider_4x.class); - } else { - Log.e(TAG, "Unspported widget type"); - return; - } - - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { - appWidgetId - }); - - sendBroadcast(intent); - setResult(RESULT_OK, intent); - } - - private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { - public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { - if (mFocusNoteDataItem != null) { - menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); - menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); - menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); - menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name); - } - } - }; - - @Override - public void onContextMenuClosed(Menu menu) { - if (mNotesListView != null) { - mNotesListView.setOnCreateContextMenuListener(null); - } - super.onContextMenuClosed(menu); - } - - @Override - public boolean onContextItemSelected(MenuItem item) { - if (mFocusNoteDataItem == null) { - Log.e(TAG, "The long click data item is null"); - return false; - } - switch (item.getItemId()) { - case MENU_FOLDER_VIEW: - openFolder(mFocusNoteDataItem); - break; - case MENU_FOLDER_DELETE: - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle(getString(R.string.alert_title_delete)); - builder.setIcon(android.R.drawable.ic_dialog_alert); - builder.setMessage(getString(R.string.alert_message_delete_folder)); - builder.setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - deleteFolder(mFocusNoteDataItem.getId()); - } - }); - builder.setNegativeButton(android.R.string.cancel, null); - builder.show(); - break; - case MENU_FOLDER_CHANGE_NAME: - showCreateOrModifyFolderDialog(false); - break; - default: - break; - } - - return true; - } - - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - menu.clear(); - if (mState == ListEditState.NOTE_LIST) { - getMenuInflater().inflate(R.menu.note_list, menu); - // set sync or sync_cancel - menu.findItem(R.id.menu_sync).setTitle( - GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); - } else if (mState == ListEditState.SUB_FOLDER) { - getMenuInflater().inflate(R.menu.sub_folder, menu); - } else if (mState == ListEditState.CALL_RECORD_FOLDER) { - getMenuInflater().inflate(R.menu.call_record_folder, menu); - } else { - Log.e(TAG, "Wrong state:" + mState); - } - return true; - } - - /** - * 处理选项菜单点击事件 - *

- * 该方法处理以下菜单项的点击事件: - * 1. 新建文件夹:显示创建文件夹对话框 - * 2. 导出文本:调用exportNoteToText方法导出笔记 - * 3. 同步: - * - 如果在同步模式下,根据当前标题判断是开始同步还是取消同步 - * - 否则跳转到设置页面 - * 4. 设置:跳转到设置页面 - * 5. 新建笔记:调用createNewNote方法创建新笔记 - * 6. 搜索:调用onSearchRequested方法启动搜索 - *

- * @param item 被点击的菜单项 - * @return 是否处理了该事件,返回true表示已处理 - */ - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.menu_new_folder: { - showCreateOrModifyFolderDialog(true); - break; - } - case R.id.menu_export_text: { - exportNoteToText(); - break; - } - case R.id.menu_sync: { - if (isSyncMode()) { - if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { - GTaskSyncService.startSync(this); - } else { - GTaskSyncService.cancelSync(this); - } - } else { - startPreferenceActivity(); - } - break; - } - case R.id.menu_setting: { - startPreferenceActivity(); - break; - } - case R.id.menu_new_note: { - createNewNote(); - break; - } - case R.id.menu_search: - onSearchRequested(); - break; - default: - break; - } - return true; - } - - /** - * 处理搜索请求 - *

- * 该方法启动搜索活动 - *

- * @return 是否处理了搜索请求,返回true表示已处理 - */ - @Override - public boolean onSearchRequested() { - startSearch(null, false, null /* appData */, false); - return true; - } - - /** - * 导出笔记到文本文件 - *

- * 该方法在异步任务中完成以下工作: - * 1. 获取BackupUtils实例 - * 2. 在后台调用exportToText方法导出笔记 - * 3. 根据导出结果显示不同的对话框: - * - 如果SD卡未挂载,显示失败对话框 - * - 如果导出成功,显示成功对话框并显示导出文件的位置 - * - 如果系统错误,显示失败对话框 - *

- */ - private void exportNoteToText() { - final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); - new AsyncTask() { - - @Override - protected Integer doInBackground(Void... unused) { - return backup.exportToText(); - } - - @Override - protected void onPostExecute(Integer result) { - if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { - AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); - builder.setTitle(NotesListActivity.this - .getString(R.string.failed_sdcard_export)); - builder.setMessage(NotesListActivity.this - .getString(R.string.error_sdcard_unmounted)); - builder.setPositiveButton(android.R.string.ok, null); - builder.show(); - } else if (result == BackupUtils.STATE_SUCCESS) { - AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); - builder.setTitle(NotesListActivity.this - .getString(R.string.success_sdcard_export)); - builder.setMessage(NotesListActivity.this.getString( - R.string.format_exported_file_location, backup - .getExportedTextFileName(), backup.getExportedTextFileDir())); - builder.setPositiveButton(android.R.string.ok, null); - builder.show(); - } else if (result == BackupUtils.STATE_SYSTEM_ERROR) { - AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); - builder.setTitle(NotesListActivity.this - .getString(R.string.failed_sdcard_export)); - builder.setMessage(NotesListActivity.this - .getString(R.string.error_sdcard_export)); - builder.setPositiveButton(android.R.string.ok, null); - builder.show(); - } - } - - }.execute(); - } - - /** - * 检查是否处于同步模式 - *

- * 该方法通过获取同步账户名来检查是否处于同步模式,如果同步账户名不为空则处于同步模式 - *

- * @return 是否处于同步模式,true表示处于同步模式,false表示不处于同步模式 - */ - private boolean isSyncMode() { - return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; - } - - /** - * 启动偏好设置活动 - *

- * 该方法完成以下工作: - * 1. 获取当前活动或父活动 - * 2. 创建意图,跳转到NotesPreferenceActivity - * 3. 启动活动 - *

- */ - private void startPreferenceActivity() { - Activity from = getParent() != null ? getParent() : this; - Intent intent = new Intent(from, NotesPreferenceActivity.class); - from.startActivityIfNeeded(intent, -1); - } - - /** - * 列表项点击监听器类 - *

- * 该类实现了OnItemClickListener接口,用于处理列表项的点击事件, - * 根据当前状态和点击的列表项类型执行不同的操作 - *

- */ - private class OnListItemClickListener implements OnItemClickListener { - - /** - * 处理列表项点击事件 - *

- * 该方法完成以下工作: - * 1. 检查被点击的视图是否是NotesListItem - * 2. 获取被点击的笔记数据项 - * 3. 如果在选择模式下: - * - 如果是笔记类型,切换选中状态 - * - 返回 - * 4. 根据当前状态和笔记类型执行不同的操作: - * - NOTE_LIST状态: - * - 如果是文件夹或系统类型,调用openFolder方法打开文件夹 - * - 如果是笔记类型,调用openNode方法打开笔记 - * - SUB_FOLDER或CALL_RECORD_FOLDER状态: - * - 如果是笔记类型,调用openNode方法打开笔记 - *

- * @param parent 父视图 - * @param view 被点击的视图 - * @param position 被点击的位置 - * @param id 被点击的ID - */ - public void onItemClick(AdapterView parent, View view, int position, long id) { - if (view instanceof NotesListItem) { - NoteItemData item = ((NotesListItem) view).getItemData(); - if (mNotesListAdapter.isInChoiceMode()) { - // 在选择模式下,允许选择所有类型的项 - // 但根文件夹不能被选中 - if (item.getId() != Notes.ID_ROOT_FOLDER) { - position = position - mNotesListView.getHeaderViewsCount(); - mModeCallBack.onItemCheckedStateChanged(null, position, id, - !mNotesListAdapter.isSelectedItem(position)); - } - return; - } - - switch (mState) { - case NOTE_LIST: - if (item.getType() == Notes.TYPE_FOLDER - || item.getType() == Notes.TYPE_SYSTEM) { - openFolder(item); - } else if (item.getType() == Notes.TYPE_NOTE) { - openNode(item); - } else { - Log.e(TAG, "Wrong note type in NOTE_LIST"); - } - break; - case SUB_FOLDER: - if (item.getType() == Notes.TYPE_NOTE) { - openNode(item); - } else if (item.getType() == Notes.TYPE_FOLDER) { - openFolder(item); - } else { - Log.e(TAG, "Wrong note type in SUB_FOLDER"); - } - break; - case CALL_RECORD_FOLDER: - if (item.getType() == Notes.TYPE_NOTE) { - openNode(item); - } else { - Log.e(TAG, "Wrong note type in CALL_RECORD_FOLDER"); - } - break; - default: - break; - } - } - } - - } - - /** - * 启动查询目标文件夹 - *

- * 该方法完成以下工作: - * 1. 构建查询条件: - * - 基本条件:类型为文件夹,父ID不等于回收站ID,ID不等于当前文件夹ID - * - 如果当前状态不是NOTE_LIST,添加根文件夹ID到条件中 - * 2. 启动异步查询,查询结果将通过BackgroundQueryHandler返回 - *

- */ - private void startQueryDestinationFolders() { - String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; - selection = (mState == ListEditState.NOTE_LIST) ? selection: - "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; - - mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, - null, - Notes.CONTENT_NOTE_URI, - FoldersListAdapter.PROJECTION, - selection, - new String[] { - String.valueOf(Notes.TYPE_FOLDER), - String.valueOf(Notes.ID_TRASH_FOLER), - String.valueOf(mCurrentFolderId) - }, - NoteColumns.MODIFIED_DATE + " DESC"); - } - - /** - * 处理列表项长按事件 - *

- * 该方法完成以下工作: - * 1. 检查被长按的视图是否是NotesListItem - * 2. 获取被长按的笔记数据项 - * 3. 根据笔记类型处理长按事件: - * - 如果是笔记类型且不在选择模式下,启动多选模式并选中当前项 - * - 如果是文件夹类型,设置上下文菜单监听器 - * 4. 返回false表示事件未被完全处理 - *

- * @param parent 父视图 - * @param view 被长按的视图 - * @param position 被长按的位置 - * @param id 被长按的ID - * @return 是否处理了该事件,返回false表示事件未被完全处理 - */ - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { - if (view instanceof NotesListItem) { - mFocusNoteDataItem = ((NotesListItem) view).getItemData(); - if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) { - if (mNotesListView.startActionMode(mModeCallBack) != null) { - mModeCallBack.onItemCheckedStateChanged(null, position, id, true); - mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); - } else { - Log.e(TAG, "startActionMode fails"); - } - } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { - mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); - } - } - return false; - } -} diff --git a/src/main/java/net/micode/notes/ui/NotesListAdapter.java b/src/main/java/net/micode/notes/ui/NotesListAdapter.java deleted file mode 100644 index 5b1a583..0000000 --- a/src/main/java/net/micode/notes/ui/NotesListAdapter.java +++ /dev/null @@ -1,326 +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.util.Log; -import android.view.View; -import android.view.ViewGroup; -import android.widget.CursorAdapter; - -import net.micode.notes.data.Notes; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; - - -/** - * 笔记列表适配器类 - *

- * 该类是CursorAdapter的子类,用于将数据库中的笔记数据绑定到列表视图上, - * 支持普通浏览模式和选择模式,能够管理选中的项目,并提供了各种方法来处理 - * 列表项的选择状态、获取选中项目ID等功能。 - *

- */ -public class NotesListAdapter extends CursorAdapter { - /** 日志标签 */ - private static final String TAG = "NotesListAdapter"; - /** 上下文对象 */ - private Context mContext; - /** 保存选中项目的位置和状态 */ - private HashMap mSelectedIndex; - /** 笔记数量 */ - private int mNotesCount; - /** 是否处于选择模式 */ - private boolean mChoiceMode; - - /** - * 应用桌面组件属性类 - *

- * 该类用于存储桌面组件的相关属性,包括组件ID和组件类型 - *

- */ - public static class AppWidgetAttribute { - /** 桌面组件ID */ - public int widgetId; - /** 桌面组件类型 */ - public int widgetType; - }; - - /** - * 构造函数 - *

- * 初始化NotesListAdapter,创建选中项目的映射表,并设置初始上下文和笔记数量 - *

- * @param context 上下文对象 - */ - public NotesListAdapter(Context context) { - super(context, null); - mSelectedIndex = new HashMap(); - mContext = context; - mNotesCount = 0; - } - - /** - * 创建新的列表项视图 - *

- * 该方法在需要为新的数据项创建视图时调用,返回一个新的NotesListItem实例 - *

- * @param context 上下文对象 - * @param cursor 数据游标 - * @param parent 父视图组 - * @return 新创建的列表项视图 - */ - @Override - public View newView(Context context, Cursor cursor, ViewGroup parent) { - return new NotesListItem(context); - } - - /** - * 将数据绑定到列表项视图 - *

- * 该方法在需要将数据绑定到现有视图时调用,将游标中的数据转换为NoteItemData对象, - * 并调用NotesListItem的bind方法将数据绑定到视图上 - *

- * @param view 要绑定数据的视图 - * @param context 上下文对象 - * @param cursor 数据游标 - */ - @Override - public void bindView(View view, Context context, Cursor cursor) { - if (view instanceof NotesListItem) { - NoteItemData itemData = new NoteItemData(context, cursor); - ((NotesListItem) view).bind(context, itemData, mChoiceMode, - isSelectedItem(cursor.getPosition())); - } - } - - /** - * 设置指定位置的项是否被选中 - *

- * 该方法用于在选择模式下设置指定位置的项的选中状态,并通知数据集变化 - *

- * @param position 项的位置 - * @param checked 是否被选中 - */ - public void setCheckedItem(final int position, final boolean checked) { - mSelectedIndex.put(position, checked); - notifyDataSetChanged(); - } - - /** - * 检查是否处于选择模式 - * @return 是否处于选择模式 - */ - public boolean isInChoiceMode() { - return mChoiceMode; - } - - /** - * 设置是否进入选择模式 - *

- * 该方法用于切换选择模式,进入选择模式时会清除之前的选中状态 - *

- * @param mode 是否进入选择模式 - */ - public void setChoiceMode(boolean mode) { - mSelectedIndex.clear(); - mChoiceMode = mode; - } - - /** - * 全选或取消全选 - *

- * 该方法用于在选择模式下全选或取消全选所有普通笔记项 - * 在回收站内部时,也会选择文件夹类型的项 - *

- * @param checked 是否全选 - */ - public void selectAll(boolean checked) { - Cursor cursor = getCursor(); - for (int i = 0; i < getCount(); i++) { - if (cursor.moveToPosition(i)) { - // 获取当前项的类型 - int noteType = NoteItemData.getNoteType(cursor); - // 获取当前项的父文件夹ID - cursor.moveToPosition(i); - long parentId = cursor.getLong(8); // PARENT_ID列的索引是8 - - // 在回收站内部时,选择所有类型的项(除了根文件夹) - if (parentId == Notes.ID_TRASH_FOLER || noteType == Notes.TYPE_NOTE) { - setCheckedItem(i, checked); - } - } - } - } - - /** - * 获取所有选中项的ID - *

- * 该方法用于获取选择模式下所有选中项的ID集合,排除根文件夹ID - *

- * @return 选中项的ID集合 - */ - public HashSet getSelectedItemIds() { - HashSet itemSet = new HashSet(); - for (Integer position : mSelectedIndex.keySet()) { - if (mSelectedIndex.get(position) == true) { - Long id = getItemId(position); - if (id == Notes.ID_ROOT_FOLDER) { - Log.d(TAG, "Wrong item id, should not happen"); - } else { - itemSet.add(id); - } - } - } - - return itemSet; - } - - /** - * 获取所有选中的桌面组件属性 - *

- * 该方法用于获取选择模式下所有选中的桌面组件的属性集合 - *

- * @return 选中的桌面组件属性集合,若获取失败则返回null - */ - public HashSet getSelectedWidget() { - HashSet itemSet = new HashSet(); - for (Integer position : mSelectedIndex.keySet()) { - if (mSelectedIndex.get(position) == true) { - Cursor c = (Cursor) getItem(position); - if (c != null) { - AppWidgetAttribute widget = new AppWidgetAttribute(); - NoteItemData item = new NoteItemData(mContext, c); - widget.widgetId = item.getWidgetId(); - widget.widgetType = item.getWidgetType(); - itemSet.add(widget); - /** - * Don't close cursor here, only the adapter could close it - */ - } else { - Log.e(TAG, "Invalid cursor"); - return null; - } - } - } - return itemSet; - } - - /** - * 获取选中项的数量 - * @return 选中项的数量 - */ - public int getSelectedCount() { - Collection values = mSelectedIndex.values(); - if (null == values) { - return 0; - } - Iterator iter = values.iterator(); - int count = 0; - while (iter.hasNext()) { - if (true == iter.next()) { - count++; - } - } - return count; - } - - /** - * 检查是否所有可选中项都已选中 - * @return 是否所有可选中项都已选中 - */ - public boolean isAllSelected() { - int checkedCount = getSelectedCount(); - return (checkedCount != 0 && checkedCount == mNotesCount); - } - - /** - * 检查指定位置的项是否被选中 - * @param position 项的位置 - * @return 是否被选中 - */ - public boolean isSelectedItem(final int position) { - if (null == mSelectedIndex.get(position)) { - return false; - } - return mSelectedIndex.get(position); - } - - /** - * 当数据内容变化时调用 - *

- * 该方法在数据内容发生变化时被调用,会重新计算笔记数量 - *

- */ - @Override - protected void onContentChanged() { - super.onContentChanged(); - calcNotesCount(); - } - - /** - * 更换数据游标 - *

- * 该方法在更换数据游标时被调用,会重新计算笔记数量 - *

- * @param cursor 新的数据游标 - */ - @Override - public void changeCursor(Cursor cursor) { - super.changeCursor(cursor); - calcNotesCount(); - } - - /** - * 计算笔记数量 - *

- * 该方法用于统计当前数据集中的普通笔记数量,并更新mNotesCount成员变量 - *

- */ - private void calcNotesCount() { - mNotesCount = 0; - Cursor cursor = getCursor(); - if (cursor != null && !cursor.isClosed()) { - // 使用 try-finally 块确保 cursor 位置正确恢复 - int originalPosition = cursor.getPosition(); - try { - if (cursor.moveToFirst()) { - do { - try { - if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { - mNotesCount++; - } - } catch (Exception e) { - // 捕获可能的异常,避免崩溃 - Log.e(TAG, "Error calculating note count: " + e.getMessage()); - break; - } - } while (cursor.moveToNext()); - } - } finally { - // 恢复 cursor 到原始位置 - if (!cursor.isClosed()) { - cursor.moveToPosition(originalPosition); - } - } - } - } -} diff --git a/src/main/java/net/micode/notes/ui/NotesListItem.java b/src/main/java/net/micode/notes/ui/NotesListItem.java deleted file mode 100644 index 069771a..0000000 --- a/src/main/java/net/micode/notes/ui/NotesListItem.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.micode.notes.ui; - -import android.content.Context; -import android.text.Html; -import android.text.format.DateUtils; -import android.view.View; -import android.widget.CheckBox; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.tool.DataUtils; -import net.micode.notes.tool.ResourceParser.NoteItemBgResources; - - -/** - * 笔记列表项视图类 - *

- * 该类用于显示笔记列表中的单个条目,包含笔记的标题、时间、提醒图标等UI元素, - * 并能根据不同的笔记类型(普通笔记、文件夹、通话记录)和状态(选择模式、是否有提醒) - * 进行动态展示和样式调整 - *

- */ -public class NotesListItem extends LinearLayout { - /** 提醒图标,用于显示笔记是否设置了提醒 */ - private ImageView mAlert; - /** 笔记标题文本视图 */ - private TextView mTitle; - /** 笔记时间文本视图 */ - private TextView mTime; - /** 通话记录名称文本视图 */ - private TextView mCallName; - /** 列表项数据对象,存储笔记的相关信息 */ - private NoteItemData mItemData; - /** 选择框,用于选择模式下选择笔记 */ - private CheckBox mCheckBox; - - /** - * 构造函数 - *

- * 初始化NotesListItem视图,加载布局文件并获取各个UI组件的引用 - *

- * @param context 上下文对象 - */ - public NotesListItem(Context context) { - super(context); - inflate(context, R.layout.note_item, this); - mAlert = (ImageView) findViewById(R.id.iv_alert_icon); - mTitle = (TextView) findViewById(R.id.tv_title); - mTime = (TextView) findViewById(R.id.tv_time); - mCallName = (TextView) findViewById(R.id.tv_name); - mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); - } - - /** - * 将笔记数据绑定到列表项视图 - *

- * 该方法根据笔记数据的类型和状态,动态调整列表项的UI显示,包括: - * 1. 根据选择模式和笔记类型决定是否显示复选框 - * 2. 根据笔记类型(通话记录文件夹、普通通话记录、普通笔记、文件夹)设置不同的UI样式 - * 3. 设置标题、时间、提醒图标等内容 - * 4. 调用setBackground方法设置背景样式 - *

- * @param context 上下文对象 - * @param data 笔记列表项数据 - * @param choiceMode 是否处于选择模式 - * @param checked 选择模式下是否被选中 - */ - public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { - if (choiceMode && data.getType() == Notes.TYPE_NOTE) { - mCheckBox.setVisibility(View.VISIBLE); - mCheckBox.setChecked(checked); - } else { - mCheckBox.setVisibility(View.GONE); - } - - mItemData = data; - if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { - mCallName.setVisibility(View.GONE); - mAlert.setVisibility(View.VISIBLE); - mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); - mTitle.setText(context.getString(R.string.call_record_folder_name) - + context.getString(R.string.format_folder_files_count, data.getNotesCount())); - mAlert.setImageResource(R.drawable.call_record); - } else if (data.getId() == Notes.ID_TRASH_FOLER) { - mCallName.setVisibility(View.GONE); - mAlert.setVisibility(View.VISIBLE); - mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); - mTitle.setText("回收站" - + context.getString(R.string.format_folder_files_count, data.getNotesCount())); - mAlert.setImageResource(R.drawable.delete); - } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { - mCallName.setVisibility(View.VISIBLE); - mCallName.setText(data.getCallName()); - mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); - mTitle.setText(Html.fromHtml(DataUtils.getFormattedSnippet(data.getSnippet()))); - if (data.hasAlert()) { - mAlert.setImageResource(R.drawable.clock); - mAlert.setVisibility(View.VISIBLE); - } else { - mAlert.setVisibility(View.GONE); - } - } else { - mCallName.setVisibility(View.GONE); - mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); - - if (data.getType() == Notes.TYPE_FOLDER) { - mTitle.setText(data.getSnippet() - + context.getString(R.string.format_folder_files_count, - data.getNotesCount())); - mAlert.setVisibility(View.GONE); - } else { - mTitle.setText(Html.fromHtml(DataUtils.getFormattedSnippet(data.getSnippet()))); - if (data.hasAlert()) { - mAlert.setImageResource(R.drawable.clock); - mAlert.setVisibility(View.VISIBLE); - } else { - mAlert.setVisibility(View.GONE); - } - } - } - // 根据笔记是否在回收站中显示不同的时间 - if (data.getParentId() == Notes.ID_TRASH_FOLER || data.isDeleted()) { - // 回收站中的项显示删除时间 - mTime.setText(context.getString(R.string.deleted_time_format, - DateUtils.getRelativeTimeSpanString(data.getDeletedDate()))); - } else { - // 普通项显示修改时间 - mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); - } - - setBackground(data); - } - - /** - * 设置列表项的背景样式 - *

- * 该方法根据笔记数据的类型和状态,选择并设置合适的背景资源: - * 1. 对于普通笔记,根据其在列表中的位置(单个、第一个、最后一个、中间)选择不同的背景 - * 2. 对于文件夹或其他类型,使用默认的文件夹背景 - *

- * @param data 笔记列表项数据,包含背景颜色ID、类型和位置信息 - */ - private void setBackground(NoteItemData data) { - int id = data.getBgColorId(); - if (data.getType() == Notes.TYPE_NOTE) { - if (data.isSingle() || data.isOneFollowingFolder()) { - setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); - } else if (data.isLast()) { - setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); - } else if (data.isFirst() || data.isMultiFollowingFolder()) { - setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); - } else { - setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); - } - } else { - setBackgroundResource(NoteItemBgResources.getFolderBgRes()); - } - } - - /** - * 获取列表项的数据对象 - * @return 笔记列表项数据对象 - */ - public NoteItemData getItemData() { - return mItemData; - } -} diff --git a/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java b/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java deleted file mode 100644 index 5cca48d..0000000 --- a/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java +++ /dev/null @@ -1,554 +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.accounts.Account; -import android.accounts.AccountManager; -import android.app.ActionBar; -import android.app.AlertDialog; -import android.content.BroadcastReceiver; -import android.content.ContentValues; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.Preference; -import android.preference.Preference.OnPreferenceClickListener; -import android.preference.PreferenceActivity; -import android.preference.PreferenceCategory; -import android.text.TextUtils; -import android.text.format.DateFormat; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.Button; -import android.widget.TextView; -import android.widget.Toast; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.remote.GTaskSyncService; - - -/** - * 笔记偏好设置活动类 - *

- * 该类用于处理笔记应用的设置,包括同步账户管理、背景颜色设置等功能, - * 提供了UI界面让用户进行偏好设置,并与GTaskSyncService进行交互实现同步功能 - *

- */ -public class NotesPreferenceActivity extends PreferenceActivity { - /** 偏好设置文件名 */ - public static final String PREFERENCE_NAME = "notes_preferences"; - - /** 同步账户名的偏好键 */ - public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; - - /** 最后同步时间的偏好键 */ - public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; - - /** 背景颜色随机出现的偏好键 */ - public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; - - /** 同步账户的偏好键 */ - private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; - - /** 权限过滤器键 */ - private static final String AUTHORITIES_FILTER_KEY = "authorities"; - - /** 账户偏好设置分类 */ - private PreferenceCategory mAccountCategory; - - /** GTask同步服务广播接收器 */ - private GTaskReceiver mReceiver; - - /** 原始账户列表 */ - private Account[] mOriAccounts; - - /** 是否添加了新账户 */ - private boolean mHasAddedAccount; - - /** - * 活动创建时调用 - *

- * 该方法完成以下工作: - * 1. 设置导航栏显示应用图标 - * 2. 加载偏好设置资源 - * 3. 初始化账户偏好设置分类 - * 4. 注册GTask同步服务广播接收器 - * 5. 为列表视图添加头部 - *

- * @param icicle 保存的实例状态 - */ - @Override - protected void onCreate(Bundle icicle) { - super.onCreate(icicle); - - /* using the app icon for navigation */ - getActionBar().setDisplayHomeAsUpEnabled(true); - - addPreferencesFromResource(R.xml.preferences); - mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); - mReceiver = new GTaskReceiver(); - IntentFilter filter = new IntentFilter(); - filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); - registerReceiver(mReceiver, filter, Context.RECEIVER_EXPORTED); - - mOriAccounts = null; - View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); - getListView().addHeaderView(header, null, true); - } - - /** - * 活动恢复时调用 - *

- * 该方法完成以下工作: - * 1. 如果添加了新账户,自动设置同步账户 - * 2. 刷新UI界面 - *

- */ - @Override - protected void onResume() { - super.onResume(); - - // need to set sync account automatically if user has added a new - // account - if (mHasAddedAccount) { - Account[] accounts = getGoogleAccounts(); - if (mOriAccounts != null && accounts.length > mOriAccounts.length) { - for (Account accountNew : accounts) { - boolean found = false; - for (Account accountOld : mOriAccounts) { - if (TextUtils.equals(accountOld.name, accountNew.name)) { - found = true; - break; - } - } - if (!found) { - setSyncAccount(accountNew.name); - break; - } - } - } - } - - refreshUI(); - } - - /** - * 活动销毁时调用 - *

- * 该方法完成以下工作: - * 1. 注销GTask同步服务广播接收器 - *

- */ - @Override - protected void onDestroy() { - if (mReceiver != null) { - unregisterReceiver(mReceiver); - } - super.onDestroy(); - } - - /** - * 加载账户偏好设置 - *

- * 该方法完成以下工作: - * 1. 清空账户偏好设置分类中的所有偏好项 - * 2. 创建新的账户偏好项 - * 3. 设置账户偏好项的标题、摘要和点击监听器 - * 4. 根据当前同步状态和账户设置情况,决定点击时显示的对话框 - * 5. 将账户偏好项添加到分类中 - *

- */ - private void loadAccountPreference() { - mAccountCategory.removeAll(); - - Preference accountPref = new Preference(this); - final String defaultAccount = getSyncAccountName(this); - accountPref.setTitle(getString(R.string.preferences_account_title)); - accountPref.setSummary(getString(R.string.preferences_account_summary)); - accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference preference) { - if (!GTaskSyncService.isSyncing()) { - if (TextUtils.isEmpty(defaultAccount)) { - // the first time to set account - showSelectAccountAlertDialog(); - } else { - // if the account has already been set, we need to promp - // user about the risk - showChangeAccountConfirmAlertDialog(); - } - } else { - Toast.makeText(NotesPreferenceActivity.this, - R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) - .show(); - } - return true; - } - }); - - mAccountCategory.addPreference(accountPref); - } - - /** - * 加载同步按钮和状态 - *

- * 该方法完成以下工作: - * 1. 获取同步按钮和最后同步时间视图 - * 2. 根据同步状态设置按钮文本和点击事件 - * 3. 根据是否有同步账户设置按钮可用性 - * 4. 设置最后同步时间或同步进度 - *

- */ - private void loadSyncButton() { - Button syncButton = (Button) findViewById(R.id.preference_sync_button); - TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); - - // set button state - if (GTaskSyncService.isSyncing()) { - syncButton.setText(getString(R.string.preferences_button_sync_cancel)); - syncButton.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - GTaskSyncService.cancelSync(NotesPreferenceActivity.this); - } - }); - } else { - syncButton.setText(getString(R.string.preferences_button_sync_immediately)); - syncButton.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - GTaskSyncService.startSync(NotesPreferenceActivity.this); - } - }); - } - syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); - - // set last sync time - if (GTaskSyncService.isSyncing()) { - lastSyncTimeView.setText(GTaskSyncService.getProgressString()); - lastSyncTimeView.setVisibility(View.VISIBLE); - } else { - long lastSyncTime = getLastSyncTime(this); - if (lastSyncTime != 0) { - lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, - DateFormat.format(getString(R.string.preferences_last_sync_time_format), - lastSyncTime))); - lastSyncTimeView.setVisibility(View.VISIBLE); - } else { - lastSyncTimeView.setVisibility(View.GONE); - } - } - } - - /** - * 刷新UI界面 - *

- * 该方法调用loadAccountPreference和loadSyncButton方法来刷新UI界面 - *

- */ - private void refreshUI() { - loadAccountPreference(); - loadSyncButton(); - } - - /** - * 显示选择账户对话框 - *

- * 该方法完成以下工作: - * 1. 创建对话框构建器并设置自定义标题 - * 2. 获取Google账户列表 - * 3. 如果有账户,显示单选列表供用户选择 - * 4. 添加添加新账户的选项 - * 5. 处理用户选择事件 - *

- */ - private void showSelectAccountAlertDialog() { - AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); - - View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); - TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); - titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); - TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); - subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); - - dialogBuilder.setCustomTitle(titleView); - dialogBuilder.setPositiveButton(null, null); - - Account[] accounts = getGoogleAccounts(); - String defAccount = getSyncAccountName(this); - - mOriAccounts = accounts; - mHasAddedAccount = false; - - if (accounts.length > 0) { - CharSequence[] items = new CharSequence[accounts.length]; - final CharSequence[] itemMapping = items; - int checkedItem = -1; - int index = 0; - for (Account account : accounts) { - if (TextUtils.equals(account.name, defAccount)) { - checkedItem = index; - } - items[index++] = account.name; - } - dialogBuilder.setSingleChoiceItems(items, checkedItem, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - setSyncAccount(itemMapping[which].toString()); - dialog.dismiss(); - refreshUI(); - } - }); - } - - View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); - dialogBuilder.setView(addAccountView); - - final AlertDialog dialog = dialogBuilder.show(); - addAccountView.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - mHasAddedAccount = true; - Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); - intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { - "gmail-ls" - }); - startActivityForResult(intent, -1); - dialog.dismiss(); - } - }); - } - - /** - * 显示更改账户确认对话框 - *

- * 该方法完成以下工作: - * 1. 创建对话框构建器并设置自定义标题 - * 2. 添加选项:更改账户、移除账户、取消 - * 3. 处理用户选择事件 - *

- */ - private void showChangeAccountConfirmAlertDialog() { - AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); - - View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); - TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); - titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, - getSyncAccountName(this))); - TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); - subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); - dialogBuilder.setCustomTitle(titleView); - - CharSequence[] menuItemArray = new CharSequence[] { - getString(R.string.preferences_menu_change_account), - getString(R.string.preferences_menu_remove_account), - getString(R.string.preferences_menu_cancel) - }; - dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - if (which == 0) { - showSelectAccountAlertDialog(); - } else if (which == 1) { - removeSyncAccount(); - refreshUI(); - } - } - }); - dialogBuilder.show(); - } - - /** - * 获取Google账户列表 - *

- * 该方法通过AccountManager获取设备上的所有Google账户 - *

- * @return Google账户数组 - */ - private Account[] getGoogleAccounts() { - AccountManager accountManager = AccountManager.get(this); - return accountManager.getAccountsByType("com.google"); - } - - /** - * 设置同步账户 - *

- * 该方法完成以下工作: - * 1. 更新同步账户偏好设置 - * 2. 清除最后同步时间 - * 3. 清除本地GTask相关信息 - * 4. 显示成功提示 - *

- * @param account 要设置的同步账户名 - */ - private void setSyncAccount(String account) { - if (!getSyncAccountName(this).equals(account)) { - SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = settings.edit(); - if (account != null) { - editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); - } else { - editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); - } - editor.commit(); - - // clean up last sync time - setLastSyncTime(this, 0); - - // clean up local gtask related info - new Thread(new Runnable() { - public void run() { - ContentValues values = new ContentValues(); - values.put(NoteColumns.GTASK_ID, ""); - values.put(NoteColumns.SYNC_ID, 0); - getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); - } - }).start(); - - Toast.makeText(NotesPreferenceActivity.this, - getString(R.string.preferences_toast_success_set_accout, account), - Toast.LENGTH_SHORT).show(); - } - } - - /** - * 移除同步账户 - *

- * 该方法完成以下工作: - * 1. 移除同步账户偏好设置 - * 2. 移除最后同步时间偏好设置 - * 3. 清除本地GTask相关信息 - *

- */ - private void removeSyncAccount() { - SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = settings.edit(); - if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { - editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); - } - if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { - editor.remove(PREFERENCE_LAST_SYNC_TIME); - } - editor.commit(); - - // clean up local gtask related info - new Thread(new Runnable() { - public void run() { - ContentValues values = new ContentValues(); - values.put(NoteColumns.GTASK_ID, ""); - values.put(NoteColumns.SYNC_ID, 0); - getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); - } - }).start(); - } - - /** - * 获取同步账户名 - *

- * 该方法从偏好设置中获取同步账户名 - *

- * @param context 上下文对象 - * @return 同步账户名,如果未设置则返回空字符串 - */ - public static String getSyncAccountName(Context context) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, - Context.MODE_PRIVATE); - return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); - } - - /** - * 设置最后同步时间 - *

- * 该方法将最后同步时间保存到偏好设置中 - *

- * @param context 上下文对象 - * @param time 最后同步时间(毫秒) - */ - public static void setLastSyncTime(Context context, long time) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, - Context.MODE_PRIVATE); - SharedPreferences.Editor editor = settings.edit(); - editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); - editor.commit(); - } - - /** - * 获取最后同步时间 - *

- * 该方法从偏好设置中获取最后同步时间 - *

- * @param context 上下文对象 - * @return 最后同步时间(毫秒),如果未设置则返回0 - */ - public static long getLastSyncTime(Context context) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, - Context.MODE_PRIVATE); - return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); - } - - /** - * GTask同步服务广播接收器 - *

- * 该类用于接收GTaskSyncService发送的广播,更新UI界面和同步状态 - *

- */ - private class GTaskReceiver extends BroadcastReceiver { - - /** - * 接收广播时调用 - *

- * 该方法完成以下工作: - * 1. 刷新UI界面 - * 2. 如果正在同步,更新同步状态文本 - *

- * @param context 上下文对象 - * @param intent 广播意图,包含同步状态和进度信息 - */ - @Override - public void onReceive(Context context, Intent intent) { - refreshUI(); - if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { - TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); - syncStatus.setText(intent - .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); - } - - } - } - - /** - * 处理选项菜单点击事件 - *

- * 该方法处理选项菜单的点击事件,目前只处理了返回按钮的点击事件 - *

- * @param item 被点击的菜单项 - * @return 是否处理了该事件 - */ - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - Intent intent = new Intent(this, NotesListActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(intent); - return true; - default: - return false; - } - } -} diff --git a/src/main/java/net/micode/notes/ui/TemplateSelectActivity.java b/src/main/java/net/micode/notes/ui/TemplateSelectActivity.java deleted file mode 100644 index 46999d5..0000000 --- a/src/main/java/net/micode/notes/ui/TemplateSelectActivity.java +++ /dev/null @@ -1,207 +0,0 @@ -package net.micode.notes.ui; - -import android.app.Activity; -import android.app.AlertDialog; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.TextView; -import android.widget.Toast; - -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import net.micode.notes.R; -import net.micode.notes.model.NoteTemplate; -import net.micode.notes.model.TemplateManager; - -import java.util.List; - -/** - * 模板选择Activity,用于展示和选择笔记模板 - */ -public class TemplateSelectActivity extends Activity { - public static final String EXTRA_TEMPLATE_CONTENT = "template_content"; - public static final String EXTRA_CURRENT_NOTE_CONTENT = "current_note_content"; - - private RecyclerView mRecyclerView; - private TemplateAdapter mAdapter; - private List mTemplates; - private TemplateManager mTemplateManager; - private String mCurrentNoteContent; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.template_select); - - // 获取当前笔记内容 - mCurrentNoteContent = getIntent().getStringExtra(EXTRA_CURRENT_NOTE_CONTENT); - - // 初始化模板管理器 - mTemplateManager = TemplateManager.getInstance(this); - mTemplates = mTemplateManager.getAllTemplates(); - - // 初始化RecyclerView - mRecyclerView = findViewById(R.id.rv_templates); - mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); - mAdapter = new TemplateAdapter(mTemplates); - mRecyclerView.setAdapter(mAdapter); - - // 初始化按钮点击事件 - findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - finish(); - } - }); - - findViewById(R.id.btn_save_as_template).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - saveAsTemplate(); - } - }); - } - - /** - * 保存当前笔记作为自定义模板 - */ - private void saveAsTemplate() { - if (TextUtils.isEmpty(mCurrentNoteContent)) { - Toast.makeText(this, R.string.error_note_empty, Toast.LENGTH_SHORT).show(); - return; - } - - // 弹出对话框输入模板名称 - final EditText editText = new EditText(this); - editText.setHint(R.string.enter_template_name); - - new AlertDialog.Builder(this) - .setTitle(R.string.save_as_template) - .setView(editText) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - String templateName = editText.getText().toString().trim(); - if (TextUtils.isEmpty(templateName)) { - Toast.makeText(TemplateSelectActivity.this, R.string.error_template_name_empty, Toast.LENGTH_SHORT).show(); - return; - } - - // 创建并保存自定义模板 - NoteTemplate template = new NoteTemplate(); - template.setName(templateName); - template.setContent(mCurrentNoteContent); - template.setType(NoteTemplate.TYPE_CUSTOM); - - mTemplateManager.addCustomTemplate(template); - - // 更新模板列表 - mTemplates = mTemplateManager.getAllTemplates(); - mAdapter = new TemplateAdapter(mTemplates); - mRecyclerView.setAdapter(mAdapter); - - Toast.makeText(TemplateSelectActivity.this, R.string.message_template_saved, Toast.LENGTH_SHORT).show(); - } - }) - .setNegativeButton(android.R.string.cancel, null) - .show(); - } - - /** - * 模板适配器,用于在RecyclerView中展示模板列表 - */ - private class TemplateAdapter extends RecyclerView.Adapter { - private List mTemplates; - - public TemplateAdapter(List templates) { - mTemplates = templates; - } - - @Override - public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = LayoutInflater.from(parent.getContext()) - .inflate(R.layout.template_item, parent, false); - return new ViewHolder(view); - } - - @Override - public void onBindViewHolder(ViewHolder holder, int position) { - final NoteTemplate template = mTemplates.get(position); - - holder.tvTemplateName.setText(template.getName()); - - // 设置模板类型标识 - if (NoteTemplate.TYPE_SYSTEM.equals(template.getType())) { - holder.tvTemplateType.setText(R.string.template_type_system); - holder.ivDelete.setVisibility(View.GONE); - } else { - holder.tvTemplateType.setText(R.string.template_type_custom); - holder.ivDelete.setVisibility(View.VISIBLE); - } - - // 设置点击事件 - holder.itemView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - // 返回选择的模板内容 - Intent intent = new Intent(); - intent.putExtra(EXTRA_TEMPLATE_CONTENT, template.getContent()); - setResult(RESULT_OK, intent); - finish(); - } - }); - - // 设置删除按钮点击事件 - holder.ivDelete.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - new AlertDialog.Builder(TemplateSelectActivity.this) - .setTitle(R.string.alert_title_delete) - .setMessage(R.string.alert_message_delete_template) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - // 删除自定义模板 - mTemplateManager.deleteCustomTemplate(template.getId()); - - // 更新模板列表 - mTemplates.clear(); - mTemplates.addAll(mTemplateManager.getAllTemplates()); - notifyDataSetChanged(); - - Toast.makeText(TemplateSelectActivity.this, R.string.message_template_deleted, Toast.LENGTH_SHORT).show(); - } - }) - .setNegativeButton(android.R.string.cancel, null) - .show(); - } - }); - } - - @Override - public int getItemCount() { - return mTemplates.size(); - } - - public class ViewHolder extends RecyclerView.ViewHolder { - public TextView tvTemplateName; - public TextView tvTemplateType; - public ImageView ivDelete; - - public ViewHolder(View itemView) { - super(itemView); - tvTemplateName = itemView.findViewById(R.id.tv_template_name); - tvTemplateType = itemView.findViewById(R.id.tv_template_type); - ivDelete = itemView.findViewById(R.id.iv_delete); - } - } - } -} 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/java/net/micode/notes/worker/TrashCleanupWorker.java b/src/main/java/net/micode/notes/worker/TrashCleanupWorker.java deleted file mode 100644 index 5efd14f..0000000 --- a/src/main/java/net/micode/notes/worker/TrashCleanupWorker.java +++ /dev/null @@ -1,81 +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.worker; - -import android.content.Context; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; -import android.util.Log; - -import net.micode.notes.model.RecentlyDeletedManager; - -/** - * 回收站自动清理工作器,负责定期清理超过保留期限的已删除项 - * 提供静态方法doCleanup()用于手动触发清理,可在应用启动时调用 - */ -public class TrashCleanupWorker { - // 日志标签 - private static final String TAG = "TrashCleanupWorker"; - // 上次清理时间的偏好设置键 - private static final String PREF_LAST_CLEANUP_TIME = "last_trash_cleanup_time"; - // 回收站保留天数的偏好设置键 - private static final String PREF_TRASH_RETENTION_DAYS = "pref_key_trash_retention_days"; - - /** - * 执行清理任务 - * @param context 上下文对象 - */ - public static void doCleanup(Context context) { - try { - // 获取偏好设置 - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); - long lastCleanupTime = prefs.getLong(PREF_LAST_CLEANUP_TIME, 0); - long currentTime = System.currentTimeMillis(); - - // 检查是否需要清理:如果距离上次清理时间超过24小时 - if (currentTime - lastCleanupTime < RecentlyDeletedManager.CLEANUP_INTERVAL) { - Log.d(TAG, "Skip cleanup, last cleanup was within the interval"); - return; - } - - // 获取用户设置的保留天数 - int retentionDays = RecentlyDeletedManager.DEFAULT_RETENTION_DAYS; - try { - String retentionDaysStr = prefs.getString(PREF_TRASH_RETENTION_DAYS, String.valueOf(RecentlyDeletedManager.DEFAULT_RETENTION_DAYS)); - retentionDays = Integer.parseInt(retentionDaysStr); - } catch (NumberFormatException e) { - Log.e(TAG, "Invalid retention days setting, using default value", e); - retentionDays = RecentlyDeletedManager.DEFAULT_RETENTION_DAYS; - } - - // 执行清理 - RecentlyDeletedManager manager = RecentlyDeletedManager.getInstance(context); - int deletedCount = manager.cleanupOldItems(retentionDays); - - if (deletedCount > 0) { - Log.i(TAG, "Cleaned up " + deletedCount + " old items from trash"); - } else { - Log.d(TAG, "No old items to cleanup"); - } - - // 更新上次清理时间 - prefs.edit().putLong(PREF_LAST_CLEANUP_TIME, currentTime).apply(); - } catch (Exception e) { - Log.e(TAG, "Failed to perform trash cleanup", e); - } - } -} \ No newline at end of file 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 @@ - - - - - - - - - \ No newline at end of file diff --git a/src/main/res/color/secondary_text_dark.xml b/src/main/res/color/secondary_text_dark.xml deleted file mode 100644 index c1c2384..0000000 --- a/src/main/res/color/secondary_text_dark.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/src/main/res/drawable-hdpi/bg_btn_set_color.png b/src/main/res/drawable-hdpi/bg_btn_set_color.png deleted file mode 100644 index 5eb5d44..0000000 Binary files a/src/main/res/drawable-hdpi/bg_btn_set_color.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/bg_color_btn_mask.png b/src/main/res/drawable-hdpi/bg_color_btn_mask.png deleted file mode 100644 index 100db77..0000000 Binary files a/src/main/res/drawable-hdpi/bg_color_btn_mask.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/call_record.png b/src/main/res/drawable-hdpi/call_record.png deleted file mode 100644 index fb88ca4..0000000 Binary files a/src/main/res/drawable-hdpi/call_record.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/clock.png b/src/main/res/drawable-hdpi/clock.png deleted file mode 100644 index 5f2ae9a..0000000 Binary files a/src/main/res/drawable-hdpi/clock.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/delete.png b/src/main/res/drawable-hdpi/delete.png deleted file mode 100644 index 643de3e..0000000 Binary files a/src/main/res/drawable-hdpi/delete.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/dropdown_icon.9.png b/src/main/res/drawable-hdpi/dropdown_icon.9.png deleted file mode 100644 index 5525025..0000000 Binary files a/src/main/res/drawable-hdpi/dropdown_icon.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/edit_blue.9.png b/src/main/res/drawable-hdpi/edit_blue.9.png deleted file mode 100644 index 55a1856..0000000 Binary files a/src/main/res/drawable-hdpi/edit_blue.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/edit_green.9.png b/src/main/res/drawable-hdpi/edit_green.9.png deleted file mode 100644 index 2cb2d60..0000000 Binary files a/src/main/res/drawable-hdpi/edit_green.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/edit_red.9.png b/src/main/res/drawable-hdpi/edit_red.9.png deleted file mode 100644 index bae944a..0000000 Binary files a/src/main/res/drawable-hdpi/edit_red.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/edit_title_blue.9.png b/src/main/res/drawable-hdpi/edit_title_blue.9.png deleted file mode 100644 index 96e6092..0000000 Binary files a/src/main/res/drawable-hdpi/edit_title_blue.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/edit_title_green.9.png b/src/main/res/drawable-hdpi/edit_title_green.9.png deleted file mode 100644 index 08d8644..0000000 Binary files a/src/main/res/drawable-hdpi/edit_title_green.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/edit_title_red.9.png b/src/main/res/drawable-hdpi/edit_title_red.9.png deleted file mode 100644 index 9c430e5..0000000 Binary files a/src/main/res/drawable-hdpi/edit_title_red.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/edit_title_white.9.png b/src/main/res/drawable-hdpi/edit_title_white.9.png deleted file mode 100644 index 19e8d95..0000000 Binary files a/src/main/res/drawable-hdpi/edit_title_white.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/edit_title_yellow.9.png b/src/main/res/drawable-hdpi/edit_title_yellow.9.png deleted file mode 100644 index bf8f580..0000000 Binary files a/src/main/res/drawable-hdpi/edit_title_yellow.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/edit_white.9.png b/src/main/res/drawable-hdpi/edit_white.9.png deleted file mode 100644 index 918f7a6..0000000 Binary files a/src/main/res/drawable-hdpi/edit_white.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/edit_yellow.9.png b/src/main/res/drawable-hdpi/edit_yellow.9.png deleted file mode 100644 index 10cb642..0000000 Binary files a/src/main/res/drawable-hdpi/edit_yellow.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/font_large.png b/src/main/res/drawable-hdpi/font_large.png deleted file mode 100644 index 78cf2e6..0000000 Binary files a/src/main/res/drawable-hdpi/font_large.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/font_normal.png b/src/main/res/drawable-hdpi/font_normal.png deleted file mode 100644 index 9de7ced..0000000 Binary files a/src/main/res/drawable-hdpi/font_normal.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/font_size_selector_bg.9.png b/src/main/res/drawable-hdpi/font_size_selector_bg.9.png deleted file mode 100644 index be8e64c..0000000 Binary files a/src/main/res/drawable-hdpi/font_size_selector_bg.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/font_small.png b/src/main/res/drawable-hdpi/font_small.png deleted file mode 100644 index d3ff104..0000000 Binary files a/src/main/res/drawable-hdpi/font_small.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/font_super.png b/src/main/res/drawable-hdpi/font_super.png deleted file mode 100644 index 85b13a1..0000000 Binary files a/src/main/res/drawable-hdpi/font_super.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/icon_app.png b/src/main/res/drawable-hdpi/icon_app.png deleted file mode 100644 index 418aadc..0000000 Binary files a/src/main/res/drawable-hdpi/icon_app.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_background.png b/src/main/res/drawable-hdpi/list_background.png deleted file mode 100644 index 087e1f9..0000000 Binary files a/src/main/res/drawable-hdpi/list_background.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_blue_down.9.png b/src/main/res/drawable-hdpi/list_blue_down.9.png deleted file mode 100644 index b88eebf..0000000 Binary files a/src/main/res/drawable-hdpi/list_blue_down.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_blue_middle.9.png b/src/main/res/drawable-hdpi/list_blue_middle.9.png deleted file mode 100644 index 96b1c8b..0000000 Binary files a/src/main/res/drawable-hdpi/list_blue_middle.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_blue_single.9.png b/src/main/res/drawable-hdpi/list_blue_single.9.png deleted file mode 100644 index d7e7206..0000000 Binary files a/src/main/res/drawable-hdpi/list_blue_single.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_blue_up.9.png b/src/main/res/drawable-hdpi/list_blue_up.9.png deleted file mode 100644 index 632e88c..0000000 Binary files a/src/main/res/drawable-hdpi/list_blue_up.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_folder.9.png b/src/main/res/drawable-hdpi/list_folder.9.png deleted file mode 100644 index 829f61b..0000000 Binary files a/src/main/res/drawable-hdpi/list_folder.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_footer_bg.9.png b/src/main/res/drawable-hdpi/list_footer_bg.9.png deleted file mode 100644 index 5325c25..0000000 Binary files a/src/main/res/drawable-hdpi/list_footer_bg.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_green_down.9.png b/src/main/res/drawable-hdpi/list_green_down.9.png deleted file mode 100644 index 64a39d9..0000000 Binary files a/src/main/res/drawable-hdpi/list_green_down.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_green_middle.9.png b/src/main/res/drawable-hdpi/list_green_middle.9.png deleted file mode 100644 index 897325a..0000000 Binary files a/src/main/res/drawable-hdpi/list_green_middle.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_green_single.9.png b/src/main/res/drawable-hdpi/list_green_single.9.png deleted file mode 100644 index c83405f..0000000 Binary files a/src/main/res/drawable-hdpi/list_green_single.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_green_up.9.png b/src/main/res/drawable-hdpi/list_green_up.9.png deleted file mode 100644 index 141f9e1..0000000 Binary files a/src/main/res/drawable-hdpi/list_green_up.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_red_down.9.png b/src/main/res/drawable-hdpi/list_red_down.9.png deleted file mode 100644 index 4224309..0000000 Binary files a/src/main/res/drawable-hdpi/list_red_down.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_red_middle.9.png b/src/main/res/drawable-hdpi/list_red_middle.9.png deleted file mode 100644 index 9988f17..0000000 Binary files a/src/main/res/drawable-hdpi/list_red_middle.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_red_single.9.png b/src/main/res/drawable-hdpi/list_red_single.9.png deleted file mode 100644 index 587c348..0000000 Binary files a/src/main/res/drawable-hdpi/list_red_single.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_red_up.9.png b/src/main/res/drawable-hdpi/list_red_up.9.png deleted file mode 100644 index 46b4757..0000000 Binary files a/src/main/res/drawable-hdpi/list_red_up.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_white_down.9.png b/src/main/res/drawable-hdpi/list_white_down.9.png deleted file mode 100644 index 29f9d8c..0000000 Binary files a/src/main/res/drawable-hdpi/list_white_down.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_white_middle.9.png b/src/main/res/drawable-hdpi/list_white_middle.9.png deleted file mode 100644 index 77a4ab4..0000000 Binary files a/src/main/res/drawable-hdpi/list_white_middle.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_white_single.9.png b/src/main/res/drawable-hdpi/list_white_single.9.png deleted file mode 100644 index 3e79189..0000000 Binary files a/src/main/res/drawable-hdpi/list_white_single.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_white_up.9.png b/src/main/res/drawable-hdpi/list_white_up.9.png deleted file mode 100644 index e23cd5c..0000000 Binary files a/src/main/res/drawable-hdpi/list_white_up.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_yellow_down.9.png b/src/main/res/drawable-hdpi/list_yellow_down.9.png deleted file mode 100644 index 31cfc1e..0000000 Binary files a/src/main/res/drawable-hdpi/list_yellow_down.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_yellow_middle.9.png b/src/main/res/drawable-hdpi/list_yellow_middle.9.png deleted file mode 100644 index b6549b2..0000000 Binary files a/src/main/res/drawable-hdpi/list_yellow_middle.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_yellow_single.9.png b/src/main/res/drawable-hdpi/list_yellow_single.9.png deleted file mode 100644 index 3faf507..0000000 Binary files a/src/main/res/drawable-hdpi/list_yellow_single.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/list_yellow_up.9.png b/src/main/res/drawable-hdpi/list_yellow_up.9.png deleted file mode 100644 index 4ae791c..0000000 Binary files a/src/main/res/drawable-hdpi/list_yellow_up.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/menu_delete.png b/src/main/res/drawable-hdpi/menu_delete.png deleted file mode 100644 index ccdfc4b..0000000 Binary files a/src/main/res/drawable-hdpi/menu_delete.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/menu_move.png b/src/main/res/drawable-hdpi/menu_move.png deleted file mode 100644 index 1140b71..0000000 Binary files a/src/main/res/drawable-hdpi/menu_move.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/new_note_normal.png b/src/main/res/drawable-hdpi/new_note_normal.png deleted file mode 100644 index e24e0d1..0000000 Binary files a/src/main/res/drawable-hdpi/new_note_normal.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/new_note_pressed.png b/src/main/res/drawable-hdpi/new_note_pressed.png deleted file mode 100644 index c748936..0000000 Binary files a/src/main/res/drawable-hdpi/new_note_pressed.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/note_edit_color_selector_panel.png b/src/main/res/drawable-hdpi/note_edit_color_selector_panel.png deleted file mode 100644 index fc49552..0000000 Binary files a/src/main/res/drawable-hdpi/note_edit_color_selector_panel.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/notification.png b/src/main/res/drawable-hdpi/notification.png deleted file mode 100644 index b13ab4a..0000000 Binary files a/src/main/res/drawable-hdpi/notification.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/search_result.png b/src/main/res/drawable-hdpi/search_result.png deleted file mode 100644 index ff2befd..0000000 Binary files a/src/main/res/drawable-hdpi/search_result.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/selected.png b/src/main/res/drawable-hdpi/selected.png deleted file mode 100644 index b889bef..0000000 Binary files a/src/main/res/drawable-hdpi/selected.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/title_alert.png b/src/main/res/drawable-hdpi/title_alert.png deleted file mode 100644 index 544ee9c..0000000 Binary files a/src/main/res/drawable-hdpi/title_alert.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/title_bar_bg.9.png b/src/main/res/drawable-hdpi/title_bar_bg.9.png deleted file mode 100644 index eb6bff0..0000000 Binary files a/src/main/res/drawable-hdpi/title_bar_bg.9.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/widget_2x_blue.png b/src/main/res/drawable-hdpi/widget_2x_blue.png deleted file mode 100644 index a1707f4..0000000 Binary files a/src/main/res/drawable-hdpi/widget_2x_blue.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/widget_2x_green.png b/src/main/res/drawable-hdpi/widget_2x_green.png deleted file mode 100644 index f86886c..0000000 Binary files a/src/main/res/drawable-hdpi/widget_2x_green.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/widget_2x_red.png b/src/main/res/drawable-hdpi/widget_2x_red.png deleted file mode 100644 index 0e66c29..0000000 Binary files a/src/main/res/drawable-hdpi/widget_2x_red.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/widget_2x_white.png b/src/main/res/drawable-hdpi/widget_2x_white.png deleted file mode 100644 index 5f0619a..0000000 Binary files a/src/main/res/drawable-hdpi/widget_2x_white.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/widget_2x_yellow.png b/src/main/res/drawable-hdpi/widget_2x_yellow.png deleted file mode 100644 index 12d1c2b..0000000 Binary files a/src/main/res/drawable-hdpi/widget_2x_yellow.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/widget_4x_blue.png b/src/main/res/drawable-hdpi/widget_4x_blue.png deleted file mode 100644 index 9183738..0000000 Binary files a/src/main/res/drawable-hdpi/widget_4x_blue.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/widget_4x_green.png b/src/main/res/drawable-hdpi/widget_4x_green.png deleted file mode 100644 index fa8b452..0000000 Binary files a/src/main/res/drawable-hdpi/widget_4x_green.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/widget_4x_red.png b/src/main/res/drawable-hdpi/widget_4x_red.png deleted file mode 100644 index 62de074..0000000 Binary files a/src/main/res/drawable-hdpi/widget_4x_red.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/widget_4x_white.png b/src/main/res/drawable-hdpi/widget_4x_white.png deleted file mode 100644 index a37d67c..0000000 Binary files a/src/main/res/drawable-hdpi/widget_4x_white.png and /dev/null differ diff --git a/src/main/res/drawable-hdpi/widget_4x_yellow.png b/src/main/res/drawable-hdpi/widget_4x_yellow.png deleted file mode 100644 index d7c5fa4..0000000 Binary files a/src/main/res/drawable-hdpi/widget_4x_yellow.png and /dev/null differ diff --git a/src/main/res/drawable/ic_launcher_background.xml b/src/main/res/drawable/ic_launcher_background.xml deleted file mode 100644 index 07d5da9..0000000 --- a/src/main/res/drawable/ic_launcher_background.xml +++ /dev/null @@ -1,170 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/res/drawable/ic_launcher_foreground.xml b/src/main/res/drawable/ic_launcher_foreground.xml deleted file mode 100644 index 2b068d1..0000000 --- a/src/main/res/drawable/ic_launcher_foreground.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/res/drawable/new_note.xml b/src/main/res/drawable/new_note.xml deleted file mode 100644 index 2154ebc..0000000 --- a/src/main/res/drawable/new_note.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - diff --git a/src/main/res/drawable/template_item_bg.xml b/src/main/res/drawable/template_item_bg.xml deleted file mode 100644 index 15117c7..0000000 --- a/src/main/res/drawable/template_item_bg.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/src/main/res/drawable/template_type_bg.xml b/src/main/res/drawable/template_type_bg.xml deleted file mode 100644 index 94af0a3..0000000 --- a/src/main/res/drawable/template_type_bg.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - diff --git a/src/main/res/layout/account_dialog_title.xml b/src/main/res/layout/account_dialog_title.xml deleted file mode 100644 index 7717112..0000000 --- a/src/main/res/layout/account_dialog_title.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/res/layout/activity_main.xml b/src/main/res/layout/activity_main.xml deleted file mode 100644 index 86a5d97..0000000 --- a/src/main/res/layout/activity_main.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/main/res/layout/add_account_text.xml b/src/main/res/layout/add_account_text.xml deleted file mode 100644 index c799178..0000000 --- a/src/main/res/layout/add_account_text.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/src/main/res/layout/datetime_picker.xml b/src/main/res/layout/datetime_picker.xml deleted file mode 100644 index f10d592..0000000 --- a/src/main/res/layout/datetime_picker.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/res/layout/dialog_edit_text.xml b/src/main/res/layout/dialog_edit_text.xml deleted file mode 100644 index 361b39a..0000000 --- a/src/main/res/layout/dialog_edit_text.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/main/res/layout/folder_list_item.xml b/src/main/res/layout/folder_list_item.xml deleted file mode 100644 index 77e8148..0000000 --- a/src/main/res/layout/folder_list_item.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/src/main/res/layout/note_edit.xml b/src/main/res/layout/note_edit.xml deleted file mode 100644 index 3344dcc..0000000 --- a/src/main/res/layout/note_edit.xml +++ /dev/null @@ -1,574 +0,0 @@ - - - - - - - - - - - - - - - - - -