diff --git a/src/androidTest/java/net/micode/notes/ExampleInstrumentedTest.java b/src/androidTest/java/net/micode/notes/ExampleInstrumentedTest.java new file mode 100644 index 0000000..a889a75 --- /dev/null +++ b/src/androidTest/java/net/micode/notes/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +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 new file mode 100644 index 0000000..cb43220 --- /dev/null +++ b/src/main/AndroidManifest.xml @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ 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 new file mode 100644 index 0000000..8091753 --- /dev/null +++ b/src/main/java/net/micode/notes/MainActivity.java @@ -0,0 +1,24 @@ +package net.micode.notes; + +import android.os.Bundle; + +import androidx.activity.EdgeToEdge; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.graphics.Insets; +import androidx.core.view.ViewCompat; +import androidx.core.view.WindowInsetsCompat; + +public class MainActivity extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + EdgeToEdge.enable(this); + setContentView(R.layout.activity_main); + ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { + Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); + v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); + return insets; + }); + } +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/data/Contact.java b/src/main/java/net/micode/notes/data/Contact.java new file mode 100644 index 0000000..6a4f1d5 --- /dev/null +++ b/src/main/java/net/micode/notes/data/Contact.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.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 new file mode 100644 index 0000000..297b7dc --- /dev/null +++ b/src/main/java/net/micode/notes/data/Notes.java @@ -0,0 +1,401 @@ +/* + * 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 new file mode 100644 index 0000000..4edf21d --- /dev/null +++ b/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java @@ -0,0 +1,533 @@ +/* + * 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 new file mode 100644 index 0000000..ceb1020 --- /dev/null +++ b/src/main/java/net/micode/notes/data/NotesProvider.java @@ -0,0 +1,424 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.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 new file mode 100644 index 0000000..2a39a68 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/data/MetaData.java @@ -0,0 +1,157 @@ +/* + * 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 new file mode 100644 index 0000000..dea45d5 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/data/Node.java @@ -0,0 +1,223 @@ +/* + * 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 new file mode 100644 index 0000000..3d537ca --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/data/SqlData.java @@ -0,0 +1,337 @@ +/* + * 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 new file mode 100644 index 0000000..ad39ff5 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/data/SqlNote.java @@ -0,0 +1,714 @@ +/* + * 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 new file mode 100644 index 0000000..a9d2764 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/data/Task.java @@ -0,0 +1,483 @@ +/* + * 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 new file mode 100644 index 0000000..1cfab78 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/data/TaskList.java @@ -0,0 +1,486 @@ +/* + * 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 new file mode 100644 index 0000000..7d7892c --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java @@ -0,0 +1,39 @@ +/* + * 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 new file mode 100644 index 0000000..b9f564d --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java @@ -0,0 +1,39 @@ +/* + * 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 new file mode 100644 index 0000000..9e52a69 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java @@ -0,0 +1,209 @@ + +/* + * 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 new file mode 100644 index 0000000..776a6a5 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java @@ -0,0 +1,782 @@ +/* + * 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 new file mode 100644 index 0000000..09c7b79 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java @@ -0,0 +1,944 @@ +/* + * 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 new file mode 100644 index 0000000..512df71 --- /dev/null +++ b/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java @@ -0,0 +1,191 @@ +/* + * 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 new file mode 100644 index 0000000..44935dd --- /dev/null +++ b/src/main/java/net/micode/notes/model/Note.java @@ -0,0 +1,430 @@ +/* + * 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/RecentlyDeletedManager.java b/src/main/java/net/micode/notes/model/RecentlyDeletedManager.java new file mode 100644 index 0000000..c025468 --- /dev/null +++ b/src/main/java/net/micode/notes/model/RecentlyDeletedManager.java @@ -0,0 +1,230 @@ +/* + * 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/tool/BackupUtils.java b/src/main/java/net/micode/notes/tool/BackupUtils.java new file mode 100644 index 0000000..8f2e96e --- /dev/null +++ b/src/main/java/net/micode/notes/tool/BackupUtils.java @@ -0,0 +1,490 @@ +/* + * 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/GTaskStringUtils.java b/src/main/java/net/micode/notes/tool/GTaskStringUtils.java new file mode 100644 index 0000000..e9e7aab --- /dev/null +++ b/src/main/java/net/micode/notes/tool/GTaskStringUtils.java @@ -0,0 +1,166 @@ +/* + * 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 new file mode 100644 index 0000000..1c3c73a --- /dev/null +++ b/src/main/java/net/micode/notes/tool/ResourceParser.java @@ -0,0 +1,296 @@ +/* + * 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 new file mode 100644 index 0000000..fd4c758 --- /dev/null +++ b/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java @@ -0,0 +1,255 @@ +/* + * 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 new file mode 100644 index 0000000..4de50d9 --- /dev/null +++ b/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.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 new file mode 100644 index 0000000..610716c --- /dev/null +++ b/src/main/java/net/micode/notes/ui/AlarmReceiver.java @@ -0,0 +1,44 @@ +/* + * 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 new file mode 100644 index 0000000..c805b60 --- /dev/null +++ b/src/main/java/net/micode/notes/ui/DateTimePicker.java @@ -0,0 +1,646 @@ +/* + * 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 new file mode 100644 index 0000000..b9986ac --- /dev/null +++ b/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java @@ -0,0 +1,152 @@ +/* + * 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 new file mode 100644 index 0000000..4e58bbb --- /dev/null +++ b/src/main/java/net/micode/notes/ui/DropdownMenu.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.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 new file mode 100644 index 0000000..7e05bf2 --- /dev/null +++ b/src/main/java/net/micode/notes/ui/FoldersListAdapter.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +/** + * 文件夹列表适配器 + *

+ * 该类继承自CursorAdapter,用于在小米便签应用中显示文件夹列表 + *

+ */ +public class FoldersListAdapter extends CursorAdapter { + /** + * 文件夹数据查询的投影列数组 + *

+ * 定义了从数据库查询文件夹数据时需要获取的列,包括文件夹ID和名称 + *

+ */ + public static final String [] PROJECTION = { + NoteColumns.ID, + NoteColumns.SNIPPET + }; + + /** + * 查询结果中文件夹ID列的索引 + */ + public static final int ID_COLUMN = 0; + + /** + * 查询结果中文件夹名称列的索引 + */ + public static final int NAME_COLUMN = 1; + + /** + * 构造函数,创建文件夹列表适配器 + * @param context 上下文对象 + * @param c 包含文件夹数据的游标 + */ + public FoldersListAdapter(Context context, Cursor c) { + super(context, c); + // TODO Auto-generated constructor stub + } + + /** + * 创建新的列表项视图 + * @param context 上下文对象 + * @param cursor 包含文件夹数据的游标 + * @param parent 父视图组 + * @return 新创建的列表项视图 + */ + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new FolderListItem(context); + } + + /** + * 将数据绑定到列表项视图 + * @param view 列表项视图 + * @param context 上下文对象 + * @param cursor 包含文件夹数据的游标 + */ + @Override + public void bindView(View view, Context context, Cursor cursor) { + if (view instanceof FolderListItem) { + String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context + .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + ((FolderListItem) view).bind(folderName); + } + } + + /** + * 获取指定位置的文件夹名称 + * @param context 上下文对象 + * @param position 列表项位置 + * @return 文件夹名称 + */ + public String getFolderName(Context context, int position) { + Cursor cursor = (Cursor) getItem(position); + return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context + .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + } + + /** + * 文件夹列表项视图 + *

+ * 该内部类用于显示单个文件夹列表项 + *

+ */ + private class FolderListItem extends LinearLayout { + /** + * 文件夹名称文本视图 + */ + private TextView mName; + + /** + * 构造函数,创建文件夹列表项视图 + * @param context 上下文对象 + */ + public FolderListItem(Context context) { + super(context); + inflate(context, R.layout.folder_list_item, this); + mName = (TextView) findViewById(R.id.tv_folder_name); + } + + /** + * 绑定文件夹名称到视图 + * @param name 文件夹名称 + */ + public void bind(String name) { + mName.setText(name); + } + } + +} diff --git a/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java b/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java new file mode 100644 index 0000000..8fffe80 --- /dev/null +++ b/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java @@ -0,0 +1,224 @@ +/* + * 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 new file mode 100644 index 0000000..02bd7f1 --- /dev/null +++ b/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java @@ -0,0 +1,85 @@ +/* + * 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 new file mode 100644 index 0000000..6e4a984 --- /dev/null +++ b/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java @@ -0,0 +1,85 @@ +/* + * 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 new file mode 100644 index 0000000..5efd14f --- /dev/null +++ b/src/main/java/net/micode/notes/worker/TrashCleanupWorker.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.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 new file mode 100644 index 0000000..7c85459 --- /dev/null +++ b/src/main/res/color/primary_text_dark.xml @@ -0,0 +1,22 @@ + + + + + + + + + \ 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 new file mode 100644 index 0000000..c1c2384 --- /dev/null +++ b/src/main/res/color/secondary_text_dark.xml @@ -0,0 +1,20 @@ + + + + + + + \ 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 new file mode 100644 index 0000000..5eb5d44 Binary files /dev/null and b/src/main/res/drawable-hdpi/bg_btn_set_color.png 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 new file mode 100644 index 0000000..100db77 Binary files /dev/null and b/src/main/res/drawable-hdpi/bg_color_btn_mask.png differ diff --git a/src/main/res/drawable-hdpi/call_record.png b/src/main/res/drawable-hdpi/call_record.png new file mode 100644 index 0000000..fb88ca4 Binary files /dev/null and b/src/main/res/drawable-hdpi/call_record.png differ diff --git a/src/main/res/drawable-hdpi/clock.png b/src/main/res/drawable-hdpi/clock.png new file mode 100644 index 0000000..5f2ae9a Binary files /dev/null and b/src/main/res/drawable-hdpi/clock.png differ diff --git a/src/main/res/drawable-hdpi/delete.png b/src/main/res/drawable-hdpi/delete.png new file mode 100644 index 0000000..643de3e Binary files /dev/null and b/src/main/res/drawable-hdpi/delete.png differ diff --git a/src/main/res/drawable-hdpi/dropdown_icon.9.png b/src/main/res/drawable-hdpi/dropdown_icon.9.png new file mode 100644 index 0000000..5525025 Binary files /dev/null and b/src/main/res/drawable-hdpi/dropdown_icon.9.png differ diff --git a/src/main/res/drawable-hdpi/edit_blue.9.png b/src/main/res/drawable-hdpi/edit_blue.9.png new file mode 100644 index 0000000..55a1856 Binary files /dev/null and b/src/main/res/drawable-hdpi/edit_blue.9.png differ diff --git a/src/main/res/drawable-hdpi/edit_green.9.png b/src/main/res/drawable-hdpi/edit_green.9.png new file mode 100644 index 0000000..2cb2d60 Binary files /dev/null and b/src/main/res/drawable-hdpi/edit_green.9.png differ diff --git a/src/main/res/drawable-hdpi/edit_red.9.png b/src/main/res/drawable-hdpi/edit_red.9.png new file mode 100644 index 0000000..bae944a Binary files /dev/null and b/src/main/res/drawable-hdpi/edit_red.9.png 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 new file mode 100644 index 0000000..96e6092 Binary files /dev/null and b/src/main/res/drawable-hdpi/edit_title_blue.9.png 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 new file mode 100644 index 0000000..08d8644 Binary files /dev/null and b/src/main/res/drawable-hdpi/edit_title_green.9.png 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 new file mode 100644 index 0000000..9c430e5 Binary files /dev/null and b/src/main/res/drawable-hdpi/edit_title_red.9.png 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 new file mode 100644 index 0000000..19e8d95 Binary files /dev/null and b/src/main/res/drawable-hdpi/edit_title_white.9.png 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 new file mode 100644 index 0000000..bf8f580 Binary files /dev/null and b/src/main/res/drawable-hdpi/edit_title_yellow.9.png differ diff --git a/src/main/res/drawable-hdpi/edit_white.9.png b/src/main/res/drawable-hdpi/edit_white.9.png new file mode 100644 index 0000000..918f7a6 Binary files /dev/null and b/src/main/res/drawable-hdpi/edit_white.9.png differ diff --git a/src/main/res/drawable-hdpi/edit_yellow.9.png b/src/main/res/drawable-hdpi/edit_yellow.9.png new file mode 100644 index 0000000..10cb642 Binary files /dev/null and b/src/main/res/drawable-hdpi/edit_yellow.9.png differ diff --git a/src/main/res/drawable-hdpi/font_large.png b/src/main/res/drawable-hdpi/font_large.png new file mode 100644 index 0000000..78cf2e6 Binary files /dev/null and b/src/main/res/drawable-hdpi/font_large.png differ diff --git a/src/main/res/drawable-hdpi/font_normal.png b/src/main/res/drawable-hdpi/font_normal.png new file mode 100644 index 0000000..9de7ced Binary files /dev/null and b/src/main/res/drawable-hdpi/font_normal.png 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 new file mode 100644 index 0000000..be8e64c Binary files /dev/null and b/src/main/res/drawable-hdpi/font_size_selector_bg.9.png differ diff --git a/src/main/res/drawable-hdpi/font_small.png b/src/main/res/drawable-hdpi/font_small.png new file mode 100644 index 0000000..d3ff104 Binary files /dev/null and b/src/main/res/drawable-hdpi/font_small.png differ diff --git a/src/main/res/drawable-hdpi/font_super.png b/src/main/res/drawable-hdpi/font_super.png new file mode 100644 index 0000000..85b13a1 Binary files /dev/null and b/src/main/res/drawable-hdpi/font_super.png differ diff --git a/src/main/res/drawable-hdpi/icon_app.png b/src/main/res/drawable-hdpi/icon_app.png new file mode 100644 index 0000000..418aadc Binary files /dev/null and b/src/main/res/drawable-hdpi/icon_app.png differ diff --git a/src/main/res/drawable-hdpi/list_background.png b/src/main/res/drawable-hdpi/list_background.png new file mode 100644 index 0000000..087e1f9 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_background.png 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 new file mode 100644 index 0000000..b88eebf Binary files /dev/null and b/src/main/res/drawable-hdpi/list_blue_down.9.png 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 new file mode 100644 index 0000000..96b1c8b Binary files /dev/null and b/src/main/res/drawable-hdpi/list_blue_middle.9.png 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 new file mode 100644 index 0000000..d7e7206 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_blue_single.9.png 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 new file mode 100644 index 0000000..632e88c Binary files /dev/null and b/src/main/res/drawable-hdpi/list_blue_up.9.png differ diff --git a/src/main/res/drawable-hdpi/list_folder.9.png b/src/main/res/drawable-hdpi/list_folder.9.png new file mode 100644 index 0000000..829f61b Binary files /dev/null and b/src/main/res/drawable-hdpi/list_folder.9.png 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 new file mode 100644 index 0000000..5325c25 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_footer_bg.9.png 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 new file mode 100644 index 0000000..64a39d9 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_green_down.9.png 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 new file mode 100644 index 0000000..897325a Binary files /dev/null and b/src/main/res/drawable-hdpi/list_green_middle.9.png 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 new file mode 100644 index 0000000..c83405f Binary files /dev/null and b/src/main/res/drawable-hdpi/list_green_single.9.png 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 new file mode 100644 index 0000000..141f9e1 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_green_up.9.png 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 new file mode 100644 index 0000000..4224309 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_red_down.9.png 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 new file mode 100644 index 0000000..9988f17 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_red_middle.9.png 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 new file mode 100644 index 0000000..587c348 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_red_single.9.png 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 new file mode 100644 index 0000000..46b4757 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_red_up.9.png 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 new file mode 100644 index 0000000..29f9d8c Binary files /dev/null and b/src/main/res/drawable-hdpi/list_white_down.9.png 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 new file mode 100644 index 0000000..77a4ab4 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_white_middle.9.png 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 new file mode 100644 index 0000000..3e79189 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_white_single.9.png 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 new file mode 100644 index 0000000..e23cd5c Binary files /dev/null and b/src/main/res/drawable-hdpi/list_white_up.9.png 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 new file mode 100644 index 0000000..31cfc1e Binary files /dev/null and b/src/main/res/drawable-hdpi/list_yellow_down.9.png 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 new file mode 100644 index 0000000..b6549b2 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_yellow_middle.9.png 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 new file mode 100644 index 0000000..3faf507 Binary files /dev/null and b/src/main/res/drawable-hdpi/list_yellow_single.9.png 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 new file mode 100644 index 0000000..4ae791c Binary files /dev/null and b/src/main/res/drawable-hdpi/list_yellow_up.9.png differ diff --git a/src/main/res/drawable-hdpi/menu_delete.png b/src/main/res/drawable-hdpi/menu_delete.png new file mode 100644 index 0000000..ccdfc4b Binary files /dev/null and b/src/main/res/drawable-hdpi/menu_delete.png differ diff --git a/src/main/res/drawable-hdpi/menu_move.png b/src/main/res/drawable-hdpi/menu_move.png new file mode 100644 index 0000000..1140b71 Binary files /dev/null and b/src/main/res/drawable-hdpi/menu_move.png differ diff --git a/src/main/res/drawable-hdpi/new_note_normal.png b/src/main/res/drawable-hdpi/new_note_normal.png new file mode 100644 index 0000000..e24e0d1 Binary files /dev/null and b/src/main/res/drawable-hdpi/new_note_normal.png differ diff --git a/src/main/res/drawable-hdpi/new_note_pressed.png b/src/main/res/drawable-hdpi/new_note_pressed.png new file mode 100644 index 0000000..c748936 Binary files /dev/null and b/src/main/res/drawable-hdpi/new_note_pressed.png 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 new file mode 100644 index 0000000..fc49552 Binary files /dev/null and b/src/main/res/drawable-hdpi/note_edit_color_selector_panel.png differ diff --git a/src/main/res/drawable-hdpi/notification.png b/src/main/res/drawable-hdpi/notification.png new file mode 100644 index 0000000..b13ab4a Binary files /dev/null and b/src/main/res/drawable-hdpi/notification.png differ diff --git a/src/main/res/drawable-hdpi/search_result.png b/src/main/res/drawable-hdpi/search_result.png new file mode 100644 index 0000000..ff2befd Binary files /dev/null and b/src/main/res/drawable-hdpi/search_result.png differ diff --git a/src/main/res/drawable-hdpi/selected.png b/src/main/res/drawable-hdpi/selected.png new file mode 100644 index 0000000..b889bef Binary files /dev/null and b/src/main/res/drawable-hdpi/selected.png differ diff --git a/src/main/res/drawable-hdpi/title_alert.png b/src/main/res/drawable-hdpi/title_alert.png new file mode 100644 index 0000000..544ee9c Binary files /dev/null and b/src/main/res/drawable-hdpi/title_alert.png 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 new file mode 100644 index 0000000..eb6bff0 Binary files /dev/null and b/src/main/res/drawable-hdpi/title_bar_bg.9.png differ diff --git a/src/main/res/drawable-hdpi/widget_2x_blue.png b/src/main/res/drawable-hdpi/widget_2x_blue.png new file mode 100644 index 0000000..a1707f4 Binary files /dev/null and b/src/main/res/drawable-hdpi/widget_2x_blue.png differ diff --git a/src/main/res/drawable-hdpi/widget_2x_green.png b/src/main/res/drawable-hdpi/widget_2x_green.png new file mode 100644 index 0000000..f86886c Binary files /dev/null and b/src/main/res/drawable-hdpi/widget_2x_green.png differ diff --git a/src/main/res/drawable-hdpi/widget_2x_red.png b/src/main/res/drawable-hdpi/widget_2x_red.png new file mode 100644 index 0000000..0e66c29 Binary files /dev/null and b/src/main/res/drawable-hdpi/widget_2x_red.png differ diff --git a/src/main/res/drawable-hdpi/widget_2x_white.png b/src/main/res/drawable-hdpi/widget_2x_white.png new file mode 100644 index 0000000..5f0619a Binary files /dev/null and b/src/main/res/drawable-hdpi/widget_2x_white.png differ diff --git a/src/main/res/drawable-hdpi/widget_2x_yellow.png b/src/main/res/drawable-hdpi/widget_2x_yellow.png new file mode 100644 index 0000000..12d1c2b Binary files /dev/null and b/src/main/res/drawable-hdpi/widget_2x_yellow.png differ diff --git a/src/main/res/drawable-hdpi/widget_4x_blue.png b/src/main/res/drawable-hdpi/widget_4x_blue.png new file mode 100644 index 0000000..9183738 Binary files /dev/null and b/src/main/res/drawable-hdpi/widget_4x_blue.png differ diff --git a/src/main/res/drawable-hdpi/widget_4x_green.png b/src/main/res/drawable-hdpi/widget_4x_green.png new file mode 100644 index 0000000..fa8b452 Binary files /dev/null and b/src/main/res/drawable-hdpi/widget_4x_green.png differ diff --git a/src/main/res/drawable-hdpi/widget_4x_red.png b/src/main/res/drawable-hdpi/widget_4x_red.png new file mode 100644 index 0000000..62de074 Binary files /dev/null and b/src/main/res/drawable-hdpi/widget_4x_red.png differ diff --git a/src/main/res/drawable-hdpi/widget_4x_white.png b/src/main/res/drawable-hdpi/widget_4x_white.png new file mode 100644 index 0000000..a37d67c Binary files /dev/null and b/src/main/res/drawable-hdpi/widget_4x_white.png differ diff --git a/src/main/res/drawable-hdpi/widget_4x_yellow.png b/src/main/res/drawable-hdpi/widget_4x_yellow.png new file mode 100644 index 0000000..d7c5fa4 Binary files /dev/null and b/src/main/res/drawable-hdpi/widget_4x_yellow.png differ diff --git a/src/main/res/drawable/ic_launcher_background.xml b/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/drawable/ic_launcher_foreground.xml b/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/new_note.xml b/src/main/res/drawable/new_note.xml new file mode 100644 index 0000000..2154ebc --- /dev/null +++ b/src/main/res/drawable/new_note.xml @@ -0,0 +1,23 @@ + + + + + + + + diff --git a/src/main/res/layout/account_dialog_title.xml b/src/main/res/layout/account_dialog_title.xml new file mode 100644 index 0000000..7717112 --- /dev/null +++ b/src/main/res/layout/account_dialog_title.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/layout/activity_main.xml b/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..86a5d97 --- /dev/null +++ b/src/main/res/layout/activity_main.xml @@ -0,0 +1,19 @@ + + + + + + \ 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 new file mode 100644 index 0000000..c799178 --- /dev/null +++ b/src/main/res/layout/add_account_text.xml @@ -0,0 +1,32 @@ + + + + + + + + \ No newline at end of file diff --git a/src/main/res/layout/datetime_picker.xml b/src/main/res/layout/datetime_picker.xml new file mode 100644 index 0000000..f10d592 --- /dev/null +++ b/src/main/res/layout/datetime_picker.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + \ 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 new file mode 100644 index 0000000..361b39a --- /dev/null +++ b/src/main/res/layout/dialog_edit_text.xml @@ -0,0 +1,23 @@ + + + + + \ 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 new file mode 100644 index 0000000..77e8148 --- /dev/null +++ b/src/main/res/layout/folder_list_item.xml @@ -0,0 +1,29 @@ + + + + + + + + \ No newline at end of file diff --git a/src/main/res/layout/note_edit_list_item.xml b/src/main/res/layout/note_edit_list_item.xml new file mode 100644 index 0000000..a885f9c --- /dev/null +++ b/src/main/res/layout/note_edit_list_item.xml @@ -0,0 +1,39 @@ + + + + + + + + + + diff --git a/src/main/res/layout/note_item.xml b/src/main/res/layout/note_item.xml new file mode 100644 index 0000000..d541f6a --- /dev/null +++ b/src/main/res/layout/note_item.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/note_list.xml b/src/main/res/layout/note_list.xml new file mode 100644 index 0000000..6ceb130 --- /dev/null +++ b/src/main/res/layout/note_list.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + +