diff --git a/BackupUtils.java b/BackupUtils.java new file mode 100644 index 0000000..7082693 --- /dev/null +++ b/BackupUtils.java @@ -0,0 +1,376 @@ +/* + * 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; + +// 导入必要的Android和Java类 +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; // 导入Notes数据访问类 +import net.micode.notes.data.Notes.DataColumns; // 导入Notes数据表的列定义 +import net.micode.notes.data.Notes.DataConstants; // 导入Notes数据表的常量定义 +import net.micode.notes.data.Notes.NoteColumns; // 导入Notes数据表的列定义 + +import java.io.File; // 提供文件和目录路径名的抽象表示形式 +import java.io.FileNotFoundException; // 当试图打开文件失败时抛出的异常 +import java.io.FileOutputStream; // 文件输出流,用于将数据写入文件 +import java.io.IOException; // 当发生某种I/O异常时抛出的异常 +import java.io.PrintStream; // 打印流,提供便利的打印方法 + +// 声明一个用于备份的工具类 +public class BackupUtils { + // 定义日志标签 + private static final String TAG = "BackupUtils"; + // 单例模式相关变量 + private static BackupUtils sInstance; + + // 获取BackupUtils实例的静态方法,使用同步关键字确保线程安全 + public static synchronized BackupUtils getInstance(Context context) { + if (sInstance == null) { + sInstance = new BackupUtils(context); + } + return sInstance; + } + + // 定义表示备份或恢复状态的常量 + public static final int STATE_SD_CARD_UNMOUONTED = 0; // SD卡未挂载 + 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; // 备份或恢复成功 + + // TextExport成员变量,用于文本导出 + private TextExport mTextExport; + + // 私有构造函数,用于单例模式 + private BackupUtils(Context context) { + mTextExport = new TextExport(context); + } + + // 检查外部存储是否可用的方法 + private static boolean externalStorageAvailable() { + return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); + } + + // 导出数据到文本文件的方法 + public int exportToText() { + return mTextExport.exportToText(); + } + + // 获取导出的文本文件名的方法 + public String getExportedTextFileName() { + return mTextExport.mFileName; + } + + // 获取导出的文本文件目录的方法 + public String getExportedTextFileDir() { + return mTextExport.mFileDirectory; + } + + // 定义一个内部类TextExport,用于处理文本导出逻辑 + 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; + // 注意:DATA_COLUMN_CALL_DATE是错误的索引,应该是DATA_COLUMN_DATA1或其他 + 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 = ""; + } + + // 根据索引获取文本格式的方法 + private String getFormat(int id) { + return TEXT_FORMAT[id]; + } + + // 导出指定文件夹的笔记到文本的方法 + 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(); + } + } + + // ... 省略了exportNoteToText方法的实现,该方法应该负责将指定笔记的内容导出到文本 + } +} +//定义一个方法,用于将笔记内容导出为文本格式 +private void exportNoteToText(String noteId, PrintStream ps) { + // 使用内容解析器查询特定笔记ID的笔记数据 + 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 { + // 获取笔记的MIME类型 + 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, "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; + } + // 首先导出文件夹及其笔记 + 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)); + } + String folderId = folderCursor.getString(NOTE_COLUMN_ID); + // 导出文件夹下的笔记 + exportFolderToText(folderId, ps); + } while (folderCursor.moveToNext()); + } + folderCursor.close(); + } + + // 导出根文件夹下的笔记 + 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)))); + // 查询并导出该笔记的内容 + String noteId = noteCursor.getString(NOTE_COLUMN_ID); + exportNoteToText(noteId, ps); + } while (noteCursor.moveToNext()); + } + noteCursor.close(); + } + ps.close(); + + return STATE_SUCCESS; +} +/** + * 获取一个指向导出文本文件的打印流。 + * 注意:此方法的实现未在代码中给出,但基于上下文,该方法应该负责创建或打开一个文件, + * 并返回一个可以向该文件写入数据的PrintStream对象。 + */ +//定义一个私有方法,用于获取一个指向导出文本文件的PrintStream对象 +private PrintStream getExportToTextPrintStream() { + // 调用generateFileMountedOnSDcard方法生成文件,该方法需要上下文、文件路径资源ID和文件名格式资源ID + File file = generateFileMountedOnSDcard(mContext, R.string.file_path, + R.string.file_name_txt_format); + // 如果文件创建失败(即file为null) + if (file == null) { + // 打印错误日志 + Log.e(TAG, "create file to exported failed"); + // 返回null,表示无法获取PrintStream + return null; + } + // 保存文件名 + mFileName = file.getName(); + // 保存文件目录路径 + mFileDirectory = mContext.getString(R.string.file_path); + PrintStream ps = null; + try { + // 创建一个指向文件的FileOutputStream + FileOutputStream fos = new FileOutputStream(file); + // 使用FileOutputStream创建一个PrintStream对象 + ps = new PrintStream(fos); + } catch (FileNotFoundException e) { + // 如果文件未找到,打印堆栈跟踪并返回null + e.printStackTrace(); + return null; + } catch (NullPointerException e) { + // 如果发生空指针异常,打印堆栈跟踪并返回null + e.printStackTrace(); + return null; + } + // 返回创建的PrintStream对象 + return ps; +} + +/** +* 生成一个位于SD卡上的文本文件,用于存储导入的数据 +*/ +private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { + // 创建一个StringBuilder对象用于拼接文件路径 + StringBuilder sb = new StringBuilder(); + // 追加SD卡根目录路径 + sb.append(Environment.getExternalStorageDirectory()); + // 追加从资源文件中获取的文件路径 + sb.append(context.getString(filePathResId)); + // 创建文件目录的File对象 + File filedir = new File(sb.toString()); + // 追加从资源文件中获取的文件名格式,并格式化当前日期作为文件名的一部分 + sb.append(context.getString( + fileNameFormatResId, + DateFormat.format(context.getString(R.string.format_date_ymd), + System.currentTimeMillis()))); + // 创建文件的File对象 + File file = new File(sb.toString()); + + try { + // 如果文件目录不存在,则创建它 + if (!filedir.exists()) { + filedir.mkdir(); + } + // 如果文件不存在,则创建它 + if (!file.exists()) { + file.createNewFile(); + } + // 返回创建的文件对象 + return file; + } catch (SecurityException e) { + // 如果发生安全异常(如没有SD卡写入权限),打印堆栈跟踪 + e.printStackTrace(); + } catch (IOException e) { + // 如果发生IO异常,打印堆栈跟踪 + e.printStackTrace(); + } + + // 如果发生异常,返回null + return null; +} + diff --git a/DataUtils.java b/DataUtils.java new file mode 100644 index 0000000..c2be8f7 --- /dev/null +++ b/DataUtils.java @@ -0,0 +1,380 @@ +/* + * 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; + +// 导入所需的Android和内容提供者操作的类 +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; + +// 导入Notes应用中的相关类 +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; + +// 导入Java工具类 +import java.util.ArrayList; +import java.util.HashSet; + +// 声明DataUtils工具类 +public class DataUtils { + // 定义日志标签 + public static final String TAG = "DataUtils"; + + /** + * 批量删除笔记 + * @param resolver 内容解析器 + * @param ids 要删除的笔记ID集合 + * @return 操作是否成功 + */ + public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { + // 检查ID集合是否为空 + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; // 如果为空,则认为操作成功(可能是一个设计选择,但通常应返回false或抛出异常) + } + // 检查ID集合是否不包含任何元素 + if (ids.size() == 0) { + Log.d(TAG, "no id is in the hashset"); + return true; // 同上,通常应返回false + } + + // 创建操作列表 + ArrayList operationList = new ArrayList<>(); + // 遍历ID集合 + for (long id : ids) { + // 检查是否为系统根文件夹ID,不应删除 + if(id == Notes.ID_ROOT_FOLDER) { + Log.e(TAG, "Don't delete system folder root"); + continue; // 跳过系统根文件夹 + } + // 创建删除操作并添加到操作列表 + ContentProviderOperation.Builder builder = ContentProviderOperation + .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + operationList.add(builder.build()); + } + try { + // 批量执行操作 + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + // 检查操作结果 + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + return false; // 如果操作失败,则返回false + } + return true; // 操作成功 + } catch (RemoteException e) { + // 捕获远程异常并记录 + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } catch (OperationApplicationException e) { + // 捕获操作应用异常并记录 + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } + return false; // 如果发生异常,则返回false + } + + /** + * 将笔记移动到指定文件夹 + * @param resolver 内容解析器 + * @param id 笔记ID + * @param srcFolderId 源文件夹ID + * @param desFolderId 目标文件夹ID + */ + public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { + // 创建要更新的内容值 + ContentValues values = new ContentValues(); + values.put(NoteColumns.PARENT_ID, desFolderId); // 设置目标文件夹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); + } + + /** + * 批量将笔记移动到指定文件夹 + * @param resolver 内容解析器 + * @param ids 要移动的笔记ID集合 + * @param folderId 目标文件夹ID + * @return 操作是否成功 + */ + public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, + long folderId) { + // 检查ID集合是否为空 + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; // 同上,通常应返回false + } + + // 创建操作列表 + ArrayList operationList = new ArrayList<>(); + // 遍历ID集合 + 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; // 如果操作失败,则返回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; // 如果发生异常,则返回false + } + + /** + * 获取用户文件夹数量(排除系统文件夹) + * @param resolver 内容解析器 + * @return 用户文件夹数量 + */ + public static int getUserFolderCount(ContentResolver resolver) { + // 执行查询操作,获取用户文件夹数量 + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, + new String[] { "COUNT(*)" }, // 选择要返回的列(这里是计数) + NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", // 查询条件:类型为文件夹且不是垃圾箱文件夹 + new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, // 查询参数 + null); // 排序(此处不需要) + + int count = 0; + if(cursor != null) { + if(cursor.moveToFirst()) { + try { + count = cursor.getInt(0); // 获取计数结果 + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "get folder count failed:" + e.toString()); // 如果发生索引越界异常,则记录错误 + } finally { + cursor.close(); // 关闭游标 + } + } + } + return count; // 返回用户文件夹数量 + } +} +//判断指定类型的笔记是否在笔记数据库中可见(不在回收站中) +public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { + // 使用ContentResolver查询指定ID的笔记,过滤条件为类型匹配且父ID不等于回收站ID + 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(); // 关闭Cursor + } + return exist; // 返回笔记是否存在的布尔值 +} + +//判断指定ID的笔记是否存在于笔记数据库中 +public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { + // 使用ContentResolver查询指定ID的笔记,没有过滤条件 + 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(); // 关闭Cursor + } + return exist; // 返回笔记是否存在的布尔值 +} + +//判断指定ID的数据项是否存在于数据数据库中 +public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { + // 使用ContentResolver查询指定ID的数据项,没有过滤条件 + 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(); // 关闭Cursor + } + return exist; // 返回数据项是否存在的布尔值 +} + +//判断指定名称的文件夹是否存在于笔记数据库中且不在回收站中 +public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { + // 使用ContentResolver查询文件夹,过滤条件为类型为文件夹且父ID不等于回收站ID且摘要(名称)匹配 + 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(); // 关闭Cursor + } + return exist; // 返回文件夹是否存在的布尔值 +} + +//获取指定文件夹ID下的所有笔记小部件属性 +public static HashSet getFolderNoteWidget(ContentResolver resolver, long folderId) { + // 使用ContentResolver查询指定文件夹ID下的笔记小部件信息 + 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()) { // 移动到Cursor的第一行 + set = new HashSet(); // 初始化HashSet + do { + try { + AppWidgetAttribute widget = new AppWidgetAttribute(); // 创建小部件属性对象 + widget.widgetId = c.getInt(0); // 获取小部件ID + widget.widgetType = c.getInt(1); // 获取小部件类型 + set.add(widget); // 将小部件属性添加到HashSet中 + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, e.toString()); // 捕获并打印索引越界异常 + } + } while (c.moveToNext()); // 移动到Cursor的下一行 + } + c.close(); // 关闭Cursor + } + return set; // 返回包含所有笔记小部件属性的HashSet +} + +//根据笔记ID获取关联的电话号码 +public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { + // 使用ContentResolver查询指定笔记ID下的电话号码数据 + 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()) { // 如果Cursor不为空且移动到第一行 + try { + return cursor.getString(0); // 返回电话号码 + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "Get call number fails " + e.toString()); // 捕获并打印索引越界异常 + } finally { + cursor.close(); // 关闭Cursor + } + } + return ""; // 如果没有找到电话号码,返回空字符串 +} + +//根据电话号码和通话日期获取笔记ID +public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { + // 使用ContentResolver查询指定电话号码和通话日期下的笔记ID + 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()) { // 如果Cursor不为空且移动到第一行 + try { + return cursor.getLong(0); // 返回笔记ID + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "Get call note id fails " + e.toString()); // 捕获并打印索引越界异常 + } + } + cursor.close(); // 关闭Cursor + } + return 0; // 如果没有找到笔记ID,返回0 +} + +//定义一个静态方法,用于通过笔记ID从内容提供者中获取笔记摘要 +public static String getSnippetById(ContentResolver resolver, long noteId) { + // 使用ContentResolver查询特定URI下的数据 + // Notes.CONTENT_NOTE_URI 是笔记内容的URI + // 查询的列只有 NoteColumns.SNIPPET,即笔记摘要 + // 查询条件是 NoteColumns.ID 等于传入的 noteId + // 最后一个参数为null,表示不需要对结果进行排序 + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, + new String [] { NoteColumns.SNIPPET }, + NoteColumns.ID + "=?", + new String [] { String.valueOf(noteId)}, + null); + + // 检查返回的Cursor是否不为null + if (cursor != null) { + String snippet = ""; // 初始化摘要字符串为空 + // 如果Cursor移动到第一行(即存在查询结果) + if (cursor.moveToFirst()) { + // 从Cursor中获取第一列的数据(即SNIPPET列),并赋值给snippet变量 + snippet = cursor.getString(0); + } + // 关闭Cursor以释放资源 + cursor.close(); + // 返回查询到的摘要字符串 + return snippet; + } + // 如果Cursor为null,则抛出异常,表示未找到指定ID的笔记 + throw new IllegalArgumentException("Note is not found with id: " + noteId); +} + +//定义一个静态方法,用于格式化笔记摘要字符串 +public static String getFormattedSnippet(String snippet) { + // 如果传入的摘要字符串不为null + if (snippet != null) { + // 去除字符串两端的空白字符 + snippet = snippet.trim(); + // 查找字符串中第一次出现换行符的位置 + int index = snippet.indexOf('\n'); + // 如果找到了换行符 + if (index != -1) { + // 将字符串截取到换行符之前的位置,即只保留第一行 + snippet = snippet.substring(0, index); + } + } + // 返回格式化后的摘要字符串 + return snippet; +} \ No newline at end of file diff --git a/GTaskManager.java b/GTaskManager.java new file mode 100644 index 0000000..bdf46e2 --- /dev/null +++ b/GTaskManager.java @@ -0,0 +1,876 @@ +/* + * 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; + +// 导入必要的Android和Java类 +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类 +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; + + // 声明单例实例和成员变量 + private static GTaskManager mInstance = null; + private Activity mActivity; + private Context mContext; + private ContentResolver mContentResolver; + private boolean mSyncing; + private boolean mCancelled; + private HashMap mGTaskListHashMap; + private HashMap mGTaskHashMap; + private HashMap mMetaHashMap; + private TaskList mMetaList; + private HashSet mLocalDeleteIdMap; + private HashMap mGidToNid; + private HashMap mNidToGid; + + // 私有构造函数,用于创建单例 + 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单例实例 + public static synchronized GTaskManager getInstance() { + if (mInstance == null) { + mInstance = new GTaskManager(); + } + return mInstance; + } + + // 设置Activity上下文(用于获取认证令牌) + public synchronized void setActivityContext(Activity activity) { + mActivity = activity; + } + + // 执行同步操作 + public int sync(Context context, GTaskASyncTask asyncTask) { + // 如果已经在同步,则返回同步进行中状态 + if (mSyncing) { + Log.d(TAG, "Sync is in progress"); + return STATE_SYNC_IN_PROGRESS; + } + // 初始化成员变量 + mContext = context; + mContentResolver = mContext.getContentResolver(); + mSyncing = true; + mCancelled = false; + // 清除所有哈希映射和集合 + mGTaskListHashMap.clear(); + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + + try { + // 获取GTaskClient实例 + GTaskClient client = GTaskClient.getInstance(); + client.resetUpdateArray(); + + // 登录Google Tasks + if (!mCancelled) { + if (!client.login(mActivity)) { + throw new NetworkFailureException("login google task failed"); + } + } + + // 从Google获取任务列表 + asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); + initGTaskList(); + + // 执行内容同步 + asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); + syncContent(); + } catch (NetworkFailureException e) { + Log.e(TAG, e.toString()); + return STATE_NETWORK_ERROR; + } catch (ActionFailureException e) { + Log.e(TAG, e.toString()); + return STATE_INTERNAL_ERROR; + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return STATE_INTERNAL_ERROR; + } finally { + // 清除所有哈希映射和集合,重置同步状态 + mGTaskListHashMap.clear(); + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + mSyncing = false; + } + + // 返回同步结果状态 + return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; + } + + // 定义一个初始化任务列表的方法,该方法可能会抛出网络失败异常 + private void initGTaskList() throws NetworkFailureException { + // 如果任务被取消,则直接返回,不执行后续操作 + if (mCancelled) + return; + // 获取GTaskClient的实例 + GTaskClient client = GTaskClient.getInstance(); + try { + // 从客户端获取任务列表的JSON数组 + JSONArray jsTaskLists = client.getTaskLists(); + + // 首先初始化元数据列表 + mMetaList = null; + // 遍历所有的任务列表 + for (int i = 0; i < jsTaskLists.length(); i++) { + // 获取当前任务列表的JSON对象 + JSONObject object = jsTaskLists.getJSONObject(i); + // 获取任务列表的ID + 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(); + // 使用JSON对象设置元数据列表的内容 + mMetaList.setContentByRemoteJSON(object); + + // 加载元数据 + JSONArray jsMetas = client.getTaskList(gid); + // 遍历所有的元数据 + for (int j = 0; j < jsMetas.length(); j++) { + object = (JSONObject) jsMetas.getJSONObject(j); + MetaData metaData = new MetaData(); + // 使用JSON对象设置元数据的内容 + metaData.setContentByRemoteJSON(object); + // 如果该元数据值得保存 + if (metaData.isWorthSaving()) { + // 将元数据添加到元数据列表中 + mMetaList.addChildTask(metaData); + // 如果元数据有GID,则将其添加到哈希映射中 + if (metaData.getGid() != null) { + mMetaHashMap.put(metaData.getRelatedGid(), metaData); + } + } + } + } + } + + // 如果元数据列表不存在,则创建它 + if (mMetaList == null) { + mMetaList = new TaskList(); + // 设置元数据列表的名称 + mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META); + // 通过客户端创建元数据列表 + GTaskClient.getInstance().createTaskList(mMetaList); + } + + // 初始化任务列表 + for (int i = 0; i < jsTaskLists.length(); i++) { + JSONObject object = jsTaskLists.getJSONObject(i); + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); + + // 如果任务列表名称以特定的前缀开始,并且不等于元数据文件夹名称 + if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) + && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META)) { + TaskList tasklist = new TaskList(); + // 使用JSON对象设置任务列表的内容 + tasklist.setContentByRemoteJSON(object); + // 将任务列表添加到哈希映射中 + mGTaskListHashMap.put(gid, tasklist); + mGTaskHashMap.put(gid, tasklist); + + // 加载任务 + JSONArray jsTasks = client.getTaskList(gid); + // 遍历所有的任务 + for (int j = 0; j < jsTasks.length(); j++) { + object = (JSONObject) jsTasks.getJSONObject(j); + gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + Task task = new Task(); + // 使用JSON对象设置任务的内容 + task.setContentByRemoteJSON(object); + // 如果该任务值得保存 + if (task.isWorthSaving()) { + // 设置任务的元数据 + task.setMetaInfo(mMetaHashMap.get(gid)); + // 将任务添加到任务列表中 + tasklist.addChildTask(task); + // 更新任务在哈希映射中的引用 + mGTaskHashMap.put(gid, task); + } + } + } + } + } catch (JSONException e) { + // 捕获JSON异常,记录错误日志 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出自定义的操作失败异常 + throw new ActionFailureException("initGTaskList: handing JSONObject failed"); + } + } + + // 定义一个名为syncContent的私有方法,该方法可能会抛出NetworkFailureException异常 + private void syncContent() throws NetworkFailureException { + // 定义一个变量syncType用于存储同步类型 + int syncType; + // 定义一个Cursor对象c,初始化为null,用于查询数据库 + Cursor c = null; + // 定义一个字符串变量gid,用于存储Google任务的ID + String gid; + // 定义一个Node对象node,用于表示Google任务节点 + Node node; + + // 清空本地删除ID的映射表 + mLocalDeleteIdMap.clear(); + + // 如果同步操作被取消,则直接返回 + if (mCancelled) { + return; + } + + // 处理本地已删除的笔记 + try { + // 查询本地数据库中非系统类型且不在回收站的笔记 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type<>? AND parent_id=?)", new String[] { + String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) + }, null); + // 如果查询结果不为空 + if (c != null) { + while (c.moveToNext()) { + // 获取Google任务的ID + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + // 从HashMap中获取对应的Node对象 + node = mGTaskHashMap.get(gid); + if (node != null) { + // 从HashMap中移除该Node对象 + mGTaskHashMap.remove(gid); + // 执行远程删除操作 + doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); + } + + // 将本地笔记ID添加到删除ID映射表中 + mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); + } + } else { + // 如果查询失败,记录警告日志 + Log.w(TAG, "failed to query trash folder"); + } + } finally { + // 关闭Cursor对象,释放资源 + if (c != null) { + c.close(); + c = null; + } + } + + // 首先同步文件夹 + syncFolder(); + + // 处理数据库中存在的笔记 + try { + // 查询本地数据库中类型为笔记且不在回收站的笔记 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type=? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + // 如果查询结果不为空 + if (c != null) { + while (c.moveToNext()) { + // 获取Google任务的ID + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + // 从HashMap中获取对应的Node对象 + node = mGTaskHashMap.get(gid); + if (node != null) { + // 从HashMap中移除该Node对象 + mGTaskHashMap.remove(gid); + // 更新gid到nid的映射以及nid到gid的映射 + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); + // 获取同步类型 + syncType = node.getSyncAction(c); + } else { + // 如果gid为空,表示是本地新增的笔记 + if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { + syncType = Node.SYNC_ACTION_ADD_REMOTE; + } else { + // 如果gid不为空但不在HashMap中,表示远程已删除 + syncType = Node.SYNC_ACTION_DEL_LOCAL; + } + } + // 执行同步操作 + doContentSync(syncType, node, c); + } + } else { + // 如果查询失败,记录警告日志 + Log.w(TAG, "failed to query existing note in database"); + } + + } finally { + // 关闭Cursor对象,释放资源 + if (c != null) { + c.close(); + c = null; + } + } + + // 遍历HashMap中剩余的项,执行本地添加操作 + Iterator> iter = mGTaskHashMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + node = entry.getValue(); + doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); + } + + // 检查mCancelled标志,确保同步操作未被取消 + // 清空本地删除表 + if (!mCancelled) { + if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { + // 如果批量删除失败,抛出ActionFailureException异常 + throw new ActionFailureException("failed to batch-delete local deleted notes"); + } + } + + // 刷新本地同步ID + if (!mCancelled) { + // 提交更新并刷新本地同步ID + GTaskClient.getInstance().commitUpdate(); + refreshLocalSyncId(); + } + + } + + // 定义一个私有的同步文件夹方法,该方法可能会抛出网络失败异常 + private void syncFolder() throws NetworkFailureException { + Cursor c = null; // 初始化一个游标对象,用于数据库查询 + String gid; // 用于存储从数据库查询得到的Google任务ID + Node node; // 用于存储节点对象,代表一个文件夹或任务 + int syncType; // 用于存储同步类型 + + // 如果同步操作被取消,则直接返回 + if (mCancelled) { + return; + } + + // 同步根文件夹的部分 + try { + // 从内容提供者查询根文件夹的信息 + c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, + Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); + if (c != null) { + c.moveToNext(); // 移动到查询结果的第一行 + gid = c.getString(SqlNote.GTASK_ID_COLUMN); // 获取Google任务ID + node = mGTaskHashMap.get(gid); // 从哈希表中获取节点对象 + if (node != null) { + // 如果节点存在,则更新本地和远程的映射关系,并根据需要更新远程名称 + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); + mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); + if (!node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) + doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); + } else { + // 如果节点不存在,则添加远程节点 + doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); + } + } else { + // 如果查询失败,则记录警告日志 + Log.w(TAG, "failed to query root folder"); + } + } finally { + // 确保游标被关闭 + if (c != null) { + c.close(); + c = null; + } + } + + // 同步通话记录文件夹的部分(类似于根文件夹的处理逻辑) + // ...(代码省略,逻辑同上) + + // 同步本地已存在的文件夹的部分 + try { + // 从内容提供者查询所有非垃圾文件夹的信息 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(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 { + // 如果节点不存在,则根据Google任务ID是否为空决定是本地添加还是远程删除 + if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { + syncType = Node.SYNC_ACTION_ADD_REMOTE; + } else { + syncType = Node.SYNC_ACTION_DEL_LOCAL; + } + } + doContentSync(syncType, node, c); // 根据同步类型进行同步 + } + } else { + // 如果查询失败,则记录警告日志 + Log.w(TAG, "failed to query existing folder"); + } + } finally { + // 确保游标被关闭 + if (c != null) { + c.close(); + c = null; + } + } + + // 同步远程添加的文件夹的部分 + Iterator> iter = mGTaskListHashMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + gid = entry.getKey(); + node = entry.getValue(); + if (mGTaskHashMap.containsKey(gid)) { + // 如果本地已经存在该Google任务ID的节点,则更新本地映射并添加本地节点 + mGTaskHashMap.remove(gid); + doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); + } + } + + // 如果同步操作没有被取消,则提交更新 + if (!mCancelled) + GTaskClient.getInstance().commitUpdate(); + } + + // 定义一个方法用于内容同步,接收同步类型、节点和游标作为参数,可能抛出网络失败异常 + private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { + // 如果同步被取消,则直接返回 + if (mCancelled) { + return; + } + + MetaData meta; // 定义一个MetaData对象用于后续操作 + // 根据不同的同步类型执行不同的操作 + 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)); // 从哈希映射中获取MetaData对象 + if (meta != null) { + GTaskClient.getInstance().deleteNode(meta); // 删除节点 + } + mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); // 将本地删除节点的ID添加到映射中 + break; + case Node.SYNC_ACTION_DEL_REMOTE: // 远程删除节点 + meta = mMetaHashMap.get(node.getGid()); // 从哈希映射中获取MetaData对象 + 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"); + } + } + + // 定义一个方法用于添加本地节点 + private void addLocalNode(Node node) throws NetworkFailureException { + // 如果同步被取消,则直接返回 + if (mCancelled) { + return; + } + + SqlNote sqlNote; // 定义一个SqlNote对象用于后续操作 + // 判断节点类型,如果是任务列表,则进行特殊处理 + if (node instanceof TaskList) { + // 根据任务列表的名称判断是否为特殊列表(如默认列表、通话记录列表) + if (node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { + sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); + } else if (node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { + sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); + } else { + sqlNote = new SqlNote(mContext); + sqlNote.setContent(node.getLocalJSONFromContent()); // 设置节点内容 + sqlNote.setParentId(Notes.ID_ROOT_FOLDER); // 设置父节点ID为根文件夹ID + } + } else { // 如果是任务节点,则进行通用处理 + sqlNote = new SqlNote(mContext); + JSONObject js = node.getLocalJSONFromContent(); // 获取节点内容的JSON对象 + try { + // 检查JSON对象中是否包含特定字段,并根据需要进行处理 + if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + if (note.has(NoteColumns.ID)) { + long id = note.getLong(NoteColumns.ID); + if (DataUtils.existInNoteDatabase(mContentResolver, id)) { + // 如果数据库中已存在该ID,则移除ID字段 + 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)) { + // 如果数据库中已存在该数据ID,则移除数据ID字段 + data.remove(DataColumns.ID); + } + } + } + } + } catch (JSONException e) { + Log.w(TAG, e.toString()); + e.printStackTrace(); + } + sqlNote.setContent(js); // 设置节点内容的JSON对象 + + // 获取父节点的ID,并设置给当前节点 + 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()); + } + + // 创建本地节点 + sqlNote.setGtaskId(node.getGid()); // 设置节点的全局ID + sqlNote.commit(false); // 提交节点到数据库 + + // 更新全局ID到本地ID的映射 + mGidToNid.put(node.getGid(), sqlNote.getId()); + mNidToGid.put(sqlNote.getId(), node.getGid()); + + // 更新MetaData + updateRemoteMeta(node.getGid(), sqlNote); + } + + // 定义一个私有方法,用于更新本地节点,参数包括节点和数据库游标 + private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { + // 如果操作被取消,则直接返回 + if (mCancelled) { + return; + } + + SqlNote sqlNote; + // 创建一个SqlNote实例,用于更新笔记 + sqlNote = new SqlNote(mContext, c); + // 设置SqlNote的内容为节点的本地JSON内容 + sqlNote.setContent(node.getLocalJSONFromContent()); + + // 根据节点类型获取父节点的ID,如果是任务则通过GID查找,否则使用根文件夹ID + Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) + : new Long(Notes.ID_ROOT_FOLDER); + // 如果找不到父节点的ID,则记录错误并抛出异常 + if (parentId == null) { + Log.e(TAG, "cannot find task's parent id locally"); + throw new ActionFailureException("cannot update local node"); + } + // 设置SqlNote的父节点ID + sqlNote.setParentId(parentId.longValue()); + // 提交更改到数据库,true表示立即写入 + sqlNote.commit(true); + + // 更新远程元数据 + updateRemoteMeta(node.getGid(), sqlNote); + } + // 定义一个私有方法,用于添加远程节点,参数包括节点和数据库游标 + private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { + // 如果操作被取消,则直接返回 + if (mCancelled) { + return; + } + + SqlNote sqlNote = new SqlNote(mContext, c); + Node n; + + // 如果是笔记类型,则进行远程更新 + if (sqlNote.isNoteType()) { + Task task = new Task(); + // 设置任务的内容为SqlNote的内容 + task.setContentByLocalJSON(sqlNote.getContent()); + + // 查找父任务的GID + String parentGid = mNidToGid.get(sqlNote.getParentId()); + // 如果找不到父任务的GID,则记录错误并抛出异常 + if (parentGid == null) { + Log.e(TAG, "cannot find task's parent tasklist"); + throw new ActionFailureException("cannot add remote task"); + } + // 将任务添加到父任务列表中 + mGTaskListHashMap.get(parentGid).addChildTask(task); + + // 创建远程任务 + GTaskClient.getInstance().createTask(task); + n = (Node) task; + + // 更新远程元数据 + updateRemoteMeta(task.getGid(), sqlNote); + } else { + TaskList tasklist = null; + + // 根据SqlNote的ID判断文件夹类型,并构建文件夹名称 + 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; + // 如果存在同名文件夹且已经在GTaskHashMap中,则移除 + if (mGTaskHashMap.containsKey(gid)) { + mGTaskHashMap.remove(gid); + } + break; + } + } + + // 如果没有找到同名文件夹,则创建新文件夹 + if (tasklist == null) { + tasklist = new TaskList(); + tasklist.setContentByLocalJSON(sqlNote.getContent()); + GTaskClient.getInstance().createTaskList(tasklist); + mGTaskListHashMap.put(tasklist.getGid(), tasklist); + } + n = (Node) tasklist; + } + + // 更新本地SqlNote的GtaskID + sqlNote.setGtaskId(n.getGid()); + // 提交更改到数据库,false表示延迟写入 + sqlNote.commit(false); + // 重置本地修改标记 + sqlNote.resetLocalModified(); + // 再次提交更改到数据库,true表示立即写入 + sqlNote.commit(true); + + // 更新GID和ID的映射关系 + mGidToNid.put(n.getGid(), sqlNote.getId()); + mNidToGid.put(sqlNote.getId(), n.getGid()); + } + + // 定义一个方法,用于更新远程节点。该方法接收一个节点和一个游标作为参数,并可能抛出网络失败异常。 + private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { + // 如果同步被取消,则直接返回。 + if (mCancelled) { + return; + } + + // 使用上下文和游标创建一个SqlNote对象。 + SqlNote sqlNote = new SqlNote(mContext, c); + + // 更新远程内容:将节点的内容设置为从SqlNote获取的本地JSON内容。 + node.setContentByLocalJSON(sqlNote.getContent()); + // 调用GTaskClient的实例来添加或更新这个节点。 + GTaskClient.getInstance().addUpdateNode(node); + + // 更新节点的元数据。 + updateRemoteMeta(node.getGid(), sqlNote); + + // 如果需要,移动任务。 + if (sqlNote.isNoteType()) { + Task task = (Task) node; + TaskList preParentList = task.getParent(); + + // 获取当前父任务的GID。 + 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); + } + } + + // 清除本地的修改标志,并提交更改。 + sqlNote.resetLocalModified(); + sqlNote.commit(true); + } + + // 定义一个方法,用于更新远程元数据。 + private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { + if (sqlNote != null && sqlNote.isNoteType()) { + MetaData metaData = mMetaHashMap.get(gid); + if (metaData != null) { + // 如果元数据已存在,则更新它。 + metaData.setMeta(gid, sqlNote.getContent()); + GTaskClient.getInstance().addUpdateNode(metaData); + } else { + // 如果元数据不存在,则创建新的元数据并添加到列表中。 + metaData = new MetaData(); + metaData.setMeta(gid, sqlNote.getContent()); + mMetaList.addChildTask(metaData); + mMetaHashMap.put(gid, metaData); + GTaskClient.getInstance().createTask(metaData); + } + } + } + + // 定义一个方法,用于刷新本地的同步ID。 + private void refreshLocalSyncId() throws NetworkFailureException { + if (mCancelled) { + return; + } + + // 清除现有的哈希映射,并初始化任务列表。 + 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) { + // 如果找到了对应的节点,则更新其同步ID。 + 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; + } + } + } + + // 定义一个方法,用于获取同步账户的名称。 + public String getSyncAccount() { + return GTaskClient.getInstance().getSyncAccount().name; + } + + // 定义一个方法,用于取消同步。 + public void cancelSync() { + mCancelled = true; + } \ No newline at end of file diff --git a/GTaskStringUtils.java b/GTaskStringUtils.java new file mode 100644 index 0000000..3f977d8 --- /dev/null +++ b/GTaskStringUtils.java @@ -0,0 +1,123 @@ +/* + * 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. + */ + +// 定义包名,表示这个类属于net.micode.notes.tool包 +package net.micode.notes.tool; + +// 声明一个公共类GTaskStringUtils +public class GTaskStringUtils { + + // 定义与GTasks JSON操作相关的常量 + // action_id,用于标识操作的ID + public final static String GTASK_JSON_ACTION_ID = "action_id"; + // action_list,用于标识操作涉及的任务列表 + public final static String GTASK_JSON_ACTION_LIST = "action_list"; + // action_type,用于标识操作类型 + public final static String GTASK_JSON_ACTION_TYPE = "action_type"; + // create,表示创建操作 + public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; + // get_all,表示获取所有操作 + public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; + // move,表示移动操作 + public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; + // update,表示更新操作 + public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; + + // 定义与GTasks实体相关的常量 + // creator_id,用于标识创建者的ID + public final static String GTASK_JSON_CREATOR_ID = "creator_id"; + // child_entity,用于标识子实体 + public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; + // client_version,用于标识客户端版本 + public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; + // completed,用于标识任务是否完成 + public final static String GTASK_JSON_COMPLETED = "completed"; + // current_list_id,用于标识当前任务所在的列表ID + public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; + // default_list_id,用于标识默认任务列表的ID + public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; + // deleted,用于标识任务是否被删除 + public final static String GTASK_JSON_DELETED = "deleted"; + // dest_list,用于标识目标列表 + public final static String GTASK_JSON_DEST_LIST = "dest_list"; + // dest_parent,用于标识目标父级 + public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; + // dest_parent_type,用于标识目标父级类型 + public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; + // entity_delta,用于标识实体变化 + public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; + // entity_type,用于标识实体类型 + public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; + // get_deleted,用于标识是否获取已删除的任务 + public final static String GTASK_JSON_GET_DELETED = "get_deleted"; + // id,用于标识实体的ID + public final static String GTASK_JSON_ID = "id"; + // index,用于标识索引 + public final static String GTASK_JSON_INDEX = "index"; + // last_modified,用于标识最后一次修改时间 + public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; + // latest_sync_point,用于标识最新的同步点 + public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; + // list_id,用于标识列表ID + public final static String GTASK_JSON_LIST_ID = "list_id"; + // lists,用于标识列表集合 + public final static String GTASK_JSON_LISTS = "lists"; + // name,用于标识名称 + public final static String GTASK_JSON_NAME = "name"; + // new_id,用于标识新ID + public final static String GTASK_JSON_NEW_ID = "new_id"; + // notes,用于标识笔记 + public final static String GTASK_JSON_NOTES = "notes"; + // parent_id,用于标识父级ID + public final static String GTASK_JSON_PARENT_ID = "parent_id"; + // prior_sibling_id,用于标识前一个同级ID + public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; + // results,用于标识结果集合 + public final static String GTASK_JSON_RESULTS = "results"; + // source_list,用于标识源列表 + public final static String GTASK_JSON_SOURCE_LIST = "source_list"; + // tasks,用于标识任务集合 + public final static String GTASK_JSON_TASKS = "tasks"; + // type,用于标识类型 + public final static String GTASK_JSON_TYPE = "type"; + // GROUP,表示组类型 + public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; + // TASK,表示任务类型 + public final static String GTASK_JSON_TYPE_TASK = "TASK"; + // user,用于标识用户 + public final static String GTASK_JSON_USER = "user"; + + // 定义与文件夹相关的常量 + // [MIUI_Notes],表示MIUI笔记文件夹的前缀 + public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; + // Default,表示默认文件夹名 + public final static String FOLDER_DEFAULT = "Default"; + // Call_Note,表示通话记录文件夹名 + public final static String FOLDER_CALL_NOTE = "Call_Note"; + // METADATA,表示元数据文件夹名 + public final static String FOLDER_META = "METADATA"; + + // 定义与元数据相关的常量 + // meta_gid,用于标识元数据中的GTasks ID + public final static String META_HEAD_GTASK_ID = "meta_gid"; + // meta_note,用于标识元数据中的笔记 + public final static String META_HEAD_NOTE = "meta_note"; + // meta_data,用于标识元数据中的数据 + public final static String META_HEAD_DATA = "meta_data"; + + // [META INFO] DON'T UPDATE AND DELETE,表示元数据笔记的名称,提示用户不要更新和删除 + public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; +} diff --git a/GTaskSyncService.java b/GTaskSyncService.java new file mode 100644 index 0000000..31dbf63 --- /dev/null +++ b/GTaskSyncService.java @@ -0,0 +1,145 @@ +/* + * 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; + +// 导入必要的Android类 +import android.app.Activity; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.IBinder; + +// 定义一个继承自Service的类,用于同步任务 +public class GTaskSyncService extends Service { + // 定义同步动作名称的常量 + 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; // 无效动作 + + // 定义广播名称的常量 + 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; // 任务完成后,将任务对象置为null + sendBroadcast(""); // 发送广播,通知同步完成 + stopSelf(); // 停止服务 + } + }); + sendBroadcast(""); // 发送广播,通知开始同步(这里可能需要发送具体信息) + mSyncTask.execute(); // 执行异步任务 + } + } + + // 取消同步的私有方法 + private void cancelSync() { + if (mSyncTask != null) { // 如果当前有正在执行的同步任务 + mSyncTask.cancelSync(); // 取消任务 + } + } + + // 当服务被创建时调用 + @Override + public void onCreate() { + mSyncTask = null; // 初始化同步任务对象为null + } + + // 当服务被命令启动时调用 + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + Bundle bundle = intent.getExtras(); // 获取Intent中的附加数据 + if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { // 如果附加数据不为空且包含动作名称 + switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { // 根据动作名称执行相应操作 + case ACTION_START_SYNC: + startSync(); // 开始同步 + break; + case ACTION_CANCEL_SYNC: + cancelSync(); // 取消同步 + break; + default: + break; + } + return START_STICKY; // 如果服务被杀死,系统会重新创建服务并调用onStartCommand方法 + } + return super.onStartCommand(intent, flags, startId); // 如果没有指定动作,则调用父类方法 + } + + // 当设备内存不足时调用 + @Override + public void onLowMemory() { + if (mSyncTask != null) { // 如果当前有正在执行的同步任务 + mSyncTask.cancelSync(); // 取消任务以释放内存 + } + } + + // 返回null,因为此服务不绑定客户端 + public IBinder onBind(Intent intent) { + return null; + } + + // 发送广播的方法,用于通知同步进度等信息 + public void sendBroadcast(String msg) { + mSyncProgress = msg; // 更新同步进度信息 + Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); // 创建广播Intent + intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); // 是否正在同步 + intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); // 同步进度信息 + sendBroadcast(intent); // 发送广播 + } + + // 提供一个静态方法,用于从Activity启动同步服务 + public static void startSync(Activity activity) { + GTaskManager.getInstance().setActivityContext(activity); // 设置GTaskManager的Activity上下文 + Intent intent = new Intent(activity, GTaskSyncService.class); // 创建Intent + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); // 添加动作类型 + activity.startService(intent); // 启动服务 + } + + // 提供一个静态方法,用于从Context取消同步服务 + public static void cancelSync(Context context) { + Intent intent = new Intent(context, GTaskSyncService.class); // 创建Intent + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); // 添加动作类型 + context.startService(intent); // 启动服务以取消同步 + } + + // 提供一个静态方法,用于检查是否正在同步 + public static boolean isSyncing() { + return mSyncTask != null; // 返回mSyncTask是否为null + } + + // 提供一个静态方法,用于获取同步进度信息 + public static String getProgressString() { + return mSyncProgress; // 返回mSyncProgress的值 + } +} \ No newline at end of file diff --git a/Note.java b/Note.java new file mode 100644 index 0000000..80f1331 --- /dev/null +++ b/Note.java @@ -0,0 +1,313 @@ +/* + * 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; + +// 导入所需的Android和内容提供者操作的类 +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; + +// 导入Java的ArrayList类 +import java.util.ArrayList; + +// 声明Note类 +public class Note { + // 用于存储笔记差异值的ContentValues对象 + private ContentValues mNoteDiffValues; + // 用于存储笔记数据的NoteData对象 + private NoteData mNoteData; + // 用于日志记录的标签 + private static final String TAG = "Note"; + + /** + * 创建一个新的笔记ID,用于向数据库添加新笔记 + */ + public static synchronized long getNewNoteId(Context context, long folderId) { + // 创建一个新的ContentValues对象,用于存储要插入数据库的数据 + 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 { + // 从返回的Uri中提取笔记ID + noteId = Long.valueOf(uri.getPathSegments().get(1)); + } catch (NumberFormatException e) { + // 如果提取ID时发生异常,则记录错误日志,并将noteId设置为0 + Log.e(TAG, "Get note id error :" + e.toString()); + noteId = 0; + } + // 如果noteId为-1,则抛出异常 + if (noteId == -1) { + throw new IllegalStateException("Wrong note id:" + noteId); + } + return noteId; // 返回新创建的笔记ID + } + + // Note类的构造函数 + 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); // 调用NoteData对象的方法设置文本数据ID + } + + // 获取文本数据的ID + public long getTextDataId() { + return mNoteData.mTextDataId; // 返回NoteData对象中的文本数据ID + } + + // 设置通话数据的ID + public void setCallDataId(long id) { + mNoteData.setCallDataId(id); // 调用NoteData对象的方法设置通话数据ID + } + + // 设置通话数据的某个键值对 + public void setCallData(String key, String value) { + mNoteData.setCallData(key, value); // 调用NoteData对象的方法设置通话数据 + } + + // 判断笔记是否已本地修改 + public boolean isLocalModified() { + return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); // 判断差异值对象或NoteData对象是否标记为已修改 + } + + // 同步笔记到数据库 + public boolean syncNote(Context context, long noteId) { + if (noteId <= 0) { + throw new IllegalArgumentException("Wrong note id:" + noteId); // 如果笔记ID非法,则抛出异常 + } + + if (!isLocalModified()) { + return true; // 如果笔记未修改,则直接返回true + } + + /** + * 理论上,一旦数据改变,就应该更新笔记的LOCAL_MODIFIED和MODIFIED_DATE字段。 + * 为了数据安全,即使更新笔记失败,也要更新笔记数据信息。 + */ + if (context.getContentResolver().update( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, + null) == 0) { + Log.e(TAG, "Update note error, should not happen"); // 如果更新失败,则记录错误日志 + // 不返回,继续执行后续代码 + } + mNoteDiffValues.clear(); // 清空差异值对象 + + // 如果NoteData对象标记为已修改,并且推送到内容提供者失败,则返回false + if (mNoteData.isLocalModified() + && (mNoteData.pushIntoContentResolver(context, noteId) == null)) { + return false; + } + + return true; // 同步成功,返回true + } + + // 定义一个私有的内部类NoteData,用于管理笔记数据的存储和操作 + private class NoteData { + // 文本数据的ID + private long mTextDataId; + + // 用于存储文本数据的ContentValues对象 + private ContentValues mTextDataValues; + + // 通话数据的ID + private long mCallDataId; + + // 用于存储通话数据的ContentValues对象 + private ContentValues mCallDataValues; + + // 用于日志输出的标签 + private static final String TAG = "NoteData"; + + // NoteData类的构造函数,初始化数据 + public NoteData() { + // 初始化文本数据和通话数据的ContentValues对象 + mTextDataValues = new ContentValues(); + mCallDataValues = new ContentValues(); + // 初始化数据ID为0,表示未设置 + mTextDataId = 0; + mCallDataId = 0; + } + + // 判断是否有本地数据被修改 + boolean isLocalModified() { + // 如果文本数据或通话数据的ContentValues对象不为空,则表示有数据被修改 + return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; + } + + // 设置文本数据的ID + void setTextDataId(long id) { + // 如果传入的ID小于等于0,则抛出异常 + if(id <= 0) { + throw new IllegalArgumentException("Text data id should larger than 0"); + } + // 设置文本数据的ID + mTextDataId = id; + } + + // 设置通话数据的ID + void setCallDataId(long id) { + // 如果传入的ID小于等于0,则抛出异常 + if (id <= 0) { + throw new IllegalArgumentException("Call data id should larger than 0"); + } + // 设置通话数据的ID + mCallDataId = id; + } + + // 设置通话数据,并标记为已修改 + void setCallData(String key, String value) { + // 将数据存入mCallDataValues + mCallDataValues.put(key, value); + // 标记为已修改(注意:这里mNoteDiffValues没有在类中定义,可能是个错误或者遗漏) + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + // 更新修改日期 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + } + + // 设置文本数据,并标记为已修改 + void setTextData(String key, String value) { + // 将数据存入mTextDataValues + mTextDataValues.put(key, value); + // 标记为已修改(注意:同样mNoteDiffValues没有在类中定义) + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + // 更新修改日期 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + } + + // 将数据推送到ContentResolver中 + Uri pushIntoContentResolver(Context context, long noteId) { + // 检查noteId的有效性 + if (noteId <= 0) { + throw new IllegalArgumentException("Wrong note id:" + noteId); + } + + // 创建一个操作列表,用于批量操作 + ArrayList operationList = new ArrayList(); + ContentProviderOperation.Builder builder = null; + + // 处理文本数据 + if(mTextDataValues.size() > 0) { + // 添加noteId到文本数据中 + 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 { + // 设置新插入的数据的ID + 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); + // 返回操作结果的URI,如果结果为空则返回null + return (results == null || results.length == 0 || results[0] == null) ? null + : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); + } catch (RemoteException e) { + // 记录远程异常并返回null + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + return null; + } catch (OperationApplicationException e) { + // 记录操作应用异常并返回null + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + return null; + } + } + // 如果没有操作,则返回null + return null; + } + } \ No newline at end of file diff --git a/NoteWidgetProvider.java b/NoteWidgetProvider.java new file mode 100644 index 0000000..ec6f819 --- /dev/null +++ b/NoteWidgetProvider.java @@ -0,0 +1,132 @@ +/* + * 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; + +public abstract class NoteWidgetProvider extends AppWidgetProvider { + public static final String [] PROJECTION = new String [] { + NoteColumns.ID, + NoteColumns.BG_COLOR_ID, + NoteColumns.SNIPPET + }; + + public static final int COLUMN_ID = 0; + public static final int COLUMN_BG_COLOR_ID = 1; + public static final int COLUMN_SNIPPET = 2; + + private static final String TAG = "NoteWidgetProvider"; + + @Override + public void onDeleted(Context context, int[] appWidgetIds) { + ContentValues values = new ContentValues(); + 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])}); + } + } + + 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); + } + + protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + update(context, appWidgetManager, appWidgetIds, false); + } + + private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, + boolean privacyMode) { + for (int i = 0; i < appWidgetIds.length; i++) { + if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { + int bgId = ResourceParser.getDefaultBgId(context); + 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); + } + } + } + + protected abstract int getBgResourceId(int bgId); + + protected abstract int getLayoutId(); + + protected abstract int getWidgetType(); +} diff --git a/NoteWidgetProvider_2x.java b/NoteWidgetProvider_2x.java new file mode 100644 index 0000000..adcb2f7 --- /dev/null +++ b/NoteWidgetProvider_2x.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.ResourceParser; + + +public class NoteWidgetProvider_2x extends NoteWidgetProvider { + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + } + + @Override + protected int getLayoutId() { + return R.layout.widget_2x; + } + + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); + } + + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_2X; + } +} diff --git a/NoteWidgetProvider_4x.java b/NoteWidgetProvider_4x.java new file mode 100644 index 0000000..c12a02e --- /dev/null +++ b/NoteWidgetProvider_4x.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.ResourceParser; + + +public class NoteWidgetProvider_4x extends NoteWidgetProvider { + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + } + + protected int getLayoutId() { + return R.layout.widget_4x; + } + + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); + } + + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_4X; + } +} diff --git a/ResourceParser.java b/ResourceParser.java new file mode 100644 index 0000000..2ce7003 --- /dev/null +++ b/ResourceParser.java @@ -0,0 +1,213 @@ +/* + * 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; + +// 导入Android框架中的Context类和PreferenceManager类 +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 + }; + + // 根据颜色ID获取对应的编辑界面背景资源 + public static int getNoteBgResource(int id) { + return BG_EDIT_RESOURCES[id]; + } + + // 根据颜色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)) { + // 如果设置了,则随机返回一个颜色ID + return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length); + } else { + // 否则返回默认颜色ID + 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获取对应的列表第一项背景资源 + public static int getNoteBgFirstRes(int id) { + return BG_FIRST_RESOURCES[id]; + } + + // 根据颜色ID获取对应的列表最后一项背景资源 + public static int getNoteBgLastRes(int id) { + return BG_LAST_RESOURCES[id]; + } + + // 根据颜色ID获取对应的列表单项背景资源 + public static int getNoteBgSingleRes(int id) { + return BG_SINGLE_RESOURCES[id]; + } + + // 根据颜色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 { + // 定义不同颜色背景的小部件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, + }; + + // 根据颜色ID获取对应的小部件2x大小背景资源 + 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 + }; + + // 根据颜色ID获取对应的小部件4x大小背景资源 + 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 + public static int getTexAppearanceResource(int id) { + if (id >= TEXTAPPEARANCE_RESOURCES.length) { + return BG_DEFAULT_FONT_SIZE; + } + return TEXTAPPEARANCE_RESOURCES[id]; + } + + // 获取文本外观资源数组的大小 + public static int getResourcesSize() { + return TEXTAPPEARANCE_RESOURCES.length; + } + } +} diff --git a/WorkingNote.java b/WorkingNote.java new file mode 100644 index 0000000..fae4644 --- /dev/null +++ b/WorkingNote.java @@ -0,0 +1,361 @@ +/* + * 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; // 导入Android的小部件管理器类 + +// 定义一个名为WorkingNote的公共类 +public class WorkingNote { + // 定义一个Note类型的私有成员变量mNote,用于存储笔记信息 + private Note mNote; + // 定义一个长整型私有成员变量mNoteId,用于存储笔记的ID + private long mNoteId; + // 定义一个字符串类型的私有成员变量mContent,用于存储笔记的内容 + private String mContent; + // 定义一个整型私有成员变量mMode,用于存储笔记的模式 + private int mMode; + + // 定义一个长整型私有成员变量mAlertDate,用于存储笔记的提醒日期 + private long mAlertDate; + + // 定义一个长整型私有成员变量mModifiedDate,用于存储笔记的最后修改日期 + private long mModifiedDate; + + // 定义一个整型私有成员变量mBgColorId,用于存储笔记的背景颜色ID + private int mBgColorId; + + // 定义一个整型私有成员变量mWidgetId,用于存储笔记关联的小部件ID + private int mWidgetId; + + // 定义一个整型私有成员变量mWidgetType,用于存储笔记关联的小部件类型 + private int mWidgetType; + + // 定义一个长整型私有成员变量mFolderId,用于存储笔记所属的文件夹ID + private long mFolderId; + + // 定义一个Context类型的私有成员变量mContext,用于获取应用程序的上下文 + private Context mContext; + + // 定义一个静态的字符串常量TAG,用于日志输出 + private static final String TAG = "WorkingNote"; + + // 定义一个布尔型的私有成员变量mIsDeleted,用于标记笔记是否被删除 + private boolean mIsDeleted; + + // 定义一个NoteSettingChangedListener类型的私有成员变量mNoteSettingStatusListener,用于监听笔记设置变化 + private NoteSettingChangedListener mNoteSettingStatusListener; + + // 定义一个静态的字符串数组DATA_PROJECTION,用于指定查询数据库时返回的列 + public static final String[] DATA_PROJECTION = new String[] { + DataColumns.ID, + DataColumns.CONTENT, + DataColumns.MIME_TYPE, + DataColumns.DATA1, + DataColumns.DATA2, + DataColumns.DATA3, + DataColumns.DATA4, + }; + + // 定义一个静态的字符串数组NOTE_PROJECTION,用于指定查询笔记数据库时返回的列 + 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() { + // 使用ContentResolver查询数据库,获取指定ID的笔记信息 + 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(); // 关闭Cursor + } 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); + // 设置笔记的ID + mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); + } + // 如果是电话笔记类型 + else if (DataConstants.CALL_NOTE.equals(type)) { + // 设置电话笔记的ID + mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); + } else { + // 如果类型不匹配,记录日志 + Log.d(TAG, "Wrong note type with type:" + type); + } + } while (cursor.moveToNext()); // 继续移动到下一行,直到遍历完所有结果 + } + // 关闭游标 + cursor.close(); + } else { + // 如果查询结果为空,记录错误日志并抛出异常 + Log.e(TAG, "No data with id:" + mNoteId); + throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); + } + } + + // 定义一个静态方法,用于创建一个空的笔记对象 + public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, + int widgetType, int defaultBgColorId) { + // 初始化笔记对象并设置属性 + WorkingNote note = new WorkingNote(context, folderId); + note.setBgColorId(defaultBgColorId); + note.setWidgetId(widgetId); + note.setWidgetType(widgetType); + return note; + } + + // 定义一个静态方法,用于根据ID加载笔记对象 + public static WorkingNote load(Context context, long id) { + return new WorkingNote(context, id, 0); + } + + // 定义一个同步方法,用于保存笔记 + public synchronized boolean saveNote() { + // 检查笔记是否值得保存 + if (isWorthSaving()) { + // 如果笔记在数据库中不存在 + if (!existInDatabase()) { + // 获取一个新的笔记ID + if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { + // 如果获取ID失败,记录错误日志并返回false + 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() { + // 如果笔记被标记为删除,或者不存在于数据库中且内容为空,或者存在于数据库中但未被本地修改,则不值得保存 + if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) + || (existInDatabase() && !mNote.isLocalModified())) { + return false; + } else { + return true; + } + } + + // 设置笔记设置状态改变的监听器 + public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { + mNoteSettingStatusListener = l; + } + + // 设置提醒日期 + public void setAlertDate(long date, boolean set) { + // 如果设置的日期与当前日期不同,更新日期并通知监听器 + if (date != mAlertDate) { + mAlertDate = date; + mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); + } + // 如果设置了监听器,通知监听器提醒日期已更改 + if (mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onClockAlertChanged(date, set); + } + } + + // 标记笔记为已删除或未删除 + public void markDeleted(boolean mark) { + mIsDeleted = mark; + // 如果笔记关联了小部件,并且小部件有效,通知小部件内容已更改 + if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onWidgetChanged(); + } + } + + // 设置笔记背景颜色ID + public void setBgColorId(int id) { + // 如果设置的ID与当前ID不同,更新ID并通知监听器 + if (id != mBgColorId) { + mBgColorId = id; + if (mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onBackgroundColorChanged(); + } + mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); + } + } + + // 设置检查列表模式 + public void setCheckListMode(int mode) { + // 如果设置的模式与当前模式不同,更新模式并通知监听器 + if (mMode != mode) { + if (mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); + } + mMode = mode; + mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); + } + } + + // 设置小部件类型 + public void setWidgetType(int type) { + // 如果设置的小部件类型与当前类型不同,更新类型 + if (type != mWidgetType) { + mWidgetType = type; + mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); + } + } + + // 设置小部件ID + public void setWidgetId(int id) { + // 如果设置的小部件ID与当前ID不同,更新ID + if (id != mWidgetId) { + mWidgetId = id; + mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); + } + } + + // 设置笔记内容 + public void setWorkingText(String text) { + // 如果设置的内容与当前内容不同,更新内容 + if (!TextUtils.equals(mContent, text)) { + mContent = text; + mNote.setTextData(DataColumns.CONTENT, mContent); + } + } + + // 将笔记转换为电话笔记 + public void convertToCallNote(String phoneNumber, long callDate) { + // 设置电话笔记的日期和电话号码 + mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); + mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); + // 设置电话笔记所属的文件夹ID为电话记录文件夹 + mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); + } + + // 检查笔记是否有提醒日期 + public boolean hasClockAlert() { + return (mAlertDate > 0 ? true : false); + } + + // 获取笔记内容 + public String getContent() { + return mContent; + } + + // 获取笔记的提醒日期 + public long getAlertDate() { + return mAlertDate; + } + + // 获取笔记的最后修改日期 + public long getModifiedDate() { + return mModifiedDate; + } + + // 获取笔记背景颜色的资源ID + public int getBgColorResId() { + return NoteBgResources.getNoteBgResource(mBgColorId); + } + + // 获取笔记背景颜色的ID + public int getBgColorId