diff --git a/src/java/net/micode/notes/tool/BackupUtils.java b/src/java/net/micode/notes/tool/BackupUtils.java index 39f6ec4..32eb5af 100644 --- a/src/java/net/micode/notes/tool/BackupUtils.java +++ b/src/java/net/micode/notes/tool/BackupUtils.java @@ -14,331 +14,316 @@ * 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; - - public static synchronized BackupUtils getInstance(Context context) { - if (sInstance == null) { - sInstance = new BackupUtils(context); - } - return sInstance; - } - - /** - * Following states are signs to represents backup or restore - * status - */ - // Currently, the sdcard is not mounted - public static final int STATE_SD_CARD_UNMOUONTED = 0; - // The backup file not exist - public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; - // The data is not well formated, may be changed by other programs - public static final int STATE_DATA_DESTROIED = 2; - // Some run-time exception which causes restore or backup fails - public static final int STATE_SYSTEM_ERROR = 3; - // Backup or restore success - public static final int STATE_SUCCESS = 4; - - 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; - } - - private static class TextExport { - private static final String[] NOTE_PROJECTION = { - NoteColumns.ID, - NoteColumns.MODIFIED_DATE, - NoteColumns.SNIPPET, - NoteColumns.TYPE - }; - - private static final int NOTE_COLUMN_ID = 0; - - private static final int NOTE_COLUMN_MODIFIED_DATE = 1; - - private static final int NOTE_COLUMN_SNIPPET = 2; - - private static final String[] DATA_PROJECTION = { - DataColumns.CONTENT, - DataColumns.MIME_TYPE, - DataColumns.DATA1, - DataColumns.DATA2, - DataColumns.DATA3, - DataColumns.DATA4, - }; - - private static final int DATA_COLUMN_CONTENT = 0; - - private static final int DATA_COLUMN_MIME_TYPE = 1; - - private static final int DATA_COLUMN_CALL_DATE = 2; - - private static final int DATA_COLUMN_PHONE_NUMBER = 4; - - private final String [] TEXT_FORMAT; - private static final int FORMAT_FOLDER_NAME = 0; - private static final int FORMAT_NOTE_DATE = 1; - private static final int FORMAT_NOTE_CONTENT = 2; - - private Context mContext; - private String mFileName; - private String mFileDirectory; - - public TextExport(Context context) { - TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); - mContext = context; - mFileName = ""; - mFileDirectory = ""; - } - - private String getFormat(int id) { - return TEXT_FORMAT[id]; - } - - /** - * Export the folder identified by folder id to text - */ - private void exportFolderToText(String folderId, PrintStream ps) { - // Query notes belong to this folder - Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, - NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { - folderId - }, null); - - if (notesCursor != null) { - if (notesCursor.moveToFirst()) { - do { - // Print note's last modified date - ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( - mContext.getString(R.string.format_datetime_mdhm), - notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); - // Query data belong to this note - String noteId = notesCursor.getString(NOTE_COLUMN_ID); - exportNoteToText(noteId, ps); - } while (notesCursor.moveToNext()); - } - notesCursor.close(); - } - } - - /** - * Export note identified by id to a print stream - */ - private void exportNoteToText(String noteId, PrintStream ps) { - Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, - DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { - noteId - }, null); - - if (dataCursor != null) { - if (dataCursor.moveToFirst()) { - do { - String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); - if (DataConstants.CALL_NOTE.equals(mimeType)) { - // Print phone number - String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); - long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); - String location = dataCursor.getString(DATA_COLUMN_CONTENT); - - if (!TextUtils.isEmpty(phoneNumber)) { - ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), - phoneNumber)); - } - // Print call date - ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat - .format(mContext.getString(R.string.format_datetime_mdhm), - callDate))); - // Print call attachment location - if (!TextUtils.isEmpty(location)) { - ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), - location)); - } - } else if (DataConstants.NOTE.equals(mimeType)) { - String content = dataCursor.getString(DATA_COLUMN_CONTENT); - if (!TextUtils.isEmpty(content)) { - ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), - content)); - } - } - } while (dataCursor.moveToNext()); - } - dataCursor.close(); - } - // print a line separator between note - try { - ps.write(new byte[] { - Character.LINE_SEPARATOR, Character.LETTER_NUMBER - }); - } catch (IOException e) { - Log.e(TAG, e.toString()); - } - } - - /** - * Note will be exported as text which is user readable - */ - public int exportToText() { - if (!externalStorageAvailable()) { - Log.d(TAG, "Media was not mounted"); - return STATE_SD_CARD_UNMOUONTED; - } - - PrintStream ps = getExportToTextPrintStream(); - if (ps == null) { - Log.e(TAG, "get print stream error"); - return STATE_SYSTEM_ERROR; - } - // First export folder and its notes - Cursor folderCursor = mContext.getContentResolver().query( - Notes.CONTENT_NOTE_URI, - NOTE_PROJECTION, - "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " - + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " - + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null); - - if (folderCursor != null) { - if (folderCursor.moveToFirst()) { - do { - // Print folder's name - String folderName = ""; - if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { - folderName = mContext.getString(R.string.call_record_folder_name); - } else { - folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); - } - if (!TextUtils.isEmpty(folderName)) { - ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); - } - String folderId = folderCursor.getString(NOTE_COLUMN_ID); - exportFolderToText(folderId, ps); - } while (folderCursor.moveToNext()); - } - folderCursor.close(); - } - - // Export notes in root's folder - Cursor noteCursor = mContext.getContentResolver().query( - Notes.CONTENT_NOTE_URI, - NOTE_PROJECTION, - NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID - + "=0", null, null); - - if (noteCursor != null) { - if (noteCursor.moveToFirst()) { - do { - ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( - mContext.getString(R.string.format_datetime_mdhm), - noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); - // Query data belong to this note - String noteId = noteCursor.getString(NOTE_COLUMN_ID); - exportNoteToText(noteId, ps); - } while (noteCursor.moveToNext()); - } - noteCursor.close(); - } - ps.close(); - - return STATE_SUCCESS; - } - - /** - * Get a print stream pointed to the file {@generateExportedTextFile} - */ - 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; - } - } - - /** - * Generate the text file to store imported data - */ - private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { - StringBuilder sb = new StringBuilder(); - sb.append(Environment.getExternalStorageDirectory()); - sb.append(context.getString(filePathResId)); - File filedir = new File(sb.toString()); - sb.append(context.getString( - fileNameFormatResId, - DateFormat.format(context.getString(R.string.format_date_ymd), - System.currentTimeMillis()))); - File file = new File(sb.toString()); - - try { - if (!filedir.exists()) { - filedir.mkdir(); - } - if (!file.exists()) { - file.createNewFile(); - } - return file; - } catch (SecurityException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return null; - } -} + package net.micode.notes.tool; + + public class BackupUtils { + private static final String TAG = "BackupUtils"; + // Singleton stuff + private static BackupUtils sInstance; //类里面为什么可以定义自身类的对象? + + public static synchronized BackupUtils getInstance(Context context) { + //ynchronized 关键字,代表这个方法加锁,相当于不管哪一个线程(例如线程A) + //运行到这个方法时,都要检查有没有其它线程B(或者C、 D等)正在用这个方法(或者该类的其他同步方法),有的话要等正在使用synchronized方法的线程B(或者C 、D)运行完这个方法后再运行此线程A,没有的话,锁定调用者,然后直接运行。 + //它包括两种用法:synchronized 方法和 synchronized 块。 + if (sInstance == null) { + //如果当前备份不存在,则新声明一个 + sInstance = new BackupUtils(context); + } + return sInstance; + } + + /** + * Following states are signs to represents backup or restore + * status + */ + // Currently, the sdcard is not mounted SD卡没有被装入手机 + public static final int STATE_SD_CARD_UNMOUONTED = 0; + // The backup file not exist 备份文件夹不存在 + public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; + // The data is not well formated, may be changed by other programs 数据已被破坏,可能被修改 + public static final int STATE_DATA_DESTROIED = 2; + // Some run-time exception which causes restore or backup fails 超时异常 + public static final int STATE_SYSTEM_ERROR = 3; + // Backup or restore success 成功存储 + public static final int STATE_SUCCESS = 4; + + 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; + } + + private static class TextExport { + private static final String[] NOTE_PROJECTION = { + NoteColumns.ID, + NoteColumns.MODIFIED_DATE, + NoteColumns.SNIPPET, + NoteColumns.TYPE + }; + + private static final int NOTE_COLUMN_ID = 0; + + private static final int NOTE_COLUMN_MODIFIED_DATE = 1; + + private static final int NOTE_COLUMN_SNIPPET = 2; + + private static final String[] DATA_PROJECTION = { + DataColumns.CONTENT, + DataColumns.MIME_TYPE, + DataColumns.DATA1, + DataColumns.DATA2, + DataColumns.DATA3, + DataColumns.DATA4, + }; + + private static final int DATA_COLUMN_CONTENT = 0; + + private static final int DATA_COLUMN_MIME_TYPE = 1; + + private static final int DATA_COLUMN_CALL_DATE = 2; + + private static final int DATA_COLUMN_PHONE_NUMBER = 4; + + private final String [] TEXT_FORMAT; + private static final int FORMAT_FOLDER_NAME = 0; + private static final int FORMAT_NOTE_DATE = 1; + private static final int FORMAT_NOTE_CONTENT = 2; + + private Context mContext; + private String mFileName; + private String mFileDirectory; + + public TextExport(Context context) { + TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); + mContext = context; + mFileName = ""; //为什么为空? + mFileDirectory = ""; + } + + private String getFormat(int id) { //获取文本的组成部分 + return TEXT_FORMAT[id]; + } + + /** + * Export the folder identified by folder id to text + */ + private void exportFolderToText(String folderId, PrintStream ps) { + // Query notes belong to this folder 通过查询parent id是文件夹id的note来选出制定ID文件夹下的Note + Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { + folderId + }, null); + + if (notesCursor != null) { + if (notesCursor.moveToFirst()) { + do { + // Print note's last modified date ps里面保存有这份note的日期 + ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), + notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); + // Query data belong to this note + String noteId = notesCursor.getString(NOTE_COLUMN_ID); + exportNoteToText(noteId, ps); //将文件导出到text + } while (notesCursor.moveToNext()); + } + notesCursor.close(); + } + } + + /** + * Export note identified by id to a print stream + */ + 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) { //利用光标来扫描内容,区别为callnote和note两种,靠ps.printline输出 + if (dataCursor.moveToFirst()) { + do { + String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); + if (DataConstants.CALL_NOTE.equals(mimeType)) { + // Print phone number + String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); + long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); + String location = dataCursor.getString(DATA_COLUMN_CONTENT); + + if (!TextUtils.isEmpty(phoneNumber)) { //判断是否为空字符 + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), + phoneNumber)); + } + // Print call date + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat + .format(mContext.getString(R.string.format_datetime_mdhm), + callDate))); + // Print call attachment location + if (!TextUtils.isEmpty(location)) { + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), + location)); + } + } else if (DataConstants.NOTE.equals(mimeType)) { + String content = dataCursor.getString(DATA_COLUMN_CONTENT); + if (!TextUtils.isEmpty(content)) { + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), + content)); + } + } + } while (dataCursor.moveToNext()); + } + dataCursor.close(); + } + // print a line separator between note + try { + ps.write(new byte[] { + Character.LINE_SEPARATOR, Character.LETTER_NUMBER + }); + } catch (IOException e) { + Log.e(TAG, e.toString()); + } + } + + /** + * Note will be exported as text which is user readable + */ + public int exportToText() { //总函数,调用上面的exportFolder和exportNote + if (!externalStorageAvailable()) { + Log.d(TAG, "Media was not mounted"); + return STATE_SD_CARD_UNMOUONTED; + } + + PrintStream ps = getExportToTextPrintStream(); + if (ps == null) { + Log.e(TAG, "get print stream error"); + return STATE_SYSTEM_ERROR; + } + // First export folder and its notes 导出文件夹,就是导出里面包含的便签 + Cursor folderCursor = mContext.getContentResolver().query( + Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, + "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " + + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " + + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null); + + if (folderCursor != null) { + if (folderCursor.moveToFirst()) { + do { + // Print folder's name + String folderName = ""; + if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { + folderName = mContext.getString(R.string.call_record_folder_name); + } else { + folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); + } + if (!TextUtils.isEmpty(folderName)) { + ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); + } + String folderId = folderCursor.getString(NOTE_COLUMN_ID); + exportFolderToText(folderId, ps); + } while (folderCursor.moveToNext()); + } + folderCursor.close(); + } + + // Export notes in root's folder 将根目录里的便签导出(由于不属于任何文件夹,因此无法通过文件夹导出来实现这一部分便签的导出) + Cursor noteCursor = mContext.getContentResolver().query( + Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, + NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + + "=0", null, null); + + if (noteCursor != null) { + if (noteCursor.moveToFirst()) { + do { + ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), + noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); + // Query data belong to this note + String noteId = noteCursor.getString(NOTE_COLUMN_ID); + exportNoteToText(noteId, ps); + } while (noteCursor.moveToNext()); + } + noteCursor.close(); + } + ps.close(); + + return STATE_SUCCESS; + } + + /** + * Get a print stream pointed to the file {@generateExportedTextFile} + */ + 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); //将ps输出流输出到特定的文件,目的就是导出到文件,而不是直接输出 + } catch (FileNotFoundException e) { + e.printStackTrace(); + return null; + } catch (NullPointerException e) { + e.printStackTrace(); + return null; + } + return ps; + } + } + + /** + * Generate the text file to store imported data + */ + private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { + StringBuilder sb = new StringBuilder(); + sb.append(Environment.getExternalStorageDirectory()); //外部(SD卡)的存储路径 + sb.append(context.getString(filePathResId)); //文件的存储路径 + File filedir = new File(sb.toString()); //filedir应该就是用来存储路径信息 + sb.append(context.getString( + fileNameFormatResId, + DateFormat.format(context.getString(R.string.format_date_ymd), + System.currentTimeMillis()))); + File file = new File(sb.toString()); + + try { //如果这些文件不存在,则新建 + if (!filedir.exists()) { + filedir.mkdir(); + } + if (!file.exists()) { + file.createNewFile(); + } + return file; + } catch (SecurityException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + // try catch 异常处理 + return null; + } + } + diff --git a/src/java/net/micode/notes/tool/DataUtils.java b/src/java/net/micode/notes/tool/DataUtils.java index 56b2e19..a9c6a48 100644 --- a/src/java/net/micode/notes/tool/DataUtils.java +++ b/src/java/net/micode/notes/tool/DataUtils.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +/*该类定义在 net.micode.notes.tool 包下,并导入了Android和Java的一些核心类。这些导入的类提供了对内容提供者操作、日志记录、游标以及存储值的支持。 */ package net.micode.notes.tool; - +/*定义了一个公共类 DataUtils,并创建了一个常量 TAG 用于日志记录。 */ import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; @@ -34,7 +34,9 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; import java.util.ArrayList; import java.util.HashSet; - +/*这个方法实现了根据一组ID批量删除笔记的功能。 +它首先检查ID集合是否为空,并创建一个操作列表。 +通过 ContentResolver 执行删除操作,成功后返回 true,失败则返回 false。 */ public class DataUtils { public static final String TAG = "DataUtils"; public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { @@ -71,7 +73,9 @@ public class DataUtils { } return false; } - +/*此方法将指定的笔记移动到目标文件夹。 +更新笔记的父文件夹ID并标记为本地修改。 */ +/*查询非系统文件夹的数量。异常处理用于确保在查询失败时释放游标资源。 */ public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { ContentValues values = new ContentValues(); values.put(NoteColumns.PARENT_ID, desFolderId); @@ -88,238 +92,294 @@ public class DataUtils { * @param: [resolver, ids, folderId] * @return: boolean */ - public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, long folderId) { - if (ids == null) { - Log.d(TAG, "the ids is null"); - return true; - } - - ArrayList operationList = new ArrayList(); - for (long id : ids) { - ContentProviderOperation.Builder builder = ContentProviderOperation - .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); - builder.withValue(NoteColumns.PARENT_ID, folderId); - builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); - operationList.add(builder.build()); - } - - try { - ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); - if (results == null || results.length == 0 || results[0] == null) { - Log.d(TAG, "delete notes failed, ids:" + ids.toString()); - return false; - } - return true; - } catch (RemoteException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); - } catch (OperationApplicationException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); - } - return false; + /*检查数据库中是否存在特定类型的可见笔记。 */ +/** + * 批量将便签移动到指定文件夹 + * @param resolver ContentResolver对象 + * @param ids 需要移动的便签ID集合 + * @param folderId 目标文件夹ID + * @return 是否移动成功 + */ +public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, long folderId) { + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; } - /** - * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} - */ - 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; + ArrayList operationList = new ArrayList(); + for (long id : ids) { + ContentProviderOperation.Builder builder = ContentProviderOperation + .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + builder.withValue(NoteColumns.PARENT_ID, folderId); + builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); + operationList.add(builder.build()); } - /** - * @Method visibleInNoteDatabase - * @Date 2024/12/13 9:08 - * @param resolver - * @param noteId - * @param type - * @Author lenovo - * @Return boolean - * @Description 访问数据库中是否有 noteId 对应的便签 - */ - public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { - /** - * withAppendedId 将 URI 和 ID 连接成一个新的URI - * query 返回 Uri 中符合 selection 的表格 - * lenovo 2024/12/13 9:06 - */ - 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(); + try { + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + return false; } - return exist; + return true; + } catch (RemoteException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } catch (OperationApplicationException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); } + return false; +} - public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { - Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), - null, null, null, null); +/** + * 获取用户文件夹的数量(不包括系统文件夹) + * @param resolver ContentResolver对象 + * @return 用户文件夹的数量 + */ +public static int getUserFolderCount(ContentResolver resolver) { + Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI, + new String[] { "COUNT(*)" }, + NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", + new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, + null); - boolean exist = false; - if (cursor != null) { - if (cursor.getCount() > 0) { - exist = true; + 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(); } - cursor.close(); } - return exist; } + return count; +} - public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { - Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), - null, null, null, null); +/** + * 检查数据库中是否存在指定ID和类型的便签 + * @param resolver ContentResolver对象 + * @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(); + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; } - return exist; + cursor.close(); } + return exist; +} - public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { - Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, - NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + - " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + - " AND " + NoteColumns.SNIPPET + "=?", - new String[] { name }, null); - boolean exist = false; - if(cursor != null) { - if(cursor.getCount() > 0) { - exist = true; - } - cursor.close(); +/** + * 检查数据库中是否存在指定ID的便签 + * @param resolver ContentResolver对象 + * @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; } - return exist; + cursor.close(); } + return exist; +} - 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); +/** + * 检查数据库中是否存在指定ID的数据 + * @param resolver ContentResolver对象 + * @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); - HashSet set = null; - if (c != null) { - if (c.moveToFirst()) { - set = new HashSet(); - do { - try { - AppWidgetAttribute widget = new AppWidgetAttribute(); - widget.widgetId = c.getInt(0); - widget.widgetType = c.getInt(1); - set.add(widget); - } catch (IndexOutOfBoundsException e) { - Log.e(TAG, e.toString()); - } - } while (c.moveToNext()); - } - c.close(); + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; } - return set; + cursor.close(); } + return exist; +} - public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { - Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, - new String [] { CallNote.PHONE_NUMBER }, - CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", - new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, - null); - - if (cursor != null && cursor.moveToFirst()) { - try { - return cursor.getString(0); - } catch (IndexOutOfBoundsException e) { - Log.e(TAG, "Get call number fails " + e.toString()); - } finally { - cursor.close(); - } +/** + * 检查数据库中是否存在指定名称的可见文件夹 + * @param resolver ContentResolver对象 + * @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; } - return ""; + cursor.close(); } + return exist; +} - public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { - Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, - new String [] { CallNote.NOTE_ID }, - CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" - + CallNote.PHONE_NUMBER + ",?)", - new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, - null); +/** + * 获取指定文件夹中的小部件属性集合 + * @param resolver ContentResolver对象 + * @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); - if (cursor != null) { - if (cursor.moveToFirst()) { + HashSet set = null; + if (c != null) { + if (c.moveToFirst()) { + set = new HashSet(); + do { try { - return cursor.getLong(0); + AppWidgetAttribute widget = new AppWidgetAttribute(); + widget.widgetId = c.getInt(0); + widget.widgetType = c.getInt(1); + set.add(widget); } catch (IndexOutOfBoundsException e) { - Log.e(TAG, "Get call note id fails " + e.toString()); + Log.e(TAG, e.toString()); } - } - cursor.close(); + } while (c.moveToNext()); } - return 0; + c.close(); } + return set; +} - public static String getSnippetById(ContentResolver resolver, long noteId) { - Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, - new String [] { NoteColumns.SNIPPET }, - NoteColumns.ID + "=?", - new String [] { String.valueOf(noteId)}, - null); +/** + * 根据便签ID获取电话号码 + * @param resolver ContentResolver对象 + * @param noteId 便签ID + * @return 电话号码 + */ +public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + new String [] { CallNote.PHONE_NUMBER }, + CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", + new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, + null); - if (cursor != null) { - String snippet = ""; - if (cursor.moveToFirst()) { - snippet = cursor.getString(0); - } + 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 snippet; } - throw new IllegalArgumentException("Note is not found with id: " + noteId); } + 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); +/** + * 根据电话号码和通话日期获取便签ID + * @param resolver ContentResolver对象 + * @param phoneNumber 电话号码 + * @param callDate 通话日期 + * @return 便签ID + */ +public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + new String [] { CallNote.NOTE_ID }, + CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" + + CallNote.PHONE_NUMBER + ",?)", + new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, + null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + try { + return cursor.getLong(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "Get call note id fails " + e.toString()); } } + cursor.close(); + } + return 0; +} + +/** + * 根据便签ID获取便签摘要 + * @param resolver ContentResolver对象 + * @param noteId 便签ID + * @return 便签摘要 + */ +public static String getSnippetById(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, + new String [] { NoteColumns.SNIPPET }, + NoteColumns.ID + "=?", + new String [] { String.valueOf(noteId)}, + null); + + if (cursor != null) { + String snippet = ""; + if (cursor.moveToFirst()) { + snippet = cursor.getString(0); + } + cursor.close(); return snippet; } + throw new IllegalArgumentException("Note is not found with id: " + noteId); +} - public static Cursor searchInNoteDatabase(ContentResolver resolver, String query) { - Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, - new String[]{NoteColumns.ID}, - Notes.DataColumns.CONTENT + " LIKE'%" + query +"%'", - null, - null); - return cursor; +/** + * 格式化便签摘要 + * @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; +} + +/** + * 在数据库中搜索包含指定查询内容的便签 + * @param resolver ContentResolver对象 + * @param query 查询内容 + * @return 包含查询结果的Cursor对象 + */ +public static Cursor searchInNoteDatabase(ContentResolver resolver, String query) { + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + new String[]{NoteColumns.ID}, + Notes.DataColumns.CONTENT + " LIKE'%" + query +"%'", + null, + null); + return cursor; } \ No newline at end of file diff --git a/src/java/net/micode/notes/tool/GTaskStringUtils.java b/src/java/net/micode/notes/tool/GTaskStringUtils.java index 666b729..694d849 100644 --- a/src/java/net/micode/notes/tool/GTaskStringUtils.java +++ b/src/java/net/micode/notes/tool/GTaskStringUtils.java @@ -16,6 +16,7 @@ package net.micode.notes.tool; +// 该类用于定义 Google 任务相关的 JSON 字段常量 public class GTaskStringUtils { public final static String GTASK_JSON_ACTION_ID = "action_id"; @@ -110,4 +111,4 @@ public class GTaskStringUtils { public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; -} +} \ No newline at end of file diff --git a/src/java/net/micode/notes/tool/ResourceParser.java b/src/java/net/micode/notes/tool/ResourceParser.java index 5876249..0fc6a61 100644 --- a/src/java/net/micode/notes/tool/ResourceParser.java +++ b/src/java/net/micode/notes/tool/ResourceParser.java @@ -22,6 +22,7 @@ import android.preference.PreferenceManager; import net.micode.notes.R; import net.micode.notes.ui.NotesPreferenceActivity; +// 资源解析器类 public class ResourceParser { public static final int YELLOW = 0; @@ -40,6 +41,7 @@ public class ResourceParser { 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, @@ -57,15 +59,18 @@ public class ResourceParser { R.drawable.edit_title_red }; + // 获取备忘录背景资源 public static int getNoteBgResource(int id) { return BG_EDIT_RESOURCES[id]; } + // 获取备忘录标题背景资源 public static int getNoteTitleBgResource(int id) { return BG_EDIT_TITLE_RESOURCES[id]; } } + // 获取默认背景ID public static int getDefaultBgId(Context context) { if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { @@ -75,6 +80,7 @@ public class ResourceParser { } } + // 备忘录项目背景资源类 public static class NoteItemBgResources { private final static int [] BG_FIRST_RESOURCES = new int [] { R.drawable.list_yellow_up, @@ -108,27 +114,33 @@ public class ResourceParser { R.drawable.list_red_single }; + // 获取备忘录第一个背景资源 public static int getNoteBgFirstRes(int id) { return BG_FIRST_RESOURCES[id]; } + // 获取备忘录最后一个背景资源 public static int getNoteBgLastRes(int id) { return BG_LAST_RESOURCES[id]; } + // 获取备忘录单独背景资源 public static int getNoteBgSingleRes(int id) { return BG_SINGLE_RESOURCES[id]; } + // 获取备忘录正常背景资源 public static int getNoteBgNormalRes(int id) { return BG_NORMAL_RESOURCES[id]; } + // 获取文件夹背景资源 public static int getFolderBgRes() { return R.drawable.list_folder; } } + // 小部件背景资源类 public static class WidgetBgResources { private final static int [] BG_2X_RESOURCES = new int [] { R.drawable.widget_2x_yellow, @@ -138,6 +150,7 @@ public class ResourceParser { R.drawable.widget_2x_red, }; + // 获取2x小部件背景资源 public static int getWidget2xBgResource(int id) { return BG_2X_RESOURCES[id]; } @@ -150,11 +163,13 @@ public class ResourceParser { R.drawable.widget_4x_red }; + // 获取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, @@ -163,6 +178,7 @@ public class ResourceParser { R.style.TextAppearanceSuper }; + // 获取文本外观资源 public static int getTexAppearanceResource(int id) { /** * HACKME: Fix bug of store the resource id in shared preference. @@ -175,8 +191,9 @@ public class ResourceParser { return TEXTAPPEARANCE_RESOURCES[id]; } + // 获取资源大小 public static int getResourcesSize() { return TEXTAPPEARANCE_RESOURCES.length; } } -} +} \ No newline at end of file diff --git a/src/java/net/micode/notes/ui/AlarmAlertActivity.java b/src/java/net/micode/notes/ui/AlarmAlertActivity.java index e305b5e..7d4d865 100644 --- a/src/java/net/micode/notes/ui/AlarmAlertActivity.java +++ b/src/java/net/micode/notes/ui/AlarmAlertActivity.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -39,49 +39,41 @@ import net.micode.notes.tool.DataUtils; import java.io.IOException; - +/** + * AlarmAlertActivity 类用于显示闹钟提醒的对话框,并播放提醒音。 + */ public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { - private long mNoteId; - private String mSnippet; - private static final int SNIPPET_PREW_MAX_LEN = 60; - MediaPlayer mPlayer; + private long mNoteId; // 便签的ID + private String mSnippet; // 便签的摘要信息 + private static final int SNIPPET_PREW_MAX_LEN = 60; // 摘要信息的最大长度 + MediaPlayer mPlayer; // 用于播放提醒音的MediaPlayer @Override - /** - * @Method onCreate - * @Date 2024/12/25 8:15 - * @param savedInstanceState - * @Author lenovo - * @Return void - * @Description - */ + /** + * 创建Activity时的初始化操作。 + * @param savedInstanceState 保存的实例状态 + */ protected void onCreate(Bundle savedInstanceState) { - /** - * Bundel 类似于 map,key-value存储 - * super 代表父类, 调用 onCreate 用于恢复上次结束的状态 - * lenovo 2024/12/25 8:39 - */ super.onCreate(savedInstanceState); - requestWindowFeature(Window.FEATURE_NO_TITLE); + requestWindowFeature(Window.FEATURE_NO_TITLE); // 不显示标题栏 final Window win = getWindow(); - // 在屏幕锁定时显示 - win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); + win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // 锁屏时显示 - // 锁屏时到闹钟提示时间后,点亮屏幕 + // 如果屏幕未点亮,则设置相关标志以确保屏幕点亮并显示对话框 if (!isScreenOn()) { - win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON - | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON - | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON - | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); + win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | + WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | + WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON | + WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); } Intent intent = getIntent(); try { - mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); - mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); - // 超出长度则变为 substr + "..." + mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); // 获取便签ID + mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); // 获取便签摘要 + // 如果摘要过长,则截取并添加省略号 mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) : mSnippet; @@ -91,85 +83,103 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD } mPlayer = new MediaPlayer(); - // 查找数据库中有没有 mNoteId 的便签, 如果有则激发对话框 + 闹钟提示音 + // 如果便签存在于数据库中,则显示对话框并播放提醒音 if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { showActionDialog(); playAlarmSound(); } else { - finish(); + finish(); // 如果不存在,则结束Activity } } + /** + * 检查屏幕是否已点亮。 + * @return 屏幕是否已点亮 + */ private boolean isScreenOn() { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); return pm.isScreenOn(); } + /** + * 播放闹钟提醒音。 + */ private void playAlarmSound() { - Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); + Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); // 获取默认闹钟铃声 int silentModeStreams = Settings.System.getInt(getContentResolver(), - Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); + Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); // 获取静音模式影响的流类型 if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { - mPlayer.setAudioStreamType(silentModeStreams); + mPlayer.setAudioStreamType(silentModeStreams); // 设置音频流类型 } else { mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); } try { - mPlayer.setDataSource(this, url); - mPlayer.prepare(); - mPlayer.setLooping(true); - mPlayer.start(); + mPlayer.setDataSource(this, url); // 设置播放数据源 + mPlayer.prepare(); // 准备播放 + mPlayer.setLooping(true); // 设置循环播放 + mPlayer.start(); // 开始播放 } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { - // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { - // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { - // TODO Auto-generated catch block e.printStackTrace(); } } - private void showActionDialog() {// TODO: 2024/1/2 可以模仿这个,写一个xxx条件下弹出来的Dialog + /** + * 显示闹钟提醒对话框。 + */ + private void showActionDialog() { AlertDialog.Builder dialog = new AlertDialog.Builder(this); - dialog.setTitle(R.string.app_name); - dialog.setMessage(mSnippet); - dialog.setPositiveButton(R.string.notealert_ok, this); + dialog.setTitle(R.string.app_name); // 设置对话框标题 + dialog.setMessage(mSnippet); // 设置对话框消息 + dialog.setPositiveButton(R.string.notealert_ok, this); // 设置确定按钮 if (isScreenOn()) { - dialog.setNegativeButton(R.string.notealert_enter, this); + dialog.setNegativeButton(R.string.notealert_enter, this); // 设置取消按钮 } - dialog.show().setOnDismissListener(this); + dialog.show().setOnDismissListener(this); // 显示对话框并设置消失监听器 } + /** + * 对话框按钮点击事件处理。 + * @param dialog 对话框 + * @param which 被点击的按钮 + */ public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_NEGATIVE: Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_VIEW); - intent.putExtra(Intent.EXTRA_UID, mNoteId); - startActivity(intent); + intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递便签ID + startActivity(intent); // 启动便签编辑Activity break; default: break; } } + /** + * 对话框消失时的处理。 + * @param dialog 对话框 + */ public void onDismiss(DialogInterface dialog) { - stopAlarmSound(); - finish(); + stopAlarmSound(); // 停止播放提醒音 + finish(); // 结束Activity } + /** + * 停止播放提醒音。 + */ private void stopAlarmSound() { if (mPlayer != null) { - mPlayer.stop(); - mPlayer.release(); - mPlayer = null; + mPlayer.stop(); // 停止播放 + mPlayer.release(); // 释放资源 + mPlayer = null; // 清空MediaPlayer对象 } } -} +} \ No newline at end of file diff --git a/src/java/net/micode/notes/ui/AlarmInitReceiver.java b/src/java/net/micode/notes/ui/AlarmInitReceiver.java index f221202..8c76f3c 100644 --- a/src/java/net/micode/notes/ui/AlarmInitReceiver.java +++ b/src/java/net/micode/notes/ui/AlarmInitReceiver.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -27,20 +27,32 @@ import android.database.Cursor; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; - +/** + * 当应用启动时,AlarmInitReceiver 会初始化所有未触发的闹钟。 + */ public class AlarmInitReceiver extends BroadcastReceiver { + // 查询数据库时需要的列名 private static final String [] PROJECTION = new String [] { - NoteColumns.ID, - NoteColumns.ALERTED_DATE + NoteColumns.ID, // 便签ID + NoteColumns.ALERTED_DATE // 闹钟提醒时间 }; + // 列索引,方便获取数据 private static final int COLUMN_ID = 0; private static final int COLUMN_ALERTED_DATE = 1; + /** + * 当接收到广播时,初始化所有未触发的闹钟。 + * @param context 上下文 + * @param intent 接收到的意图 + */ @Override public void onReceive(Context context, Intent intent) { + // 获取当前时间 long currentDate = System.currentTimeMillis(); + + // 查询所有未触发的闹钟 Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, PROJECTION, NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, @@ -48,18 +60,25 @@ public class AlarmInitReceiver extends BroadcastReceiver { null); if (c != null) { + // 如果有未触发的闹钟 if (c.moveToFirst()) { do { + // 获取闹钟提醒时间和便签ID long alertDate = c.getLong(COLUMN_ALERTED_DATE); Intent sender = new Intent(context, AlarmReceiver.class); sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); + + // 创建PendingIntent PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); - AlarmManager alermManager = (AlarmManager) context - .getSystemService(Context.ALARM_SERVICE); - alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); - } while (c.moveToNext()); + + // 获取AlarmManager服务 + AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + + // 设置闹钟 + alarmManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + } while (c.moveToNext()); // 继续查询下一个闹钟 } - c.close(); + c.close(); // 关闭游标 } } -} +} \ No newline at end of file diff --git a/src/java/net/micode/notes/ui/AlarmReceiver.java b/src/java/net/micode/notes/ui/AlarmReceiver.java index 54e503b..6cc4c17 100644 --- a/src/java/net/micode/notes/ui/AlarmReceiver.java +++ b/src/java/net/micode/notes/ui/AlarmReceiver.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -20,11 +20,22 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; +/** + * 当闹钟时间到时,AlarmReceiver 会启动闹钟提醒界面。 + */ public class AlarmReceiver extends BroadcastReceiver { + /** + * 当接收到闹钟触发的广播时,启动闹钟提醒界面。 + * @param context 上下文 + * @param intent 接收到的意图 + */ @Override public void onReceive(Context context, Intent intent) { + // 设置意图的目标类为闹钟提醒界面 intent.setClass(context, AlarmAlertActivity.class); + // 添加标志,表示启动一个新的任务 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + // 启动闹钟提醒界面 context.startActivity(intent); } -} +} \ No newline at end of file diff --git a/src/java/net/micode/notes/ui/DateTimePicker.java b/src/java/net/micode/notes/ui/DateTimePicker.java index 496b0cd..27e4d39 100644 --- a/src/java/net/micode/notes/ui/DateTimePicker.java +++ b/src/java/net/micode/notes/ui/DateTimePicker.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -21,20 +21,28 @@ import java.util.Calendar; import net.micode.notes.R; - import android.content.Context; import android.text.format.DateFormat; import android.view.View; import android.widget.FrameLayout; import android.widget.NumberPicker; +/** + * DateTimePicker 类用于创建日期和时间选择器。 + */ public class DateTimePicker extends FrameLayout { + // 默认使能状态 private static final boolean DEFAULT_ENABLE_STATE = true; + // 12小时制和24小时制的小时数 private static final int HOURS_IN_HALF_DAY = 12; private static final int HOURS_IN_ALL_DAY = 24; + + // 一周的天数 private static final int DAYS_IN_ALL_WEEK = 7; + + // 日期和时间选择器的最小和最大值 private static final int DATE_SPINNER_MIN_VAL = 0; private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; @@ -46,36 +54,51 @@ public class DateTimePicker extends FrameLayout { private static final int AMPM_SPINNER_MIN_VAL = 0; private static final int AMPM_SPINNER_MAX_VAL = 1; + // 日期选择器 private final NumberPicker mDateSpinner; + // 小时选择器 private final NumberPicker mHourSpinner; + // 分钟选择器 private final NumberPicker mMinuteSpinner; + // AM/PM选择器 private final NumberPicker mAmPmSpinner; + // 当前日期 private Calendar mDate; + // 日期显示值 private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; + // 是否为上午 private boolean mIsAm; + // 是否为24小时制 private boolean mIs24HourView; + // 是否使能 private boolean mIsEnabled = DEFAULT_ENABLE_STATE; + // 初始化标志 private boolean mInitialising; + // 日期时间改变监听器 private OnDateTimeChangedListener mOnDateTimeChangedListener; + // 日期改变监听器 private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + // 更新日期 mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); updateDateControl(); onDateTimeChanged(); } }; + // 小时改变监听器 private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + // 更新小时 boolean isDateChanged = false; Calendar cal = Calendar.getInstance(); if (!mIs24HourView) { @@ -115,9 +138,11 @@ public class DateTimePicker extends FrameLayout { } }; + // 分钟改变监听器 private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + // 更新分钟 int minValue = mMinuteSpinner.getMinValue(); int maxValue = mMinuteSpinner.getMaxValue(); int offset = 0; @@ -144,9 +169,11 @@ public class DateTimePicker extends FrameLayout { } }; + // AM/PM改变监听器 private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + // 更新AM/PM mIsAm = !mIsAm; if (mIsAm) { mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); @@ -158,19 +185,37 @@ public class DateTimePicker extends FrameLayout { } }; + /** + * 日期时间改变监听器接口。 + */ public interface OnDateTimeChangedListener { void onDateTimeChanged(DateTimePicker view, int year, int month, int dayOfMonth, int hourOfDay, int minute); } + /** + * 构造函数。 + * @param context 上下文 + */ public DateTimePicker(Context context) { this(context, System.currentTimeMillis()); } + /** + * 构造函数。 + * @param context 上下文 + * @param date 当前日期 + */ public DateTimePicker(Context context, long date) { this(context, date, DateFormat.is24HourFormat(context)); } + /** + * 构造函数。 + * @param context 上下文 + * @param date 当前日期 + * @param is24HourView 是否为24小时制 + */ public DateTimePicker(Context context, long date, boolean is24HourView) { super(context); mDate = Calendar.getInstance(); @@ -191,6 +236,7 @@ public class DateTimePicker extends FrameLayout { mMinuteSpinner.setOnLongPressUpdateInterval(100); mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); + // AM/PM选择器的字符串数组 String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); @@ -198,22 +244,28 @@ public class DateTimePicker extends FrameLayout { mAmPmSpinner.setDisplayedValues(stringsForAmPm); mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); - // update controls to initial state + // 更新控件到初始状态 updateDateControl(); updateHourControl(); updateAmPmControl(); + // 设置24小时制 set24HourView(is24HourView); - // set to current time + // 设置当前日期 setCurrentDate(date); + // 设置使能状态 setEnabled(isEnabled()); - // set the content descriptions + // 设置内容描述 mInitialising = false; } + /** + * 设置使能状态。 + * @param enabled 是否使能 + */ @Override public void setEnabled(boolean enabled) { if (mIsEnabled == enabled) { @@ -227,24 +279,26 @@ public class DateTimePicker extends FrameLayout { mIsEnabled = enabled; } + /** + * 获取使能状态。 + * @return 是否使能 + */ @Override public boolean isEnabled() { return mIsEnabled; } /** - * Get the current date in millis - * - * @return the current date in millis + * 获取当前日期的时间戳。 + * @return 当前日期的时间戳 */ public long getCurrentDateInTimeMillis() { return mDate.getTimeInMillis(); } /** - * Set the current date - * - * @param date The current date in millis + * 设置当前日期。 + * @param date 当前日期的时间戳 */ public void setCurrentDate(long date) { Calendar cal = Calendar.getInstance(); @@ -254,13 +308,12 @@ public class DateTimePicker extends FrameLayout { } /** - * Set the current date - * - * @param year The current year - * @param month The current month - * @param dayOfMonth The current dayOfMonth - * @param hourOfDay The current hourOfDay - * @param minute The current minute + * 设置当前日期。 + * @param year 当前年份 + * @param month 当前月份 + * @param dayOfMonth 当前日期 + * @param hourOfDay 当前小时 + * @param minute 当前分钟 */ public void setCurrentDate(int year, int month, int dayOfMonth, int hourOfDay, int minute) { @@ -272,18 +325,16 @@ public class DateTimePicker extends FrameLayout { } /** - * Get current year - * - * @return The current year + * 获取当前年份。 + * @return 当前年份 */ public int getCurrentYear() { return mDate.get(Calendar.YEAR); } /** - * Set current year - * - * @param year The current year + * 设置当前年份。 + * @param year 当前年份 */ public void setCurrentYear(int year) { if (!mInitialising && year == getCurrentYear()) { @@ -295,18 +346,16 @@ public class DateTimePicker extends FrameLayout { } /** - * Get current month in the year - * - * @return The current month in the year + * 获取当前月份。 + * @return 当前月份 */ public int getCurrentMonth() { return mDate.get(Calendar.MONTH); } /** - * Set current month in the year - * - * @param month The month in the year + * 设置当前月份。 + * @param month 当前月份 */ public void setCurrentMonth(int month) { if (!mInitialising && month == getCurrentMonth()) { @@ -318,18 +367,16 @@ public class DateTimePicker extends FrameLayout { } /** - * Get current day of the month - * - * @return The day of the month + * 获取当前日期。 + * @return 当前日期 */ public int getCurrentDay() { return mDate.get(Calendar.DAY_OF_MONTH); } /** - * Set current day of the month - * - * @param dayOfMonth The day of the month + * 设置当前日期。 + * @param dayOfMonth 当前日期 */ public void setCurrentDay(int dayOfMonth) { if (!mInitialising && dayOfMonth == getCurrentDay()) { @@ -341,15 +388,19 @@ public class DateTimePicker extends FrameLayout { } /** - * Get current hour in 24 hour mode, in the range (0~23) - * @return The current hour in 24 hour mode + * 获取当前小时(24小时制)。 + * @return 当前小时(24小时制) */ public int getCurrentHourOfDay() { return mDate.get(Calendar.HOUR_OF_DAY); } + /** + * 获取当前小时(12小时制或24小时制)。 + * @return 当前小时 + */ private int getCurrentHour() { - if (mIs24HourView){ + if (mIs24HourView) { return getCurrentHourOfDay(); } else { int hour = getCurrentHourOfDay(); @@ -362,9 +413,8 @@ public class DateTimePicker extends FrameLayout { } /** - * Set current hour in 24 hour mode, in the range (0~23) - * - * @param hourOfDay + * 设置当前小时(24小时制)。 + * @param hourOfDay 当前小时(24小时制) */ public void setCurrentHour(int hourOfDay) { if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { @@ -390,16 +440,16 @@ public class DateTimePicker extends FrameLayout { } /** - * Get currentMinute - * - * @return The Current Minute + * 获取当前分钟。 + * @return 当前分钟 */ public int getCurrentMinute() { return mDate.get(Calendar.MINUTE); } /** - * Set current minute + * 设置当前分钟。 + * @param minute 当前分钟 */ public void setCurrentMinute(int minute) { if (!mInitialising && minute == getCurrentMinute()) { @@ -411,16 +461,16 @@ public class DateTimePicker extends FrameLayout { } /** - * @return true if this is in 24 hour view else false. + * 获取是否为24小时制。 + * @return 是否为24小时制 */ - public boolean is24HourView () { + public boolean is24HourView() { return mIs24HourView; } /** - * Set whether in 24 hour or AM/PM mode. - * - * @param is24HourView True for 24 hour mode. False for AM/PM mode. + * 设置是否为24小时制。 + * @param is24HourView 是否为24小时制 */ public void set24HourView(boolean is24HourView) { if (mIs24HourView == is24HourView) { @@ -434,6 +484,9 @@ public class DateTimePicker extends FrameLayout { updateAmPmControl(); } + /** + * 更新日期控件。 + */ private void updateDateControl() { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(mDate.getTimeInMillis()); @@ -448,6 +501,9 @@ public class DateTimePicker extends FrameLayout { mDateSpinner.invalidate(); } + /** + * 更新AM/PM控件。 + */ private void updateAmPmControl() { if (mIs24HourView) { mAmPmSpinner.setVisibility(View.GONE); @@ -458,6 +514,9 @@ public class DateTimePicker extends FrameLayout { } } + /** + * 更新小时控件。 + */ private void updateHourControl() { if (mIs24HourView) { mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); @@ -469,17 +528,20 @@ public class DateTimePicker extends FrameLayout { } /** - * Set the callback that indicates the 'Set' button has been pressed. - * @param callback the callback, if null will do nothing + * 设置日期时间改变监听器。 + * @param callback 日期时间改变监听器 */ public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { mOnDateTimeChangedListener = callback; } + /** + * 通知日期时间改变。 + */ private void onDateTimeChanged() { if (mOnDateTimeChangedListener != null) { mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); } } -} +} \ No newline at end of file diff --git a/src/java/net/micode/notes/ui/DateTimePickerDialog.java b/src/java/net/micode/notes/ui/DateTimePickerDialog.java index 2c47ba4..f92ecc3 100644 --- a/src/java/net/micode/notes/ui/DateTimePickerDialog.java +++ b/src/java/net/micode/notes/ui/DateTimePickerDialog.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -29,62 +29,107 @@ import android.content.DialogInterface.OnClickListener; import android.text.format.DateFormat; import android.text.format.DateUtils; +/** + * DateTimePickerDialog 类用于创建日期和时间选择对话框。 + */ public class DateTimePickerDialog extends AlertDialog implements OnClickListener { + // 当前日期 private Calendar mDate = Calendar.getInstance(); + // 是否为24小时制 private boolean mIs24HourView; + // 日期时间设置监听器 private OnDateTimeSetListener mOnDateTimeSetListener; + // 日期时间选择器 private DateTimePicker mDateTimePicker; + /** + * 日期时间设置监听器接口。 + */ public interface OnDateTimeSetListener { void OnDateTimeSet(AlertDialog dialog, long date); } + /** + * 构造函数。 + * @param context 上下文 + * @param date 当前日期的时间戳 + */ public DateTimePickerDialog(Context context, long date) { super(context); + // 创建日期时间选择器 mDateTimePicker = new DateTimePicker(context); + // 设置对话框视图 setView(mDateTimePicker); + // 设置日期时间改变监听器 mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { public void onDateTimeChanged(DateTimePicker view, int year, int month, int dayOfMonth, int hourOfDay, int minute) { + // 更新日期 mDate.set(Calendar.YEAR, year); mDate.set(Calendar.MONTH, month); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.MINUTE, minute); + // 更新对话框标题 updateTitle(mDate.getTimeInMillis()); } }); + // 设置当前日期 mDate.setTimeInMillis(date); mDate.set(Calendar.SECOND, 0); mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); + // 设置确定按钮 setButton(context.getString(R.string.datetime_dialog_ok), this); + // 设置取消按钮 setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); + // 设置24小时制 set24HourView(DateFormat.is24HourFormat(this.getContext())); + // 更新对话框标题 updateTitle(mDate.getTimeInMillis()); } + /** + * 设置是否为24小时制。 + * @param is24HourView 是否为24小时制 + */ public void set24HourView(boolean is24HourView) { mIs24HourView = is24HourView; } + /** + * 设置日期时间设置监听器。 + * @param callBack 日期时间设置监听器 + */ public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { mOnDateTimeSetListener = callBack; } + /** + * 更新对话框标题。 + * @param date 当前日期的时间戳 + */ private void updateTitle(long date) { + // 设置日期格式 int flag = DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME; - flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; + // 根据是否为24小时制设置时间格式 + flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR; + // 设置对话框标题 setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); } + /** + * 点击事件处理。 + * @param arg0 对话框 + * @param arg1 按钮ID + */ public void onClick(DialogInterface arg0, int arg1) { + // 如果设置了日期时间设置监听器,则通知日期时间已设置 if (mOnDateTimeSetListener != null) { mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); } } - } \ No newline at end of file diff --git a/src/java/net/micode/notes/ui/DropdownMenu.java b/src/java/net/micode/notes/ui/DropdownMenu.java index 613dc74..6706b22 100644 --- a/src/java/net/micode/notes/ui/DropdownMenu.java +++ b/src/java/net/micode/notes/ui/DropdownMenu.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -27,35 +27,67 @@ import android.widget.PopupMenu.OnMenuItemClickListener; import net.micode.notes.R; +/** + * DropdownMenu 类用于创建一个下拉菜单。 + */ public class DropdownMenu { + // 下拉菜单按钮 private Button mButton; + // 弹出菜单 private PopupMenu mPopupMenu; + // 菜单项 private Menu mMenu; + /** + * 构造函数。 + * @param context 上下文 + * @param button 下拉菜单按钮 + * @param menuId 菜单资源ID + */ public DropdownMenu(Context context, Button button, int menuId) { mButton = button; + // 设置按钮背景为下拉图标 mButton.setBackgroundResource(R.drawable.dropdown_icon); + // 创建弹出菜单 mPopupMenu = new PopupMenu(context, mButton); + // 获取菜单项 mMenu = mPopupMenu.getMenu(); + // 加载菜单资源 mPopupMenu.getMenuInflater().inflate(menuId, mMenu); + // 设置按钮点击事件 mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { + // 显示弹出菜单 mPopupMenu.show(); } }); } + /** + * 设置下拉菜单项点击事件监听器。 + * @param listener 菜单项点击事件监听器 + */ public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { if (mPopupMenu != null) { + // 设置弹出菜单项点击事件监听器 mPopupMenu.setOnMenuItemClickListener(listener); } } + /** + * 查找菜单项。 + * @param id 菜单项ID + * @return 菜单项 + */ public MenuItem findItem(int id) { return mMenu.findItem(id); } + /** + * 设置下拉菜单按钮标题。 + * @param title 标题 + */ public void setTitle(CharSequence title) { mButton.setText(title); } -} +} \ No newline at end of file diff --git a/src/java/net/micode/notes/ui/FoldersListAdapter.java b/src/java/net/micode/notes/ui/FoldersListAdapter.java index 96b77da..c04c24e 100644 --- a/src/java/net/micode/notes/ui/FoldersListAdapter.java +++ b/src/java/net/micode/notes/ui/FoldersListAdapter.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -28,53 +28,94 @@ import net.micode.notes.R; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; - +/** + * FoldersListAdapter 类用于创建文件夹列表的适配器。 + */ public class FoldersListAdapter extends CursorAdapter { + // 查询数据库时需要的列名 public static final String [] PROJECTION = { - NoteColumns.ID, - NoteColumns.SNIPPET + NoteColumns.ID, // 文件夹ID + NoteColumns.SNIPPET // 文件夹名称 }; + // 列索引,方便获取数据 public static final int ID_COLUMN = 0; public static final int NAME_COLUMN = 1; + /** + * 构造函数。 + * @param context 上下文 + * @param c 游标 + */ public FoldersListAdapter(Context context, Cursor c) { super(context, c); - // TODO Auto-generated constructor stub } + /** + * 创建新的视图。 + * @param context 上下文 + * @param cursor 游标 + * @param parent 父视图 + * @return 新的视图 + */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return new FolderListItem(context); } + /** + * 绑定视图。 + * @param view 视图 + * @param context 上下文 + * @param cursor 游标 + */ @Override public void bindView(View view, Context context, Cursor cursor) { if (view instanceof FolderListItem) { + // 获取文件夹名称 String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + // 绑定文件夹名称 ((FolderListItem) view).bind(folderName); } } + /** + * 获取文件夹名称。 + * @param context 上下文 + * @param position 位置 + * @return 文件夹名称 + */ public String getFolderName(Context context, int position) { Cursor cursor = (Cursor) getItem(position); return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); } + /** + * FolderListItem 类用于创建文件夹列表项。 + */ private class FolderListItem extends LinearLayout { - private TextView mName; + private TextView mName; // 文件夹名称文本视图 + /** + * 构造函数。 + * @param context 上下文 + */ public FolderListItem(Context context) { super(context); + // 加载文件夹列表项布局 inflate(context, R.layout.folder_list_item, this); + // 获取文件夹名称文本视图 mName = (TextView) findViewById(R.id.tv_folder_name); } + /** + * 绑定文件夹名称。 + * @param name 文件夹名称 + */ public void bind(String name) { - mName.setText(name); + mName.setText(name); // 设置文件夹名称 } } - -} +} \ No newline at end of file diff --git a/src/java/net/micode/notes/ui/NoteEditActivity.java b/src/java/net/micode/notes/ui/NoteEditActivity.java index 7915c4e..f16050f 100644 --- a/src/java/net/micode/notes/ui/NoteEditActivity.java +++ b/src/java/net/micode/notes/ui/NoteEditActivity.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -57,7 +57,6 @@ import android.os.Environment; import android.graphics.Bitmap; import android.graphics.Typeface; // 自带四种字体 - import net.micode.notes.R; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.TextNote; @@ -82,9 +81,9 @@ import java.util.Vector; import java.io.File; import java.io.FileOutputStream; - - - +/** + * NoteEditActivity 类用于创建和编辑便签。 + */ public class NoteEditActivity extends Activity //NOTE: extends--单继承,但可多重继承 @zhoukexing 2023/12/17 23:29 implements OnClickListener, NoteSettingChangedListener, OnTextViewChangeListener { private Intent intent; //NOTE: implements--实现接口 @zhoukexing 2023/12/17 23:24 @@ -93,11 +92,11 @@ public class NoteEditActivity extends Activity //NOTE: extends--单继承,但 * @zhoukexing 2023/12/17 23:39 */ private class HeadViewHolder { - public TextView tvModified; + public TextView tvModified; // 显示修改时间的文本视图 - public ImageView ivAlertIcon; + public ImageView ivAlertIcon; // 提醒图标的图像视图 - public TextView tvAlertDate; + public TextView tvAlertDate; // 提醒日期的文本视图 // 顶部置顶文本 public TextView tvTopText; @@ -105,9 +104,10 @@ public class NoteEditActivity extends Activity //NOTE: extends--单继承,但 // 顶部长度统计文本 public TextView tvTextNum; - public ImageView ibSetBgColor; + public ImageView ibSetBgColor; // 设置背景颜色的按钮 } + // 背景颜色选择器按钮映射 private static final Map sBgSelectorBtnsMap = new HashMap(); static { sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); @@ -117,6 +117,7 @@ public class NoteEditActivity extends Activity //NOTE: extends--单继承,但 sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); } + // 背景颜色选择器选中状态映射 private static final Map sBgSelectorSelectionMap = new HashMap(); static { sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); @@ -126,6 +127,7 @@ public class NoteEditActivity extends Activity //NOTE: extends--单继承,但 sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); } + // 字体大小选择器按钮映射 private static final Map sFontSizeBtnsMap = new HashMap(); static { sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); @@ -134,6 +136,7 @@ public class NoteEditActivity extends Activity //NOTE: extends--单继承,但 sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); } + // 字体大小选择器选中状态映射 private static final Map sFontSelectorSelectionMap = new HashMap(); static { sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); @@ -142,47 +145,44 @@ public class NoteEditActivity extends Activity //NOTE: extends--单继承,但 sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); } - - - private static final String TAG = "NoteEditActivity"; - private static int mMaxRevokeTimes = 10; + private static int mMaxRevokeTimes = 10; // 最大撤销次数 - private HeadViewHolder mNoteHeaderHolder; + private HeadViewHolder mNoteHeaderHolder; // 便签头部视图的持有者 - private View mHeadViewPanel; + private View mHeadViewPanel; // 头部视图面板 - private View mNoteBgColorSelector; + private View mNoteBgColorSelector; // 便签背景颜色选择器 - private View mFontSizeSelector; + private View mFontSizeSelector; // 字体大小选择器 - private EditText mNoteEditor; + private EditText mNoteEditor; // 便签编辑器 - private View mNoteEditorPanel; + private View mNoteEditorPanel; // 便签编辑器面板 - private WorkingNote mWorkingNote; + private WorkingNote mWorkingNote; // 正在编辑的便签 - private SharedPreferences mSharedPrefs; - private int mFontSizeId; - private int mFontStyleId; + private SharedPreferences mSharedPrefs; // 共享偏好设置 + private int mFontSizeId; // 字体大小ID + private int mFontStyleId; // 字体样式ID - private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; - private static final String PREFERENCE_FONT_STYLE = "pref_font_style"; + private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; // 字体大小偏好设置键 + private static final String PREFERENCE_FONT_STYLE = "pref_font_style"; // 字体样式偏好设置键 - private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; + private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; // 快捷方式图标标题最大长度 - public static final String TAG_CHECKED = String.valueOf('\u221A'); - public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); + public static final String TAG_CHECKED = String.valueOf('\u221A'); // 已选中标签 + public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); // 未选中标签 - private LinearLayout mEditTextList; + private LinearLayout mEditTextList; // 编辑文本列表 - private String mUserQuery; - private Pattern mPattern; + private String mUserQuery; // 用户查询 + private Pattern mPattern; // 正则表达式模式 // 存储改变的数据 private Vector mHistory = new Vector(mMaxRevokeTimes); - private boolean mIsRvoke; + private boolean mIsRvoke; // 是否撤销 /*--- 以上是此类中的数据区,以下是方法区 ---*/ diff --git a/src/java/net/micode/notes/ui/NoteEditText.java b/src/java/net/micode/notes/ui/NoteEditText.java index 3d7e3fe..fe44890 100644 --- a/src/java/net/micode/notes/ui/NoteEditText.java +++ b/src/java/net/micode/notes/ui/NoteEditText.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -37,121 +37,161 @@ import net.micode.notes.R; import java.util.HashMap; import java.util.Map; +/** + * 自定义的便签编辑文本框,扩展自EditText。 + * 提供了对文本编辑的特殊处理,如删除、添加文本框、创建上下文菜单等。 + */ public class NoteEditText extends EditText { - private static final String TAG = "NoteEditText"; - private int mIndex; - private int mSelectionStartBeforeDelete; + private static final String TAG = "NoteEditText"; // 日志标签 + private int mIndex; // 当前文本框的索引 + private int mSelectionStartBeforeDelete; // 删除前的选择起始位置 - private static final String SCHEME_TEL = "tel:" ; - private static final String SCHEME_HTTP = "http:" ; - private static final String SCHEME_EMAIL = "mailto:" ; + // 定义几种URL协议的前缀 + private static final String SCHEME_TEL = "tel:"; // 电话 + private static final String SCHEME_HTTP = "http:"; // 网络 + private static final String SCHEME_EMAIL = "mailto:"; // 邮箱 + // URL协议到资源ID的映射 private static final Map sSchemaActionResMap = new HashMap(); static { - sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); - sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); - sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); + sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); // 电话链接文本 + sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); // 网络链接文本 + sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); // 邮箱链接文本 } /** - * Call by the {@link NoteEditActivity} to delete or add edit text + * 文本框变化监听器接口。 + * 用于在文本框内容发生变化时通知外部。 */ public interface OnTextViewChangeListener { /** - * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens - * and the text is null + * 当文本框被删除时调用。 + * @param index 文本框的索引 + * @param text 被删除的文本内容 */ void onEditTextDelete(int index, String text); /** - * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} - * happen + * 当文本框后添加新的文本框时调用。 + * @param index 新文本框的索引 + * @param text 新文本框的初始文本内容 */ void onEditTextEnter(int index, String text); /** - * Hide or show item option when text change + * 当文本框内容发生变化时调用。 + * @param index 文本框的索引 + * @param hasText 文本框是否包含文本 */ void onTextChange(int index, boolean hasText); } - private OnTextViewChangeListener mOnTextViewChangeListener; + private OnTextViewChangeListener mOnTextViewChangeListener; // 文本框变化监听器 + /** + * 构造函数。 + * @param context 上下文 + */ public NoteEditText(Context context) { super(context, null); - mIndex = 0; + mIndex = 0; // 默认索引为0 } + /** + * 设置文本框的索引。 + * @param index 文本框的索引 + */ public void setIndex(int index) { mIndex = index; } + /** + * 设置文本框变化监听器。 + * @param listener 文本框变化监听器 + */ public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { mOnTextViewChangeListener = listener; } + /** + * 构造函数。 + * @param context 上下文 + * @param attrs 属性集 + */ public NoteEditText(Context context, AttributeSet attrs) { super(context, attrs, android.R.attr.editTextStyle); } + /** + * 构造函数。 + * @param context 上下文 + * @param attrs 属性集 + * @param defStyle 默认样式 + */ public NoteEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - // TODO Auto-generated constructor stub } + /** + * 处理触摸事件。 + * 当用户触摸文本框时,根据触摸位置设置文本选择位置。 + * @param event 触摸事件 + * @return 是否处理了事件 + */ @Override public boolean onTouchEvent(MotionEvent event) { - switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: - - int x = (int) event.getX(); - int y = (int) event.getY(); - x -= getTotalPaddingLeft(); - y -= getTotalPaddingTop(); - x += getScrollX(); - y += getScrollY(); - - Layout layout = getLayout(); - int line = layout.getLineForVertical(y); - int off = layout.getOffsetForHorizontal(line, x); - Selection.setSelection(getText(), off); - break; + if (event.getAction() == MotionEvent.ACTION_DOWN) { + int x = (int) event.getX(); + int y = (int) event.getY(); + x -= getTotalPaddingLeft(); + y -= getTotalPaddingTop(); + x += getScrollX(); + y += getScrollY(); + + Layout layout = getLayout(); + int line = layout.getLineForVertical(y); + int off = layout.getOffsetForHorizontal(line, x); + Selection.setSelection(getText(), off); // 设置文本选择位置 } - return super.onTouchEvent(event); } + /** + * 处理按键按下事件。 + * 主要处理回车键和删除键的按下。 + * @param keyCode 按键代码 + * @param event 按键事件 + * @return 是否处理了事件 + */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_ENTER: if (mOnTextViewChangeListener != null) { - return false; + return false; // 不处理回车键,交由监听器处理 } break; case KeyEvent.KEYCODE_DEL: - mSelectionStartBeforeDelete = getSelectionStart(); - break; - default: + mSelectionStartBeforeDelete = getSelectionStart(); // 记录删除前的选择起始位置 break; } return super.onKeyDown(keyCode, event); } + /** - * @method: onKeyUp - * @description: 处理键盘输入的键。对于delete键和enter键做了异常处理。 - * 编辑时会进入,按返回键退出时也会进入 - * @date: 2023/12/21 0:28 - * @author: zhoukexing - * @param: [keyCode, event] - * @return: boolean + * 处理按键抬起事件。 + * 主要处理删除键和回车键的抬起。 + * @param keyCode 按键代码 + * @param event 按键事件 + * @return 是否处理了事件 */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { - switch(keyCode) { - case KeyEvent.KEYCODE_DEL: // delete键的号为67 @zhoukexing 2023/12/21 0:31 + switch (keyCode) { + case KeyEvent.KEYCODE_DEL: // 删除键 if (mOnTextViewChangeListener != null) { - if (0 == mSelectionStartBeforeDelete && mIndex != 0) { + if (mSelectionStartBeforeDelete == 0 && mIndex != 0) { + // 如果删除前的选择起始位置为0且不是第一个文本框,则删除当前文本框 mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); return true; } @@ -159,22 +199,27 @@ public class NoteEditText extends EditText { Log.d(TAG, "OnTextViewChangeListener was not seted"); } break; - case KeyEvent.KEYCODE_ENTER: // enter键的号为66 @zhoukexing 2023/12/21 0:31 + case KeyEvent.KEYCODE_ENTER: // 回车键 if (mOnTextViewChangeListener != null) { int selectionStart = getSelectionStart(); String text = getText().subSequence(selectionStart, length()).toString(); - setText(getText().subSequence(0, selectionStart)); - mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); + setText(getText().subSequence(0, selectionStart)); // 删除回车键后的内容 + mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); // 添加新的文本框 } else { Log.d(TAG, "OnTextViewChangeListener was not seted"); } break; - default: - break; } return super.onKeyUp(keyCode, event); } + /** + * 处理焦点变化事件。 + * 当文本框失去焦点且内容为空时,通知监听器文本框内容为空。 + * @param focused 是否获得焦点 + * @param direction 焦点变化方向 + * @param previouslyFocusedRect 之前获得焦点的矩形区域 + */ @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { if (mOnTextViewChangeListener != null) { @@ -187,39 +232,4 @@ public class NoteEditText extends EditText { super.onFocusChanged(focused, direction, previouslyFocusedRect); } - @Override - protected void onCreateContextMenu(ContextMenu menu) { - if (getText() instanceof Spanned) { - int selStart = getSelectionStart(); - int selEnd = getSelectionEnd(); - - int min = Math.min(selStart, selEnd); - int max = Math.max(selStart, selEnd); - - final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); - if (urls.length == 1) { - int defaultResId = 0; - for(String schema: sSchemaActionResMap.keySet()) { - if(urls[0].getURL().indexOf(schema) >= 0) { - defaultResId = sSchemaActionResMap.get(schema); - break; - } - } - - if (defaultResId == 0) { - defaultResId = R.string.note_link_other; - } - - menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( - new OnMenuItemClickListener() { - public boolean onMenuItemClick(MenuItem item) { - // goto a new intent - urls[0].onClick(NoteEditText.this); - return true; - } - }); - } - } - super.onCreateContextMenu(menu); - } -} + \ No newline at end of file diff --git a/src/java/net/micode/notes/ui/NoteItemData.java b/src/java/net/micode/notes/ui/NoteItemData.java index bd04f74..f1884e8 100644 --- a/src/java/net/micode/notes/ui/NoteItemData.java +++ b/src/java/net/micode/notes/ui/NoteItemData.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -25,8 +25,12 @@ import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.tool.DataUtils; - +/** + * NoteItemData 类用于封装便签项的数据。 + * 它从数据库游标中提取便签的相关信息,并提供一些辅助方法来判断便签的状态和类型。 + */ public class NoteItemData { + // 定义查询便签数据库时需要的列 static final String [] PROJECTION = new String [] { NoteColumns.ID, NoteColumns.ALERTED_DATE, @@ -43,6 +47,7 @@ public class NoteItemData { NoteColumns.TOP, }; + // 定义列的索引 private static final int ID_COLUMN = 0; private static final int ALERTED_DATE_COLUMN = 1; private static final int BG_COLOR_ID_COLUMN = 2; @@ -55,11 +60,9 @@ public class NoteItemData { private static final int TYPE_COLUMN = 9; private static final int WIDGET_ID_COLUMN = 10; private static final int WIDGET_TYPE_COLUMN = 11; - private static final int TOP_STATE_COLUMN = 12; + private static final int TOP_STATE_COLUMN = 12; - /** 以下这些数据,对照着NotesDatabaseHelper.java看 - * 都是数据行里设置好的属性 - * @zhoukexing 2023/12/25 20:22 */ + // 便签项的数据字段 private long mId; private long mAlertDate; private int mBgColorId; @@ -76,6 +79,7 @@ public class NoteItemData { private String mName; private String mPhoneNumber; + // 便签项的位置状态 private boolean mIsLastItem; private boolean mIsFirstItem; private boolean mIsOnlyOneItem; @@ -83,37 +87,33 @@ public class NoteItemData { private boolean mIsMultiNotesFollowingFolder; /** - * @method: NoteItemData - * @description: 描述一下方法的作用 - * @date: 2023/12/25 19:58 - * @author: zhoukexing - * @param: [context, cursor] - * @return: + * 构造函数,从游标中提取便签项的数据。 + * @param context 上下文 + * @param cursor 数据库游标 */ - public NoteItemData(Context context, Cursor cursor) { // 把cursor理解为这样一个指针,指向一个表格 @zhoukexing 2023/12/25 20:12 - mId = cursor.getLong(ID_COLUMN); // 可以根据传入的列号获取到表格里对应列的值 @zhoukexing 2023/12/25 20:12 - mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); - mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); - mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); - mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; - mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); - mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); - mParentId = cursor.getLong(PARENT_ID_COLUMN); - mSnippet = cursor.getString(SNIPPET_COLUMN); + public NoteItemData(Context context, Cursor cursor) { + mId = cursor.getLong(ID_COLUMN); // 获取便签ID + mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); // 获取提醒日期 + mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); // 获取背景颜色ID + mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); // 获取创建日期 + mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0); // 是否有附件 + mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); // 获取修改日期 + mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); // 获取便签数量 + mParentId = cursor.getLong(PARENT_ID_COLUMN); // 获取父便签ID + mSnippet = cursor.getString(SNIPPET_COLUMN); // 获取便签摘要 mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( - NoteEditActivity.TAG_UNCHECKED, ""); - mType = cursor.getInt(TYPE_COLUMN); - mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); - mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); - mTop = cursor.getInt(TOP_STATE_COLUMN); + NoteEditActivity.TAG_UNCHECKED, ""); // 去除摘要中的标签 + mType = cursor.getInt(TYPE_COLUMN); // 获取便签类型 + mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); // 获取小部件ID + mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); // 获取小部件类型 + mTop = cursor.getInt(TOP_STATE_COLUMN); // 获取置顶状态 mPhoneNumber = ""; - if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { //Q: 文件夹为什么有电话记录之说?怎么是通过一个便签的父文件夹来判断便签内有无电话号码?@zkx 2023/12/25 - mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); - // 根据电话号码锁定联系人名称,若不在联系人里,直接使用电话号码 @zhoukexing 2023/12/25 20:17 - if (!TextUtils.isEmpty(mPhoneNumber)) { - mName = Contact.getContact(context, mPhoneNumber); - if (mName == null) { + if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { // 如果便签属于通话记录文件夹 + mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); // 获取电话号码 + if (!TextUtils.isEmpty(mPhoneNumber)) { // 如果电话号码不为空 + mName = Contact.getContact(context, mPhoneNumber); // 获取联系人名称 + if (mName == null) { // 如果联系人名称为空,则使用电话号码 mName = mPhoneNumber; } } @@ -122,70 +122,114 @@ public class NoteItemData { if (mName == null) { mName = ""; } - checkPostion(cursor); + checkPostion(cursor); // 检查便签项的位置状态 } + /** + * 检查便签项的位置状态。 + * @param cursor 数据库游标 + */ private void checkPostion(Cursor cursor) { - mIsLastItem = cursor.isLast() ? true : false; - mIsFirstItem = cursor.isFirst() ? true : false; - mIsOnlyOneItem = (cursor.getCount() == 1); + mIsLastItem = cursor.isLast(); // 是否是最后一个便签项 + mIsFirstItem = cursor.isFirst(); // 是否是第一个便签项 + mIsOnlyOneItem = (cursor.getCount() == 1); // 是否只有一个便签项 mIsMultiNotesFollowingFolder = false; mIsOneNoteFollowingFolder = false; - if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { + if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { // 如果是便签且不是第一个便签项 int position = cursor.getPosition(); - if (cursor.moveToPrevious()) { + if (cursor.moveToPrevious()) { // 移动到前一个便签项 if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER - || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { - if (cursor.getCount() > (position + 1)) { - mIsMultiNotesFollowingFolder = true; + || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { // 如果前一个便签项是文件夹或系统便签 + if (cursor.getCount() > (position + 1)) { // 如果便签项数量大于当前便签项的位置+1 + mIsMultiNotesFollowingFolder = true; // 多个便签项跟随文件夹 } else { - mIsOneNoteFollowingFolder = true; + mIsOneNoteFollowingFolder = true; // 一个便签项跟随文件夹 } } - if (!cursor.moveToNext()) { + if (!cursor.moveToNext()) { // 移动回当前便签项 throw new IllegalStateException("cursor move to previous but can't move back"); } } } } + /** + * 判断是否是跟随文件夹的单个便签项。 + * @return 是否是跟随文件夹的单个便签项 + */ public boolean isOneFollowingFolder() { return mIsOneNoteFollowingFolder; } + /** + * 判断是否是跟随文件夹的多个便签项。 + * @return 是否是跟随文件夹的多个便签项 + */ public boolean isMultiFollowingFolder() { return mIsMultiNotesFollowingFolder; } + /** + * 判断是否是最后一个便签项。 + * @return 是否是最后一个便签项 + */ public boolean isLast() { return mIsLastItem; } + /** + * 获取通话记录的联系人名称。 + * @return 联系人名称 + */ public String getCallName() { return mName; } + /** + * 判断是否是第一个便签项。 + * @return 是否是第一个便签项 + */ public boolean isFirst() { return mIsFirstItem; } + /** + * 判断是否是唯一的便签项。 + * @return 是否是唯一的便签项 + */ public boolean isSingle() { return mIsOnlyOneItem; } + /** + * 获取便签项的置顶状态。 + * @return 置顶状态 + */ public int getTop(){ return mTop; } + /** + * 获取便签项的ID。 + * @return 便签项的ID + */ public long getId() { return mId; } + /** + * 获取便签项的提醒日期。 + * @return 提醒日期 + */ public long getAlertDate() { return mAlertDate; } + /** + * 获取便签项的创建日期。 + * @return 创建日期 + */ public long getCreatedDate() { return mCreatedDate; }