diff --git a/README.md b/README.md deleted file mode 100644 index a6ed909..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# note - diff --git a/src/BackupUtils.java b/src/BackupUtils.java new file mode 100644 index 0000000..7c89f71 --- /dev/null +++ b/src/BackupUtils.java @@ -0,0 +1,297 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.tool; + +import android.content.Context; +import android.database.Cursor; +import android.os.Environment; +import android.text.TextUtils; +import android.text.format.DateFormat; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +public class BackupUtils { + private static final String TAG = "BackupUtils"; + // 单例模式,确保只有一个BackupUtils实例 + private static BackupUtils sInstance; + + // 获取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; + + // 构造函数,初始化TextExport类 + private BackupUtils(Context context) { + mTextExport = new TextExport(context); + } + + // 检查外部存储(SD卡)是否可用 + private static boolean externalStorageAvailable() { + return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); + } + + // 导出笔记为文本格式 + public int exportToText() { + return mTextExport.exportToText(); + } + + // 获取导出的文本文件名 + public String getExportedTextFileName() { + return mTextExport.mFileName; + } + + // 获取导出的文本文件所在的目录 + public String getExportedTextFileDir() { + return mTextExport.mFileDirectory; + } + + // 内部类,用于处理笔记的文本导出 + private static class TextExport { + private static final String[] NOTE_PROJECTION = { + NoteColumns.ID, + 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; + + // 构造函数,初始化格式化字符串和上下文 + public TextExport(Context context) { + TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); + mContext = context; + mFileName = ""; + mFileDirectory = ""; + } + + // 根据格式ID获取相应的格式化字符串 + private String getFormat(int id) { + return TEXT_FORMAT[id]; + } + + /** + * 将指定文件夹内的笔记导出为文本格式 + * @param folderId 文件夹的ID + * @param ps 输出流,用于写入导出的数据 + */ + private void exportFolderToText(String folderId, PrintStream ps) { + // 查询属于该文件夹的笔记 + 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 { + // 打印笔记的最后修改日期 + ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), + notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); + // 查询与该笔记相关的数据 + 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)) { + // 导出电话记录相关信息 + 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)); + } + // 打印电话日期 + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat + .format(mContext.getString(R.string.format_datetime_mdhm), + callDate))); + // 打印电话记录的地点 + 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(); + } + // 在每个笔记之间打印一个分隔符 + try { + ps.write(new byte[] { + Character.LINE_SEPARATOR, Character.LETTER_NUMBER + }); + } catch (IOException e) { + Log.e(TAG, e.toString()); + } + } + + /** + * 将笔记导出为用户可读的文本格式 + */ + public int exportToText() { + if (!externalStorageAvailable()) { + Log.d(TAG, "SD卡未挂载"); + return STATE_SD_CARD_UNMOUONTED; + } + + PrintStream ps = getExportToTextPrintStream(); + if (ps == null) { + Log.e(TAG, "获取输出流失败"); + return STATE_SYSTEM_ERROR; + } + + // 首先导出文件夹及其笔记 + 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 { + // 打印文件夹的名称 + 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)); + exportFolderToText(folderCursor.getString(NOTE_COLUMN_ID), ps); + } + } while (folderCursor.moveToNext()); + } + folderCursor.close(); + } + + ps.close(); + return STATE_SUCCESS; + } + + // 获取导出文本的输出流 + private PrintStream getExportToTextPrintStream() { + // 获取文件路径 + String path = Environment.getExternalStorageDirectory() + "/notesBackup"; + File dir = new File(path); + if (!dir.exists()) { + if (!dir.mkdirs()) { + return null; + } + } + + // 设置输出文件路径 + mFileName = "NotesBackup_" + System.currentTimeMillis() + ".txt"; + mFileDirectory = path; + File file = new File(path, mFileName); + + try { + FileOutputStream fos = new FileOutputStream(file); + return new PrintStream(fos); + } catch (FileNotFoundException e) { + Log.e(TAG, e.toString()); + return null; + } + } + } +} diff --git a/src/DataUtils.java b/src/DataUtils.java new file mode 100644 index 0000000..72b923e --- /dev/null +++ b/src/DataUtils.java @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.tool; + +import android.content.ContentProviderOperation; +import android.content.ContentProviderResult; +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.OperationApplicationException; +import android.database.Cursor; +import android.os.RemoteException; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; + +import java.util.ArrayList; +import java.util.HashSet; + +public class DataUtils { + public static final String TAG = "DataUtils"; + + // 批量删除笔记 + public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + } + if (ids.size() == 0) { + Log.d(TAG, "no id is in the hashset"); + return true; + } + + ArrayList operationList = new ArrayList(); + for (long id : ids) { + // 如果是根文件夹,则不允许删除 + if(id == Notes.ID_ROOT_FOLDER) { + Log.e(TAG, "Don't delete system folder root"); + continue; + } + // 构建删除操作 + ContentProviderOperation.Builder builder = ContentProviderOperation + .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + operationList.add(builder.build()); + } + try { + // 执行批量操作 + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + return false; + } + return true; + } catch (RemoteException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } catch (OperationApplicationException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } + return false; + } + + // 将笔记从一个文件夹移动到另一个文件夹 + public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.PARENT_ID, desFolderId); // 设置目标文件夹ID + values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 设置原文件夹ID + values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为已修改 + resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); + } + + // 批量将笔记移动到指定的文件夹 + public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, long folderId) { + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + } + + ArrayList operationList = new ArrayList(); + for (long id : ids) { + // 构建更新操作 + ContentProviderOperation.Builder builder = ContentProviderOperation + .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + builder.withValue(NoteColumns.PARENT_ID, folderId); // 设置目标文件夹ID + builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); // 标记为已修改 + operationList.add(builder.build()); + } + + try { + // 执行批量操作 + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "move notes failed, ids:" + ids.toString()); + return false; + } + return true; + } catch (RemoteException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } catch (OperationApplicationException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } + return false; + } + + /** + * 获取所有非系统文件夹的数量 + */ + public static int getUserFolderCount(ContentResolver resolver) { + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, + new String[] { "COUNT(*)" }, + NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", + new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, + null); + + int count = 0; + if (cursor != null) { + if (cursor.moveToFirst()) { + try { + count = cursor.getInt(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "get folder count failed:" + e.toString()); + } finally { + cursor.close(); + } + } + } + return count; + } + + // 检查指定笔记是否存在并且可见(非回收站) + public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + null, + NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, + new String [] {String.valueOf(type)}, + null); + + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + } + cursor.close(); + } + return exist; + } + + // 检查笔记是否存在 + public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + null, null, null, null); + + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + } + cursor.close(); + } + return exist; + } + + // 检查数据是否存在 + public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), + null, null, null, null); + + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + } + cursor.close(); + } + return exist; + } + + // 检查文件夹名称是否已存在 + public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.SNIPPET + "=?", + new String[] { name }, null); + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + } + cursor.close(); + } + return exist; + } + + // 获取指定文件夹中的小部件(AppWidget)属性 + public static HashSet getFolderNoteWidget(ContentResolver resolver, long folderId) { + Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, + new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, + NoteColumns.PARENT_ID + "=?", + new String[] { String.valueOf(folderId) }, + null); + + HashSet set = null; + if (c != null) { + if (c.moveToFirst()) { + set = new HashSet(); + do { + try { + AppWidgetAttribute widget = new AppWidgetAttribute(); + widget.widgetId = c.getInt(0); + widget.widgetType = c.getInt(1); + set.add(widget); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, e.toString()); + } + } while (c.moveToNext()); + } + c.close(); + } + return set; + } + + // 根据笔记ID获取通话记录的电话号码 + public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + new String [] { CallNote.PHONE_NUMBER }, + CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", + new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, + null); + + if (cursor != null && cursor.moveToFirst()) { + try { + return cursor.getString(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "Get call number fails " + e.toString()); + } finally { + cursor.close(); + } + } + return ""; + } + + // 根据电话号和通话日期获取对应的笔记ID + public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + new String [] { CallNote.NOTE_ID }, + CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" + + CallNote.PHONE_NUMBER + ",?)", + new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, + null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + try { + return cursor.getLong(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "Get call note id fails " + e.toString()); + } + } + cursor.close(); + } + return 0; + } + + // 根据笔记ID获取摘要 + public static String getSnippetById(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, + new String [] { NoteColumns.SNIPPET }, + NoteColumns.ID + "=?", + new String [] { String.valueOf(noteId)}, + null); + + if (cursor != null) { + String snippet = ""; + if (cursor.moveToFirst()) { + snippet = cursor.getString(0); + } + cursor.close(); + return snippet; + } + throw new IllegalArgumentException("Note is not found with id: " + noteId); + } + + // 格式化笔记摘要,去除多余的空格和换行 + public static String getFormattedSnippet(String snippet) { + if (snippet != null) { + snippet = snippet.trim(); + int index = snippet.indexOf('\n'); + if (index != -1) { + snippet = snippet.substring(0, index); + } + } + return snippet; + } +} diff --git a/src/GTaskStringUtils.java b/src/GTaskStringUtils.java new file mode 100644 index 0000000..02a2496 --- /dev/null +++ b/src/GTaskStringUtils.java @@ -0,0 +1,76 @@ +/* + * 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; + +public class GTaskStringUtils { + + // GTASK JSON 数据字段常量 + public final static String GTASK_JSON_ACTION_ID = "action_id"; // 操作ID + public final static String GTASK_JSON_ACTION_LIST = "action_list"; // 操作列表 + public final static String GTASK_JSON_ACTION_TYPE = "action_type"; // 操作类型 + public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; // 创建操作 + public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; // 获取所有操作 + public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; // 移动操作 + public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; // 更新操作 + public final static String GTASK_JSON_CREATOR_ID = "creator_id"; // 创建者ID + public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; // 子实体 + public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; // 客户端版本 + public final static String GTASK_JSON_COMPLETED = "completed"; // 是否完成 + public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; // 当前列表ID + public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; // 默认列表ID + public final static String GTASK_JSON_DELETED = "deleted"; // 是否删除 + public final static String GTASK_JSON_DEST_LIST = "dest_list"; // 目标列表 + public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; // 目标父级 + public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; // 目标父级类型 + public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; // 实体差异 + public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; // 实体类型 + public final static String GTASK_JSON_GET_DELETED = "get_deleted"; // 获取已删除的 + public final static String GTASK_JSON_ID = "id"; // ID + public final static String GTASK_JSON_INDEX = "index"; // 索引 + public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; // 最后修改时间 + public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; // 最新同步点 + public final static String GTASK_JSON_LIST_ID = "list_id"; // 列表ID + public final static String GTASK_JSON_LISTS = "lists"; // 列表 + public final static String GTASK_JSON_NAME = "name"; // 名称 + public final static String GTASK_JSON_NEW_ID = "new_id"; // 新ID + public final static String GTASK_JSON_NOTES = "notes"; // 笔记 + public final static String GTASK_JSON_PARENT_ID = "parent_id"; // 父级ID + public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; // 上一个兄弟ID + public final static String GTASK_JSON_RESULTS = "results"; // 结果 + public final static String GTASK_JSON_SOURCE_LIST = "source_list"; // 源列表 + public final static String GTASK_JSON_TASKS = "tasks"; // 任务 + public final static String GTASK_JSON_TYPE = "type"; // 类型 + public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; // 任务组类型 + public final static String GTASK_JSON_TYPE_TASK = "TASK"; // 任务类型 + public final static String GTASK_JSON_USER = "user"; // 用户 + + // MIUI 笔记相关文件夹前缀 + public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; // MIUI笔记文件夹前缀 + + // 默认文件夹名称 + public final static String FOLDER_DEFAULT = "Default"; // 默认文件夹 + public final static String FOLDER_CALL_NOTE = "Call_Note"; // 通话笔记文件夹 + public final static String FOLDER_META = "METADATA"; // 元数据文件夹 + + // 元数据头部字段 + public final static String META_HEAD_GTASK_ID = "meta_gid"; // GTASK ID + public final static String META_HEAD_NOTE = "meta_note"; // 笔记元数据 + public final static String META_HEAD_DATA = "meta_data"; // 数据元数据 + + // 元数据笔记名称,表示不允许更新和删除 + public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; // 元数据笔记名称 +} diff --git a/src/Note.java b/src/Note.java new file mode 100644 index 0000000..6f5e8ba --- /dev/null +++ b/src/Note.java @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.model; + +import android.content.ContentProviderOperation; +import android.content.ContentProviderResult; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.content.OperationApplicationException; +import android.net.Uri; +import android.os.RemoteException; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.Notes.TextNote; + +import java.util.ArrayList; + + +public class Note { + private ContentValues mNoteDiffValues; // 用于存储笔记修改的数据 + private NoteData mNoteData; // 用于存储笔记的具体内容(如文本或通话数据) + private static final String TAG = "Note"; // 用于日志输出的标签 + + /** + * 创建一个新的笔记ID,用于在数据库中添加新的笔记 + */ + public static synchronized long getNewNoteId(Context context, long folderId) { + // 创建新的笔记记录 + 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); // 设置笔记所在的文件夹ID + + // 插入新笔记到数据库,并获取URI + Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); + + long noteId = 0; + try { + noteId = Long.valueOf(uri.getPathSegments().get(1)); // 获取新笔记的ID + } catch (NumberFormatException e) { + Log.e(TAG, "Get note id error :" + e.toString()); + noteId = 0; + } + + // 如果ID获取失败,抛出异常 + if (noteId == -1) { + throw new IllegalStateException("Wrong note id:" + noteId); + } + return noteId; // 返回新创建的笔记ID + } + + public Note() { + mNoteDiffValues = new ContentValues(); // 初始化笔记修改数据 + mNoteData = new NoteData(); // 初始化笔记具体内容 + } + + // 设置笔记的某个键值对 + public void setNoteValue(String key, String value) { + mNoteDiffValues.put(key, value); // 将键值对放入修改数据中 + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记本地已修改 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新修改时间 + } + + // 设置文本数据 + public void setTextData(String key, String value) { + mNoteData.setTextData(key, value); // 将文本数据传递给NoteData对象 + } + + // 设置文本数据ID + public void setTextDataId(long id) { + mNoteData.setTextDataId(id); // 设置文本数据的ID + } + + // 获取文本数据ID + public long getTextDataId() { + return mNoteData.mTextDataId; // 返回文本数据的ID + } + + // 设置通话数据ID + public void setCallDataId(long id) { + mNoteData.setCallDataId(id); // 设置通话数据的ID + } + + // 设置通话数据 + public void setCallData(String key, String value) { + mNoteData.setCallData(key, value); // 将通话数据传递给NoteData对象 + } + + // 判断笔记是否本地已修改 + public boolean isLocalModified() { + return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); // 如果修改数据不为空或者NoteData已修改,则返回true + } + + // 同步笔记数据到ContentProvider + public boolean syncNote(Context context, long noteId) { + if (noteId <= 0) { + throw new IllegalArgumentException("Wrong note id:" + noteId); // 检查笔记ID是否合法 + } + + if (!isLocalModified()) { + return true; // 如果没有修改,直接返回 + } + + // 更新笔记的修改数据 + if (context.getContentResolver().update( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, + null) == 0) { + Log.e(TAG, "Update note error, should not happen"); + } + mNoteDiffValues.clear(); // 清空修改数据 + + // 如果有本地修改的内容,推送到ContentResolver + if (mNoteData.isLocalModified() + && (mNoteData.pushIntoContentResolver(context, noteId) == null)) { + return false; // 如果推送失败,返回false + } + + return true; // 同步成功,返回true + } + + // 内部类:表示笔记的具体内容(文本数据、通话数据) + private class NoteData { + private long mTextDataId; // 文本数据的ID + private ContentValues mTextDataValues; // 文本数据的内容 + private long mCallDataId; // 通话数据的ID + private ContentValues mCallDataValues; // 通话数据的内容 + + private static final String TAG = "NoteData"; // 用于日志输出的标签 + + public NoteData() { + mTextDataValues = new ContentValues(); // 初始化文本数据 + mCallDataValues = new ContentValues(); // 初始化通话数据 + mTextDataId = 0; + mCallDataId = 0; + } + + // 判断笔记内容是否本地已修改 + boolean isLocalModified() { + return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; // 如果文本或通话数据有修改,返回true + } + + // 设置文本数据的ID + void setTextDataId(long id) { + if(id <= 0) { + throw new IllegalArgumentException("Text data id should larger than 0"); // 检查ID是否合法 + } + mTextDataId = id; // 设置文本数据ID + } + + // 设置通话数据的ID + void setCallDataId(long id) { + if (id <= 0) { + throw new IllegalArgumentException("Call data id should larger than 0"); // 检查ID是否合法 + } + mCallDataId = id; // 设置通话数据ID + } + + // 设置通话数据 + void setCallData(String key, String value) { + mCallDataValues.put(key, value); // 将通话数据放入ContentValues + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记本地已修改 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新修改时间 + } + + // 设置文本数据 + void setTextData(String key, String value) { + mTextDataValues.put(key, value); // 将文本数据放入ContentValues + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记本地已修改 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新修改时间 + } + + // 推送内容到ContentResolver + Uri pushIntoContentResolver(Context context, long noteId) { + if (noteId <= 0) { + throw new IllegalArgumentException("Wrong note id:" + noteId); // 检查笔记ID是否合法 + } + + ArrayList operationList = new ArrayList(); // 存储所有操作 + ContentProviderOperation.Builder builder = null; + + // 插入或更新文本数据 + if(mTextDataValues.size() > 0) { + mTextDataValues.put(DataColumns.NOTE_ID, noteId); // 设置笔记ID + if (mTextDataId == 0) { + mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); // 设置MIME类型 + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, mTextDataValues); // 插入数据 + try { + setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); // 获取文本数据ID + } 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); // 设置笔记ID + if (mCallDataId == 0) { + mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); // 设置MIME类型 + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, mCallDataValues); // 插入数据 + try { + setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); // 获取通话数据ID + } 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); // 返回URI + } 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/ResourceParser.java b/src/ResourceParser.java new file mode 100644 index 0000000..b07e0fa --- /dev/null +++ b/src/ResourceParser.java @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.tool; + +import android.content.Context; +import android.preference.PreferenceManager; + +import net.micode.notes.R; +import net.micode.notes.ui.NotesPreferenceActivity; + +public class ResourceParser { + + // 背景颜色的常量定义 + public static final int YELLOW = 0; // 黄色 + public static final int BLUE = 1; // 蓝色 + public static final int WHITE = 2; // 白色 + public static final int GREEN = 3; // 绿色 + public static final int RED = 4; // 红色 + + // 默认背景颜色为黄色 + public static final int BG_DEFAULT_COLOR = YELLOW; + + // 文字大小的常量定义 + public static final int TEXT_SMALL = 0; // 小号文字 + public static final int TEXT_MEDIUM = 1; // 中号文字 + public static final int TEXT_LARGE = 2; // 大号文字 + public static final int TEXT_SUPER = 3; // 超大号文字 + + // 默认字体大小为中号 + public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; + + // 笔记背景资源类 + public static class NoteBgResources { + // 编辑界面的背景资源 + private final static int [] BG_EDIT_RESOURCES = new int [] { + R.drawable.edit_yellow, // 黄色背景 + R.drawable.edit_blue, // 蓝色背景 + R.drawable.edit_white, // 白色背景 + R.drawable.edit_green, // 绿色背景 + R.drawable.edit_red // 红色背景 + }; + + // 编辑界面标题的背景资源 + private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] { + R.drawable.edit_title_yellow, // 黄色标题背景 + R.drawable.edit_title_blue, // 蓝色标题背景 + R.drawable.edit_title_white, // 白色标题背景 + R.drawable.edit_title_green, // 绿色标题背景 + R.drawable.edit_title_red // 红色标题背景 + }; + + // 获取笔记编辑界面的背景资源 + public static int getNoteBgResource(int id) { + return BG_EDIT_RESOURCES[id]; + } + + // 获取笔记编辑界面标题的背景资源 + public static int getNoteTitleBgResource(int id) { + return BG_EDIT_TITLE_RESOURCES[id]; + } + } + + // 获取默认的背景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 // 红色单一条目 + }; + + // 获取笔记条目的第一个背景资源 + public static int getNoteBgFirstRes(int id) { + return BG_FIRST_RESOURCES[id]; + } + + // 获取笔记条目的最后一个背景资源 + public static int getNoteBgLastRes(int id) { + return BG_LAST_RESOURCES[id]; + } + + // 获取笔记条目的单一背景资源 + public static int getNoteBgSingleRes(int id) { + return BG_SINGLE_RESOURCES[id]; + } + + // 获取笔记条目的正常背景资源 + public static int getNoteBgNormalRes(int id) { + return BG_NORMAL_RESOURCES[id]; + } + + // 获取文件夹的背景资源 + public static int getFolderBgRes() { + return R.drawable.list_folder; // 文件夹背景资源 + } + } + + // 小部件背景资源类 + public static class WidgetBgResources { + // 2x2 小部件的背景资源 + 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 // 红色背景 + }; + + // 获取 2x2 小部件的背景资源 + public static int getWidget2xBgResource(int id) { + return BG_2X_RESOURCES[id]; + } + + // 4x4 小部件的背景资源 + 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 // 红色背景 + }; + + // 获取 4x4 小部件的背景资源 + 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 // 超大号文字 + }; + + // 获取文字外观资源 + public static int getTexAppearanceResource(int id) { + /** + * HACKME: 修复存储资源ID到共享偏好设置的bug。 + * 如果ID大于资源数组的长度,返回默认的字体大小。 + */ + if (id >= TEXTAPPEARANCE_RESOURCES.length) { + return BG_DEFAULT_FONT_SIZE; // 如果ID超出范围,返回默认的字体大小 + } + return TEXTAPPEARANCE_RESOURCES[id]; + } + + // 获取文字外观资源的数量 + public static int getResourcesSize() { + return TEXTAPPEARANCE_RESOURCES.length; + } + } +} diff --git a/src/WorkingNote.java b/src/WorkingNote.java new file mode 100644 index 0000000..e62151e --- /dev/null +++ b/src/WorkingNote.java @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.model; + +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.database.Cursor; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.Notes.TextNote; +import net.micode.notes.tool.ResourceParser.NoteBgResources; + +/** + * WorkingNote 类处理与笔记相关的工作逻辑。它支持创建新笔记、加载现有笔记、设置笔记内容、 + * 管理笔记的背景色、提醒时间等,同时支持与小部件的交互。 + */ +public class WorkingNote { + private Note mNote; // 代表笔记的 Note 对象 + private long mNoteId; // 笔记的 ID + private String mContent; // 笔记的内容(文本) + private int mMode; // 笔记的模式(例如:清单模式) + private long mAlertDate; // 提醒时间 + private long mModifiedDate; // 最后修改时间 + private int mBgColorId; // 背景色 ID + private int mWidgetId; // 小部件 ID + private int mWidgetType; // 小部件类型 + private long mFolderId; // 文件夹 ID + private Context mContext; // 上下文 + private boolean mIsDeleted; // 是否被标记为已删除 + private NoteSettingChangedListener mNoteSettingStatusListener; // 设置变更监听器 + + private static final String TAG = "WorkingNote"; // 日志标签 + + // 数据查询的列名数组 + public static final String[] DATA_PROJECTION = new String[] { + DataColumns.ID, DataColumns.CONTENT, DataColumns.MIME_TYPE, DataColumns.DATA1, + DataColumns.DATA2, DataColumns.DATA3, DataColumns.DATA4 + }; + + // 笔记数据的查询列名 + public static final String[] NOTE_PROJECTION = new String[] { + NoteColumns.PARENT_ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, + NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.MODIFIED_DATE + }; + + // 各列的索引常量 + private static final int DATA_ID_COLUMN = 0; + private static final int DATA_CONTENT_COLUMN = 1; + private static final int DATA_MIME_TYPE_COLUMN = 2; + private static final int DATA_MODE_COLUMN = 3; + + private static final int NOTE_PARENT_ID_COLUMN = 0; + private static final int NOTE_ALERTED_DATE_COLUMN = 1; + private static final int NOTE_BG_COLOR_ID_COLUMN = 2; + private static final int NOTE_WIDGET_ID_COLUMN = 3; + private static final int NOTE_WIDGET_TYPE_COLUMN = 4; + private static final int NOTE_MODIFIED_DATE_COLUMN = 5; + + /** + * 构造一个新的工作笔记 + */ + private WorkingNote(Context context, long folderId) { + mContext = context; + mAlertDate = 0; + mModifiedDate = System.currentTimeMillis(); + mFolderId = folderId; + mNote = new Note(); // 创建一个新的 Note 对象 + mNoteId = 0; + mIsDeleted = false; + mMode = 0; + mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 默认无效的小部件类型 + } + + /** + * 构造一个现有的工作笔记 + */ + private WorkingNote(Context context, long noteId, long folderId) { + mContext = context; + mNoteId = noteId; + mFolderId = folderId; + mIsDeleted = false; + mNote = new Note(); + loadNote(); // 加载笔记数据 + } + + /** + * 从数据库加载笔记的信息 + */ + private void loadNote() { + // 从笔记内容 URI 中查询笔记的基本信息 + Cursor cursor = mContext.getContentResolver().query( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, + null, null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + // 获取笔记的基本信息 + mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); + mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); + mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); + mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN); + mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN); + mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); + } + cursor.close(); + } else { + Log.e(TAG, "No note with id:" + mNoteId); + throw new IllegalArgumentException("Unable to find note with id " + mNoteId); + } + loadNoteData(); // 加载笔记的内容数据 + } + + /** + * 加载笔记的具体内容(如文本内容或通话记录等) + */ + private void loadNoteData() { + // 查询笔记的数据内容 + Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, + DataColumns.NOTE_ID + "=?", new String[] { + String.valueOf(mNoteId) + }, null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + do { + String type = cursor.getString(DATA_MIME_TYPE_COLUMN); + if (DataConstants.NOTE.equals(type)) { + mContent = cursor.getString(DATA_CONTENT_COLUMN); + mMode = cursor.getInt(DATA_MODE_COLUMN); + mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); // 设置文本数据ID + } else if (DataConstants.CALL_NOTE.equals(type)) { + mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); // 设置通话数据ID + } else { + Log.d(TAG, "Wrong note type with type:" + type); + } + } while (cursor.moveToNext()); + } + cursor.close(); + } else { + Log.e(TAG, "No data with id:" + mNoteId); + throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); + } + } + + /** + * 创建一个空的工作笔记 + */ + public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, + int widgetType, int defaultBgColorId) { + WorkingNote note = new WorkingNote(context, folderId); + note.setBgColorId(defaultBgColorId); // 设置背景色 + note.setWidgetId(widgetId); // 设置小部件ID + note.setWidgetType(widgetType); // 设置小部件类型 + return note; + } + + /** + * 加载指定ID的工作笔记 + */ + public static WorkingNote load(Context context, long id) { + return new WorkingNote(context, id, 0); + } + + /** + * 保存笔记 + */ + public synchronized boolean saveNote() { + if (isWorthSaving()) { // 如果笔记值得保存 + if (!existInDatabase()) { // 如果笔记不存在数据库 + if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { + Log.e(TAG, "Create new note fail with id:" + mNoteId); + return false; + } + } + + mNote.syncNote(mContext, mNoteId); // 同步笔记内容到数据库 + + // 如果笔记关联了小部件,更新小部件内容 + if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && mWidgetType != Notes.TYPE_WIDGET_INVALIDE + && mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onWidgetChanged(); + } + return true; + } else { + return false; + } + } + + /** + * 判断笔记是否已经存在于数据库 + */ + public boolean existInDatabase() { + return mNoteId > 0; + } + + /** + * 判断笔记是否值得保存 + */ + private boolean isWorthSaving() { + return !(mIsDeleted || (TextUtils.isEmpty(mContent) && !existInDatabase()) + || (existInDatabase() && !mNote.isLocalModified())); // 判断笔记是否被删除或没有修改 + } + + // 其他设置方法(设置提醒时间、背景色、小部件等) + public void setAlertDate(long date, boolean set) { ... } + public void markDeleted(boolean mark) { ... } + public void setBgColorId(int id) { ... } + public void setCheckListMode(int mode) { ... } + public void setWidgetType(int type) { ... } + public void setWidgetId(int id) { ... } + public void setWorkingText(String text) { ... } + + // 获取笔记内容、提醒时间、修改时间等信息 + public String getContent() { return mContent; } + public long getAlertDate() { return mAlertDate; } + public long getModifiedDate() { return mModifiedDate; } + public int getBgColorResId() { return NoteBgResources.getNoteBgResource(mBgColorId); } + public int getBgColorId() { return mBgColorId; } + public int getCheckListMode() { return mMode; } + public long getNoteId() { return mNoteId; } + public long getFolderId() { return mFolderId; } + public int getWidgetId() { return mWidgetId; } + public int getWidgetType() { return mWidgetType; } + + // 设置变更监听接口 + public interface NoteSettingChangedListener { + void onBackgroundColorChanged(); // 背景色变更时调用 + void onClockAlertChanged(long date, boolean set); // 提醒时间变更时调用 + void onWidgetChanged(); // 小部件变更时调用 + void onCheckListModeChanged(int oldMode, int newMode); // 清单模式切换时调用 + } +}