diff --git a/src/tool/BackupUtils.java b/src/tool/BackupUtils.java new file mode 100644 index 0000000..0f0a7d1 --- /dev/null +++ b/src/tool/BackupUtils.java @@ -0,0 +1,420 @@ +/* + * 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"; // 日志标签,用于在日志输出中标识该类的相关信息 + // Singleton stuff + 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; + + + private BackupUtils(Context context) { + mTextExport = new TextExport(context); + } + /** + * 检查外部存储(SD卡)是否可用 + * + * @return 如果SD卡已挂载,则返回true;否则返回false + */ + private static boolean externalStorageAvailable() { + return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); + } +/** + * 调用TextExport实例的exportToText方法,将笔记数据导出为文本文件 + * + * @return 导出操作的状态码,如STATE_SUCCESS、STATE_SD_CARD_UNMOUONTED等 + */ + 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, // 笔记的ID + NoteColumns.MODIFIED_DATE, // 笔记的修改日期 + NoteColumns.SNIPPET, // 笔记的摘要 + NoteColumns.TYPE // 笔记的类型 + }; + + + // 笔记ID列在查询结果中的索引 + 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, // 数据的MIME类型 + DataColumns.DATA1, + DataColumns.DATA2, + DataColumns.DATA3, + DataColumns.DATA4 + }; + + // 数据内容列在查询结果中的索引 + private static final int DATA_COLUMN_CONTENT = 0; + // 数据MIME类型列在查询结果中的索引 + 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 = ""; + } +/** + * 根据索引获取文本格式字符串 + * + * @param id 文本格式在数组中的索引 + * @return 对应的文本格式字符串 + */ + 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); + + f (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)))); + // 获取笔记的ID + String noteId = notesCursor.getString(NOTE_COLUMN_ID); + // 导出该笔记的详细内容 + exportNoteToText(noteId, ps); + } while (notesCursor.moveToNext()); + } + // 关闭游标,释放资源 + notesCursor.close(); + } + + /** + * 将指定ID的笔记详细内容导出到文本文件 + */ + 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 { + // 获取数据的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() { + // 检查SD卡是否可用 + 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)); + } + // 获取文件夹ID + 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)))); + // 获取笔记的ID + String noteId = noteCursor.getString(NOTE_COLUMN_ID); + // 导出该笔记的详细内容 + exportNoteToText(noteId, ps); + } while (noteCursor.moveToNext()); + } + // 关闭游标,释放资源 + noteCursor.close(); + } + // 关闭打印流 + ps.close(); + + return STATE_SUCCESS; + } + + /** + * 获取用于导出文本文件的打印流 + * + * @return 打印流实例,如果创建失败则返回null + */ + private PrintStream getExportToTextPrintStream() { + // 生成用于存储导出数据的文件 + File file = generateFileMountedOnSDcard(mContext, R.string.file_path, + R.string.file_name_txt_format); + if (file == null) { + Log.e(TAG, "create file to exported failed"); + return null; + } + // 记录文件名 + mFileName = file.getName(); + // 记录文件目录 + mFileDirectory = mContext.getString(R.string.file_path); + PrintStream ps = null; + try { + // 创建文件输出流 + FileOutputStream fos = new FileOutputStream(file); + // 创建打印流 + ps = new PrintStream(fos); + } catch (FileNotFoundException e) { + // 处理文件未找到异常 + e.printStackTrace(); + return null; + } catch (NullPointerException e) { + // 处理空指针异常 + e.printStackTrace(); + return null; + } + return ps; + } + } + + + /** + * 生成用于存储导出数据的文件 + * + * @param context 应用上下文,用于获取资源 + * @param filePathResId 文件路径的资源ID + * @param fileNameFormatResId 文件名格式的资源ID + * @return 生成的文件实例,如果创建失败则返回null + */ + private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { + StringBuilder sb = new StringBuilder(); + // 添加外部存储目录 + sb.append(Environment.getExternalStorageDirectory()); + // 添加文件路径 + sb.append(context.getString(filePathResId)); + File filedir = new File(sb.toString()); + // 添加文件名 + sb.append(context.getString( + fileNameFormatResId, + DateFormat.format(context.getString(R.string.format_date_ymd), + System.currentTimeMillis()))); + File file = new File(sb.toString()); + + try { + if (!filedir.exists()) { + // 如果目录不存在,则创建目录 + filedir.mkdir(); + } + if (!file.exists()) { + // 如果文件不存在,则创建文件 + file.createNewFile(); + } + return file; + } catch (SecurityException e) { + // 处理安全异常 + e.printStackTrace(); + } catch (IOException e) { + // 处理IO异常 + e.printStackTrace(); + } + + return null; + } +} + + diff --git a/src/tool/DataUtils.java b/src/tool/DataUtils.java new file mode 100644 index 0000000..6305e97 --- /dev/null +++ b/src/tool/DataUtils.java @@ -0,0 +1,450 @@ +/* + * 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"; + + /** + * 批量删除指定ID集合中的笔记 + * + * @param resolver 内容解析器,用于与内容提供者交互 + * @param ids 要删除的笔记ID集合 + * @return 删除操作是否成功,若集合为空或操作成功返回true,失败返回false + */ + public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { + // 若传入的ID集合为null,打印日志并返回true + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + } + // 若ID集合为空,打印日志并返回true + if (ids.size() == 0) { + Log.d(TAG, "no id is in the hashset"); + return true; + } + + // 用于存储批量操作的列表 + ArrayList operationList = new ArrayList<>(); + // 遍历ID集合 + for (long id : ids) { + // 若ID为根文件夹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); + // 若操作结果为空或长度为0或第一个结果为空,打印日志并返回false + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + return false; + } + return true; + } catch (RemoteException e) { + // 处理远程异常,打印错误日志 + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } catch (OperationApplicationException e) { + // 处理操作应用异常,打印错误日志 + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } + return false; + } + + /** + * 将指定ID的笔记移动到目标文件夹 + * + * @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(); + // 设置笔记的父文件夹ID为目标文件夹ID + values.put(NoteColumns.PARENT_ID, desFolderId); + // 设置笔记的原始父文件夹ID为源文件夹ID + values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); + // 标记笔记为本地修改 + values.put(NoteColumns.LOCAL_MODIFIED, 1); + // 执行更新操作 + resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); + } + + /** + * 批量将指定ID集合中的笔记移动到目标文件夹 + * + * @param resolver 内容解析器 + * @param ids 要移动的笔记ID集合 + * @param folderId 目标文件夹ID + * @return 移动操作是否成功 + */ + public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, long folderId) { + // 若传入的ID集合为null,打印日志并返回true + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + } + + // 用于存储批量操作的列表 + ArrayList operationList = new ArrayList<>(); + // 遍历ID集合 + for (long id : ids) { + // 创建一个更新操作的构建器 + ContentProviderOperation.Builder builder = ContentProviderOperation + .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + // 设置笔记的父文件夹ID为目标文件夹ID + builder.withValue(NoteColumns.PARENT_ID, folderId); + // 标记笔记为本地修改 + builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); + // 将构建好的操作添加到操作列表中 + operationList.add(builder.build()); + } + + try { + // 批量执行操作 + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + // 若操作结果为空或长度为0或第一个结果为空,打印日志并返回false + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + return false; + } + return true; + } catch (RemoteException e) { + // 处理远程异常,打印错误日志 + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } catch (OperationApplicationException e) { + // 处理操作应用异常,打印错误日志 + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } + return false; + } + + /** + * 获取用户创建的文件夹数量(排除系统文件夹) + * + * @param resolver 内容解析器 + * @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; + } + + /** + * 检查指定笔记是否在数据库中可见 + * + * @param resolver 内容解析器 + * @param noteId 笔记ID + * @param type 笔记类型 + * @return 笔记是否可见 + */ + 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; + } + + /** + * 检查指定笔记是否存在于数据库中 + * + * @param resolver 内容解析器 + * @param noteId 笔记ID + * @return 笔记是否存在 + */ + 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; + } + + /** + * 检查指定数据是否存在于数据库中 + * + * @param resolver 内容解析器 + * @param dataId 数据ID + * @return 数据是否存在 + */ + public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { + // 查询指定数据是否存在 + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), + null, null, null, null); + + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + } + // 关闭游标 + cursor.close(); + } + return exist; + } + + /** + * 检查指定名称的可见文件夹是否存在于数据库中 + * + * @param resolver 内容解析器 + * @param name 文件夹名称 + * @return 文件夹是否存在 + */ + 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; + } + + /** + * 获取指定文件夹下的笔记小部件属性集合 + * + * @param resolver 内容解析器 + * @param folderId 文件夹ID + * @return 笔记小部件属性集合 + */ + 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(); + // 设置小部件ID + widget.widgetId = c.getInt(0); + // 设置小部件类型 + widget.widgetType = c.getInt(1); + // 将小部件属性添加到集合中 + set.add(widget); + } catch (IndexOutOfBoundsException e) { + // 处理索引越界异常,打印错误日志 + Log.e(TAG, e.toString()); + } + } while (c.moveToNext()); + } + // 关闭游标 + c.close(); + } + return set; + } + + /** + * 根据笔记ID获取通话号码 + * + * @param resolver 内容解析器 + * @param noteId 笔记ID + * @return 通话号码,如果未找到则返回空字符串 + */ + public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { + // 查询指定笔记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()) { + try { + // 获取通话号码 + return cursor.getString(0); + } catch (IndexOutOfBoundsException e) { + // 处理索引越界异常,打印错误日志 + Log.e(TAG, "Get call number fails " + e.toString()); + } finally { + // 关闭游标 + cursor.close(); + } + } + return ""; + } + + /** + * 根据电话号码和通话日期获取笔记ID + * + * @param resolver 内容解析器 + * @param phoneNumber 电话号码 + * @param callDate 通话日期 + * @return 笔记ID,如果未找到则返回0 + */ + public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { + // 查询指定电话号码和通话日期对应的笔记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()) { + try { + // 获取笔记ID + return cursor.getLong(0); + } catch (IndexOutOfBoundsException e) { + // 处理索引越界异常,打印错误日志 + Log.e(TAG, "Get call note id fails " + e.toString()); + } + } + // 关闭游标 + cursor.close(); + } + return 0; + } + + /** + * 根据笔记ID获取笔记摘要 + * + * @param resolver 内容解析器 + * @param noteId 笔记ID + * @return 笔记摘要,如果未找到则抛出异常 + */ + public static String getSnippetById(ContentResolver resolver, long noteId) { + // 查询指定笔记ID对应的摘要 + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, + new String[]{NoteColumns.SNIPPET}, + NoteColumns.ID + "=?", + new String[]{String.valueOf(noteId)}, + null); + + if (cursor != null) { + String snippet = ""; + if (cursor.moveToFirst()) { + // 获取笔记摘要 + snippet = cursor.getString(0); + } + // 关闭游标 + cursor.close(); + return snippet; + } + // 若未找到笔记,抛出异常 + throw new IllegalArgumentException("Note is not found with id: " + noteId); + } + + /** + * 格式化笔记摘要,去除首尾空格并截取第一行 + * + * @param snippet 原始笔记摘要 + * @return 格式化后的笔记摘要 + */ + public static String getFormattedSnippet(String snippet) { + if (snippet != null) { + // 去除首尾空格 + snippet = snippet.trim(); + // 查找换行符位置 + int index = snippet.indexOf('\n'); + if (index != -1) { + // 截取第一行 + snippet = snippet.substring(0, index); + } + } + return snippet; + } +} \ No newline at end of file diff --git a/src/tool/GTaskStringUtils.java b/src/tool/GTaskStringUtils.java new file mode 100644 index 0000000..9195ae2 --- /dev/null +++ b/src/tool/GTaskStringUtils.java @@ -0,0 +1,163 @@ +/* + * 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; + +/** + * 该类定义了一系列与 Google 任务(GTask)相关的 JSON 键名常量, + * 同时包含一些特定文件夹名称、元数据头部信息等常量, + * 用于在应用中处理 GTask 数据时保持键名的一致性和可维护性。 + */ +public class GTaskStringUtils { + + // 表示操作 ID 的 JSON 键名 + public final static String GTASK_JSON_ACTION_ID = "action_id"; + + // 表示操作列表的 JSON 键名 + public final static String GTASK_JSON_ACTION_LIST = "action_list"; + + // 表示操作类型的 JSON 键名 + public final static String GTASK_JSON_ACTION_TYPE = "action_type"; + + // 表示创建操作类型的 JSON 值 + public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; + + // 表示获取所有数据操作类型的 JSON 值 + public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; + + // 表示移动操作类型的 JSON 值 + public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; + + // 表示更新操作类型的 JSON 值 + public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; + + // 表示创建者 ID 的 JSON 键名 + public final static String GTASK_JSON_CREATOR_ID = "creator_id"; + + // 表示子实体的 JSON 键名 + public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; + + // 表示客户端版本的 JSON 键名 + public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; + + // 表示任务是否完成的 JSON 键名 + public final static String GTASK_JSON_COMPLETED = "completed"; + + // 表示当前列表 ID 的 JSON 键名 + public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; + + // 表示默认列表 ID 的 JSON 键名 + public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; + + // 表示任务是否已删除的 JSON 键名 + public final static String GTASK_JSON_DELETED = "deleted"; + + // 表示目标列表的 JSON 键名 + public final static String GTASK_JSON_DEST_LIST = "dest_list"; + + // 表示目标父级的 JSON 键名 + public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; + + // 表示目标父级类型的 JSON 键名 + public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; + + // 表示实体增量的 JSON 键名 + public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; + + // 表示实体类型的 JSON 键名 + public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; + + // 表示获取已删除数据的 JSON 键名 + public final static String GTASK_JSON_GET_DELETED = "get_deleted"; + + // 表示 ID 的 JSON 键名 + public final static String GTASK_JSON_ID = "id"; + + // 表示索引的 JSON 键名 + public final static String GTASK_JSON_INDEX = "index"; + + // 表示最后修改时间的 JSON 键名 + public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; + + // 表示最新同步点的 JSON 键名 + public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; + + // 表示列表 ID 的 JSON 键名 + public final static String GTASK_JSON_LIST_ID = "list_id"; + + // 表示列表集合的 JSON 键名 + public final static String GTASK_JSON_LISTS = "lists"; + + // 表示名称的 JSON 键名 + public final static String GTASK_JSON_NAME = "name"; + + // 表示新 ID 的 JSON 键名 + public final static String GTASK_JSON_NEW_ID = "new_id"; + + // 表示备注的 JSON 键名 + public final static String GTASK_JSON_NOTES = "notes"; + + // 表示父级 ID 的 JSON 键名 + public final static String GTASK_JSON_PARENT_ID = "parent_id"; + + // 表示前一个兄弟节点 ID 的 JSON 键名 + public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; + + // 表示操作结果的 JSON 键名 + public final static String GTASK_JSON_RESULTS = "results"; + + // 表示源列表的 JSON 键名 + public final static String GTASK_JSON_SOURCE_LIST = "source_list"; + + // 表示任务集合的 JSON 键名 + public final static String GTASK_JSON_TASKS = "tasks"; + + // 表示类型的 JSON 键名 + public final static String GTASK_JSON_TYPE = "type"; + + // 表示组类型的 JSON 值 + public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; + + // 表示任务类型的 JSON 值 + public final static String GTASK_JSON_TYPE_TASK = "TASK"; + + // 表示用户的 JSON 键名 + public final static String GTASK_JSON_USER = "user"; + + // MIUI 笔记文件夹的前缀 + public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; + + // 默认文件夹的名称 + public final static String FOLDER_DEFAULT = "Default"; + + // 通话记录笔记文件夹的名称 + public final static String FOLDER_CALL_NOTE = "Call_Note"; + + // 元数据文件夹的名称 + public final static String FOLDER_META = "METADATA"; + + // 元数据头部中 Google 任务 ID 的键名 + public final static String META_HEAD_GTASK_ID = "meta_gid"; + + // 元数据头部中笔记的键名 + public final static String META_HEAD_NOTE = "meta_note"; + + // 元数据头部中数据的键名 + public final static String META_HEAD_DATA = "meta_data"; + + // 元数据笔记的名称,提示不要更新和删除 + public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; +} \ No newline at end of file diff --git a/src/tool/ResourceParser.java b/src/tool/ResourceParser.java new file mode 100644 index 0000000..59871db --- /dev/null +++ b/src/tool/ResourceParser.java @@ -0,0 +1,284 @@ +/* + * 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 + }; + + /** + * 根据颜色 ID 获取笔记编辑界面的背景资源 ID + * + * @param id 颜色对应的 ID,取值范围为 0 - 4 + * @return 对应的背景资源 ID + */ + public static int getNoteBgResource(int id) { + return BG_EDIT_RESOURCES[id]; + } + + /** + * 根据颜色 ID 获取笔记编辑界面标题的背景资源 ID + * + * @param id 颜色对应的 ID,取值范围为 0 - 4 + * @return 对应的标题背景资源 ID + */ + public static int getNoteTitleBgResource(int id) { + return BG_EDIT_TITLE_RESOURCES[id]; + } + } + + /** + * 获取默认的笔记背景颜色 ID + * + * @param context 应用上下文 + * @return 默认的背景颜色 ID + */ + public static int getDefaultBgId(Context context) { + // 检查是否开启了随机背景颜色的偏好设置 + if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( + NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { + // 如果开启,则随机返回一个背景颜色 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 获取笔记列表首项的背景资源 ID + * + * @param id 颜色对应的 ID,取值范围为 0 - 4 + * @return 对应的首项背景资源 ID + */ + public static int getNoteBgFirstRes(int id) { + return BG_FIRST_RESOURCES[id]; + } + + /** + * 根据颜色 ID 获取笔记列表末项的背景资源 ID + * + * @param id 颜色对应的 ID,取值范围为 0 - 4 + * @return 对应的末项背景资源 ID + */ + public static int getNoteBgLastRes(int id) { + return BG_LAST_RESOURCES[id]; + } + + /** + * 根据颜色 ID 获取笔记列表单项的背景资源 ID + * + * @param id 颜色对应的 ID,取值范围为 0 - 4 + * @return 对应的单项背景资源 ID + */ + public static int getNoteBgSingleRes(int id) { + return BG_SINGLE_RESOURCES[id]; + } + + /** + * 根据颜色 ID 获取笔记列表普通项的背景资源 ID + * + * @param id 颜色对应的 ID,取值范围为 0 - 4 + * @return 对应的普通项背景资源 ID + */ + public static int getNoteBgNormalRes(int id) { + return BG_NORMAL_RESOURCES[id]; + } + + /** + * 获取文件夹的背景资源 ID + * + * @return 文件夹背景资源 ID + */ + public static int getFolderBgRes() { + return R.drawable.list_folder; + } + } + + /** + * 小部件背景资源管理类,负责管理和提供不同尺寸(2x 和 4x)小部件的背景资源。 + */ + 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 尺寸小部件的背景资源 ID + * + * @param id 颜色对应的 ID,取值范围为 0 - 4 + * @return 对应的 2x 小部件背景资源 ID + */ + public static int getWidget2xBgResource(int id) { + return BG_2X_RESOURCES[id]; + } + + // 4x 尺寸小部件的背景资源数组,按颜色顺序存储 + private final static int[] BG_4X_RESOURCES = new int[]{ + R.drawable.widget_4x_yellow, + R.drawable.widget_4x_blue, + R.drawable.widget_4x_white, + R.drawable.widget_4x_green, + R.drawable.widget_4x_red + }; + + /** + * 根据颜色 ID 获取 4x 尺寸小部件的背景资源 ID + * + * @param id 颜色对应的 ID,取值范围为 0 - 4 + * @return 对应的 4x 小部件背景资源 ID + */ + public static int getWidget4xBgResource(int id) { + return BG_4X_RESOURCES[id]; + } + } + + /** + * 文本外观资源管理类,负责管理和提供不同字体大小对应的文本外观资源。 + */ + public static class TextAppearanceResources { + // 文本外观资源数组,按字体大小顺序存储 + private final static int[] TEXTAPPEARANCE_RESOURCES = new int[]{ + R.style.TextAppearanceNormal, + R.style.TextAppearanceMedium, + R.style.TextAppearanceLarge, + R.style.TextAppearanceSuper + }; + + /** + * 根据字体大小 ID 获取对应的文本外观资源 ID + * + * @param id 字体大小对应的 ID,取值范围为 0 - 3 + * @return 对应的文本外观资源 ID + */ + public static int getTexAppearanceResource(int id) { + /** + * HACKME: Fix bug of store the resource id in shared preference. + * The id may larger than the length of resources, in this case, + * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} + */ + // 防止传入的 ID 超出资源数组的范围,如果超出则返回默认字体大小对应的资源 ID + if (id >= TEXTAPPEARANCE_RESOURCES.length) { + return BG_DEFAULT_FONT_SIZE; + } + return TEXTAPPEARANCE_RESOURCES[id]; + } + + /** + * 获取文本外观资源数组的长度 + * + * @return 资源数组的长度 + */ + public static int getResourcesSize() { + return TEXTAPPEARANCE_RESOURCES.length; + } + } +}