diff --git a/README.md b/README.md index 872dc6d..bd5ef54 100644 --- a/README.md +++ b/README.md @@ -2,3 +2,5 @@ __________ - 2023/3/24 创建了基本结构,初始化了项目 - 2023/3/31 撰写了泛读报告 +- 2023/4/07 修复了菜单栏的BUG +- 2023/4/10 完成全部代码注释 \ No newline at end of file diff --git a/doc/doc.md b/doc/doc.md deleted file mode 100644 index fe19484..0000000 --- a/doc/doc.md +++ /dev/null @@ -1 +0,0 @@ -这里存放各类文档 \ No newline at end of file diff --git a/doc/精读代码(注释)/周卢东注释/tool/BackupUtils.java b/doc/精读代码(注释)/周卢东注释/tool/BackupUtils.java new file mode 100644 index 0000000..3b57f49 --- /dev/null +++ b/doc/精读代码(注释)/周卢东注释/tool/BackupUtils.java @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.tool; + +public class 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/doc/精读代码(注释)/周卢东注释/tool/DataUtils.java b/doc/精读代码(注释)/周卢东注释/tool/DataUtils.java new file mode 100644 index 0000000..c7ff6cf --- /dev/null +++ b/doc/精读代码(注释)/周卢东注释/tool/DataUtils.java @@ -0,0 +1,279 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.tool; + +public class DataUtils { + public static final String TAG = "DataUtils"; + public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { //直接删除多个笔记 + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + } + if (ids.size() == 0) { + Log.d(TAG, "no id is in the hashset"); + return true; + } + + ArrayList operationList = new ArrayList(); //提供一个任务列表 + for (long id : ids) { + if(id == Notes.ID_ROOT_FOLDER) { + Log.e(TAG, "Don't delete system folder root"); + continue; + } //如果发现是根文件夹,则不删除 + ContentProviderOperation.Builder builder = ContentProviderOperation + .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); //用newDelete实现删除功能 + operationList.add(builder.build()); // + } + try { + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);//主机名(或叫Authority)用于唯一标识这个ContentProvider,外部调用者可以根据这个标识来找到它。 + //数据库事务,数据库事务是由一组数据库操作序列组成,事务作为一个整体被执行 + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + return false; + } + return true; + } catch (RemoteException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } catch (OperationApplicationException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + } + return false; + } + + public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.PARENT_ID, desFolderId); + 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); //对需要移动的便签进行数据更新,然后用update实现 + } + + 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)); //通过withAppendedId方法,为该Uri加上ID + builder.withValue(NoteColumns.PARENT_ID, folderId); + builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); + operationList.add(builder.build()); + }//将ids里包含的每一列的数据逐次加入到operationList中,等待最后的批量处理 + + try { + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); //applyBatch一次性处理一个操作列表 + 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; + } + + /** + * 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); //筛选条件:源文件不为trash folder + + int count = 0; + if(cursor != null) { + if(cursor.moveToFirst()) { + try { + count = cursor.getInt(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "get folder count failed:" + e.toString()); + } finally { + cursor.close(); + } + } + } + return count; + } + + public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), //通过withAppendedId方法,为该Uri加上ID + null, + NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, + new String [] {String.valueOf(type)}, + null); //查询条件:type符合,且不属于垃圾文件夹 + + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) {//用getcount函数判断cursor是否为空 + exist = true; + } + cursor.close(); + } + return exist; + } + + public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + null, null, null, null); + + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + } + cursor.close(); + } + return exist; + } + + public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), + null, null, null, null); + + boolean exist = false; + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + } + cursor.close(); + } + return exist; + } + + public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.SNIPPET + "=?", + new String[] { name }, null); + //通过名字查询文件是否存在 + boolean exist = false; + if(cursor != null) { + if(cursor.getCount() > 0) { + exist = true; + } + cursor.close(); + } + return exist; + } + + 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是传入的folderId; + + HashSet set = null; + if (c != null) { + if (c.moveToFirst()) { + set = new HashSet(); + do { + try { + AppWidgetAttribute widget = new AppWidgetAttribute(); + widget.widgetId = c.getInt(0); //0对应的NoteColumns.WIDGET_ID + widget.widgetType = c.getInt(1); //1对应的NoteColumns.WIDGET_TYPE + set.add(widget); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, e.toString()); + } + } while (c.moveToNext()); //查询下一条 + } + c.close(); + } + return set; + } + + public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + new String [] { CallNote.PHONE_NUMBER }, + CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", + new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, + null); + + if (cursor != null && cursor.moveToFirst()) { + try { + return cursor.getString(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "Get call number fails " + e.toString()); + } finally { + cursor.close(); + } + } + return ""; + } + + 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); + //通过数据库操作,查询条件是(callDate和phoneNumber匹配传入参数的值) + + if (cursor != null) { + if (cursor.moveToFirst()) { + try { + return cursor.getLong(0); //0对应的CallNote.NOTE_ID + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "Get call note id fails " + e.toString()); + } + } + cursor.close(); + } + return 0; + } + + 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);//查询条件:noteId + + if (cursor != null) { + String snippet = ""; + if (cursor.moveToFirst()) { + snippet = cursor.getString(0); + } + cursor.close(); + return snippet; + } + throw new IllegalArgumentException("Note is not found with id: " + noteId); + } + public static String getFormattedSnippet(String snippet) { //对字符串进行格式处理,将字符串两头的空格去掉,同时将换行符去掉 + if (snippet != null) { + snippet = snippet.trim(); + int index = snippet.indexOf('\n'); + if (index != -1) { + snippet = snippet.substring(0, index); + } + } + return snippet; + } + +} \ No newline at end of file diff --git a/doc/精读代码(注释)/周卢东注释/tool/GTaskStringUtils.java b/doc/精读代码(注释)/周卢东注释/tool/GTaskStringUtils.java new file mode 100644 index 0000000..8f82926 --- /dev/null +++ b/doc/精读代码(注释)/周卢东注释/tool/GTaskStringUtils.java @@ -0,0 +1,115 @@ +/* + * 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. + */ + +//简介:定义了很多的静态字符串,目的就是为了提供jsonObject中相应字符串的"key"。把这些静态的定义单独写到了一个类里面,这是非常好的编程规范 +package net.micode.notes.tool; + +//这个类就是定义了一堆static string,实际就是为jsonObject提供Key,把这些定义全部写到一个类里,方便查看管理,是一个非常好的编程习惯 +public class GTaskStringUtils { + + public final static String GTASK_JSON_ACTION_ID = "action_id"; + + public final static String GTASK_JSON_ACTION_LIST = "action_list"; + + public final static String GTASK_JSON_ACTION_TYPE = "action_type"; + + public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; + + public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; + + public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; + + public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; + + public final static String GTASK_JSON_CREATOR_ID = "creator_id"; + + public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; + + public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; + + public final static String GTASK_JSON_COMPLETED = "completed"; + + public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; + + public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; + + public final static String GTASK_JSON_DELETED = "deleted"; + + public final static String GTASK_JSON_DEST_LIST = "dest_list"; + + public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; + + public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; + + public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; + + public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; + + public final static String GTASK_JSON_GET_DELETED = "get_deleted"; + + public final static String GTASK_JSON_ID = "id"; + + public final static String GTASK_JSON_INDEX = "index"; + + public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; + + public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; + + public final static String GTASK_JSON_LIST_ID = "list_id"; + + public final static String GTASK_JSON_LISTS = "lists"; + + public final static String GTASK_JSON_NAME = "name"; + + public final static String GTASK_JSON_NEW_ID = "new_id"; + + public final static String GTASK_JSON_NOTES = "notes"; + + public final static String GTASK_JSON_PARENT_ID = "parent_id"; + + public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; + + public final static String GTASK_JSON_RESULTS = "results"; + + public final static String GTASK_JSON_SOURCE_LIST = "source_list"; + + public final static String GTASK_JSON_TASKS = "tasks"; + + public final static String GTASK_JSON_TYPE = "type"; + + public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; + + public final static String GTASK_JSON_TYPE_TASK = "TASK"; + + public final static String GTASK_JSON_USER = "user"; + + 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"; + + 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/doc/精读代码(注释)/周卢东注释/tool/ResourceParser.java b/doc/精读代码(注释)/周卢东注释/tool/ResourceParser.java new file mode 100644 index 0000000..3d50b41 --- /dev/null +++ b/doc/精读代码(注释)/周卢东注释/tool/ResourceParser.java @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.tool; + +/*简介:字面意义是资源分析器,实际上就是获取资源并且在程序中使用,比如颜色图片等 + * 实现方法:主要利用R.java这个类,其中包括 + * R.id 组件资源引用 + * R.drawable 图片资源 (被使用) + * R.layout 布局资源 + * R.menu 菜单资源 + * R.String 文字资源 + * R.style 主题资源 (被使用) + * 在按顺序设置好相应的id后,就可以编写简单的getXXX函数获取需要的资源 + * + * 特殊的变量 : + * @BG_DEFAULT_COLOR 默认背景颜色(黄) + * BG_DEFAULT_FONT_SIZE 默认文本大小(中) + */ + +public class ResourceParser { + + public static final int YELLOW = 0; + public static final int BLUE = 1; + public static final int WHITE = 2; + public static final int GREEN = 3; + public static final int RED = 4; + + public static final int BG_DEFAULT_COLOR = YELLOW; + + public static final int TEXT_SMALL = 0; + public static final int TEXT_MEDIUM = 1; + public static final int TEXT_LARGE = 2; + public static final int TEXT_SUPER = 3; + + public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; + + public static class NoteBgResources { + private final static int [] BG_EDIT_RESOURCES = new int [] { + R.drawable.edit_yellow, + R.drawable.edit_blue, + R.drawable.edit_white, + R.drawable.edit_green, + R.drawable.edit_red + }; + + private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] { + R.drawable.edit_title_yellow, + R.drawable.edit_title_blue, + R.drawable.edit_title_white, + R.drawable.edit_title_green, + R.drawable.edit_title_red + }; + + public static int getNoteBgResource(int id) { + return BG_EDIT_RESOURCES[id]; + } + + public static int getNoteTitleBgResource(int id) { + return BG_EDIT_TITLE_RESOURCES[id]; + } + } + //直接获取默认的背景颜色。看不太懂,这个PREFERENCE_SET_BG_COLOR_KEY是个final string,也就是说getBoolean肯定执行else,为什么要这么写 + public static int getDefaultBgId(Context context) { + if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( + NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { + return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length); + } else { + return BG_DEFAULT_COLOR; + } + } + + public static class NoteItemBgResources { + private final static int [] BG_FIRST_RESOURCES = new int [] { + R.drawable.list_yellow_up, + R.drawable.list_blue_up, + R.drawable.list_white_up, + R.drawable.list_green_up, + R.drawable.list_red_up + }; + + private final static int [] BG_NORMAL_RESOURCES = new int [] { + R.drawable.list_yellow_middle, + R.drawable.list_blue_middle, + R.drawable.list_white_middle, + R.drawable.list_green_middle, + R.drawable.list_red_middle + }; + + private final static int [] BG_LAST_RESOURCES = new int [] { + R.drawable.list_yellow_down, + R.drawable.list_blue_down, + R.drawable.list_white_down, + R.drawable.list_green_down, + R.drawable.list_red_down, + }; + + private final static int [] BG_SINGLE_RESOURCES = new int [] { + R.drawable.list_yellow_single, + R.drawable.list_blue_single, + R.drawable.list_white_single, + R.drawable.list_green_single, + R.drawable.list_red_single + }; + + public static int getNoteBgFirstRes(int id) { + return BG_FIRST_RESOURCES[id]; + } + + public static int getNoteBgLastRes(int id) { + return BG_LAST_RESOURCES[id]; + } + + public static int getNoteBgSingleRes(int id) { + return BG_SINGLE_RESOURCES[id]; + } + + public static int getNoteBgNormalRes(int id) { + return BG_NORMAL_RESOURCES[id]; + } + + public static int getFolderBgRes() { + return R.drawable.list_folder; + } + } + + public static class WidgetBgResources { + 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, + }; + + public static int getWidget2xBgResource(int id) { + return BG_2X_RESOURCES[id]; + } + + 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 + }; + + 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大于资源总量,若如此,则自动返回默认的设置结果 + public static int getTexAppearanceResource(int id) { + /** + * HACKME: Fix bug of store the resource id in shared preference. + * The id may larger than the length of resources, in this case, + * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} + */ + if (id >= TEXTAPPEARANCE_RESOURCES.length) { + return BG_DEFAULT_FONT_SIZE; + } + return TEXTAPPEARANCE_RESOURCES[id]; + } + + public static int getResourcesSize() { + return TEXTAPPEARANCE_RESOURCES.length; + } + } +} \ No newline at end of file diff --git a/doc/精读代码(注释)/孔维屿注释/data/Contact.java b/doc/精读代码(注释)/孔维屿注释/data/Contact.java new file mode 100644 index 0000000..706f607 --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/data/Contact.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.data; + +import android.content.Context; +import android.database.Cursor; +import android.provider.ContactsContract.CommonDataKinds.Phone; +import android.provider.ContactsContract.Data; +import android.telephony.PhoneNumberUtils; +import android.util.Log; + +import java.util.HashMap; + +/** + *联系人类,主要用于获取电话号码对应的联系人姓名 + */ +public class Contact { + + /** + * 声明了一个静态变量sContactCache,用于缓存联系人信息 + */ + private static HashMap sContactCache; + + /** + * 声明了一个静态常量TAG,用于在日志中标识该类名。 + */ + private static final String TAG = "Contact"; + + /** + 定义了一个SQL查询字符串,用于查询满足指定条件的联系人信息。 + */ + private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER + + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + + " AND " + Data.RAW_CONTACT_ID + " IN " + + "(SELECT raw_contact_id " + + " FROM phone_lookup" + + " WHERE min_match = '+')"; + + /** + * 公共方法,用于获取给定电话号码所对应联系人的姓名。 + * @param context + * @param phoneNumber + * @return + */ + public static String getContact(Context context, String phoneNumber) { + if(sContactCache == null) { + sContactCache = new HashMap(); + } + + if(sContactCache.containsKey(phoneNumber)) { + return sContactCache.get(phoneNumber); + } + + String selection = CALLER_ID_SELECTION.replace("+", + PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); + Cursor cursor = context.getContentResolver().query( + Data.CONTENT_URI, + new String [] { Phone.DISPLAY_NAME }, + selection, + new String[] { phoneNumber }, + null); + + if (cursor != null && cursor.moveToFirst()) { + try { + String name = cursor.getString(0); + sContactCache.put(phoneNumber, name); + return name; + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, " Cursor get string error " + e.toString()); + return null; + } finally { + cursor.close(); + } + } else { + Log.d(TAG, "No contact matched with number:" + phoneNumber); + return null; + } + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/data/Notes.java b/doc/精读代码(注释)/孔维屿注释/data/Notes.java new file mode 100644 index 0000000..8de418f --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/data/Notes.java @@ -0,0 +1,309 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.data; + +import android.net.Uri; +public class Notes { + + /** + * 这是一个静态的字符串常量,表示内容提供者的授权标识。 + */ + public static final String AUTHORITY = "micode_notes"; + + /** + * 这是一个静态的字符串常量,用于在日志中标识该类名。 + */ + public static final String TAG = "Notes"; + + //这些静态的整数常量表示不同类型的便签笔记。 + public static final int TYPE_NOTE = 0; + public static final int TYPE_FOLDER = 1; + public static final int TYPE_SYSTEM = 2; + + /** + * Following IDs are system folders' identifiers + * {@link Notes#ID_ROOT_FOLDER } is default folder + * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder + * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records + */ + //这些静态的整数常量表示不同类型的系统文件夹的标识符 + public static final int ID_ROOT_FOLDER = 0; + public static final int ID_TEMPARAY_FOLDER = -1; + public static final int ID_CALL_RECORD_FOLDER = -2; + public static final int ID_TRASH_FOLER = -3; + + //这些静态的字符串常量表示传递给Intent对象的额外数据的键名。 + public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; + public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; + public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; + public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; + public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; + public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; + + //这些静态的整数常量表示小部件的类型。 + public static final int TYPE_WIDGET_INVALIDE = -1; + public static final int TYPE_WIDGET_2X = 0; + public static final int TYPE_WIDGET_4X = 1; + + /** + * 这是一个静态的内部类,定义了一些用于数据类型的常量字符串。 + */ + public static class DataConstants { + public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; + public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; + } + + /** + * Uri to query all notes and folders + * 这静态的Uri常量表示查询的基础地址。 + */ + public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); + + /** + * Uri to query data + * 这静态的Uri常量表示查询的基础地址。 + */ + public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); + + /** + * 标准接口,声明了列名。 + */ + public interface NoteColumns { + /** + * The unique ID for a row + *

Type: INTEGER (long)

+ */ + public static final String ID = "_id"; + + /** + * The parent's id for note or folder + *

Type: INTEGER (long)

+ */ + public static final String PARENT_ID = "parent_id"; + + /** + * Created data for note or folder + *

Type: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * Latest modified date + *

Type: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + + + /** + * Alert date + *

Type: INTEGER (long)

+ */ + public static final String ALERTED_DATE = "alert_date"; + + /** + * Folder's name or text content of note + *

Type: TEXT

+ */ + public static final String SNIPPET = "snippet"; + + /** + * Note's widget id + *

Type: INTEGER (long)

+ */ + public static final String WIDGET_ID = "widget_id"; + + /** + * Note's widget type + *

Type: INTEGER (long)

+ */ + public static final String WIDGET_TYPE = "widget_type"; + + /** + * Note's background color's id + *

Type: INTEGER (long)

+ */ + public static final String BG_COLOR_ID = "bg_color_id"; + + /** + * For text note, it doesn't has attachment, for multi-media + * note, it has at least one attachment + *

Type: INTEGER

+ */ + public static final String HAS_ATTACHMENT = "has_attachment"; + + /** + * Folder's count of notes + *

Type: INTEGER (long)

+ */ + public static final String NOTES_COUNT = "notes_count"; + + /** + * The file type: folder or note + *

Type: INTEGER

+ */ + public static final String TYPE = "type"; + + /** + * The last sync id + *

Type: INTEGER (long)

+ */ + public static final String SYNC_ID = "sync_id"; + + /** + * Sign to indicate local modified or not + *

Type: INTEGER

+ */ + public static final String LOCAL_MODIFIED = "local_modified"; + + /** + * Original parent id before moving into temporary folder + *

Type : INTEGER

+ */ + public static final String ORIGIN_PARENT_ID = "origin_parent_id"; + + /** + * The gtask id + *

Type : TEXT

+ */ + public static final String GTASK_ID = "gtask_id"; + + /** + * The version code + *

Type : INTEGER (long)

+ */ + public static final String VERSION = "version"; + } + + /** + * 这些是标准接口,声明了数据类型。 + */ + public interface DataColumns { + /** + * The unique ID for a row + *

Type: INTEGER (long)

+ */ + public static final String ID = "_id"; + + /** + * The MIME type of the item represented by this row. + *

Type: Text

+ */ + public static final String MIME_TYPE = "mime_type"; + + /** + * The reference id to note that this data belongs to + *

Type: INTEGER (long)

+ */ + public static final String NOTE_ID = "note_id"; + + /** + * Created data for note or folder + *

Type: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * Latest modified date + *

Type: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + + /** + * Data's content + *

Type: TEXT

+ */ + public static final String CONTENT = "content"; + + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * integer data type + *

Type: INTEGER

+ */ + public static final String DATA1 = "data1"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * integer data type + *

Type: INTEGER

+ */ + public static final String DATA2 = "data2"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA3 = "data3"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA4 = "data4"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA5 = "data5"; + } + + /** + * 这个静态的内部类扩展了DataColumns接口,表示不同类型的便签笔记。包含一些额外的列。 + */ + public static final class TextNote implements DataColumns { + /** + * Mode to indicate the text in check list mode or not + *

Type: Integer 1:check list mode 0: normal mode

+ */ + public static final String MODE = DATA1; + + public static final int MODE_CHECK_LIST = 1; + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); + } + + /** + * 这个静态的内部类扩展了DataColumns接口,表示不同类型的便签笔记。包含一些额外的数据类型。 + */ + public static final class CallNote implements DataColumns { + /** + * Call date for this record + *

Type: INTEGER (long)

+ */ + public static final String CALL_DATE = DATA1; + + /** + * Phone number for this record + *

Type: TEXT

+ */ + public static final String PHONE_NUMBER = DATA3; + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/data/NotesDatabaseHelper.java b/doc/精读代码(注释)/孔维屿注释/data/NotesDatabaseHelper.java new file mode 100644 index 0000000..d6dec55 --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/data/NotesDatabaseHelper.java @@ -0,0 +1,451 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.data; + +import android.content.ContentValues; +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; + +/** + * 用于打开、创建和管理Note应用程序的数据库 + */ +public class NotesDatabaseHelper extends SQLiteOpenHelper { + private static final String DB_NAME = "note.db"; + + private static final int DB_VERSION = 4; + + /** + * 这是一个接口,内部定义了一个笔记表和一个数据表的表名常量。 + */ + public interface TABLE { + public static final String NOTE = "note"; + + public static final String DATA = "data"; + } + + private static final String TAG = "NotesDatabaseHelper"; + + private static NotesDatabaseHelper mInstance; + + /** + * 该字符串表示用于创建“note”表的SQL语句。该表用于存储笔记的基本信息。 + */ + private static final String CREATE_NOTE_TABLE_SQL = + "CREATE TABLE " + TABLE.NOTE + "(" + + NoteColumns.ID + " INTEGER PRIMARY KEY," + + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + + ")"; + + /** + * SQL语句用于创建“data”表的字符串常量 + */ + private static final String CREATE_DATA_TABLE_SQL = + "CREATE TABLE " + TABLE.DATA + "(" + + DataColumns.ID + " INTEGER PRIMARY KEY," + + DataColumns.MIME_TYPE + " TEXT NOT NULL," + + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA1 + " INTEGER," + + DataColumns.DATA2 + " INTEGER," + + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + + ")"; + + /** + * SQL语句在"data"表上创建索引的字符串常量 + */ + private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = + "CREATE INDEX IF NOT EXISTS note_id_index ON " + + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; + + /** + * Increase folder's note count when move note to the folder + * 在将笔记移动到文件夹时增加文件夹的笔记计数 + */ + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = + "CREATE TRIGGER increase_folder_count_on_update "+ + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END"; + + /** + * Decrease folder's note count when move note from folder + * 在将笔记移出文件夹时减少文件夹的笔记计数 + */ + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = + "CREATE TRIGGER decrease_folder_count_on_update " + + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + + " END"; + + /** + * Increase folder's note count when insert new note to the folder + * 此触发器将在向数据库中添加新的笔记时自动触发。当向某个文件夹添加新的笔记时,此触发器将使该文件夹的“notes_count”值增加 1。 + */ + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = + "CREATE TRIGGER increase_folder_count_on_insert " + + " AFTER INSERT ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END"; + + /** + * Decrease folder's note count when delete note from the folder + * 此触发器将在从数据库中删除笔记时自动触发。当从某个文件夹删除笔记时,此触发器将使该文件夹的“notes_count”值减少 1。 + */ + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = + "CREATE TRIGGER decrease_folder_count_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0;" + + " END"; + + /** + * Update note's content when insert data with type {@link DataConstants#NOTE} + * 此触发器将在向数据库中添加一个数据记录时自动触发。 + * 当添加类型为“note”的数据记录时,此触发器将更新笔记的“snippet”列,将其设置为新增数据记录的“content”列值。 + */ + private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = + "CREATE TRIGGER update_note_content_on_insert " + + " AFTER INSERT ON " + TABLE.DATA + + " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END"; + + /** + * Update note's content when data with {@link DataConstants#NOTE} type has changed + * 此触发器将在数据库中的数据记录被更新时自动触发。 + * 当更新的数据记录类型为“note”时,此触发器将更新笔记的“snippet”列,将其设置为更新后的数据记录的“content”列的值。 + */ + private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = + "CREATE TRIGGER update_note_content_on_update " + + " AFTER UPDATE ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END"; + + /** + * Update note's content when data with {@link DataConstants#NOTE} type has deleted + * 此触发器将在从数据库中删除一个数据记录时自动触发。 + * 当被删除的数据记录类型为“note”时,此触发器将更新笔记的“snippet”列,并将其设置为空字符串。 + */ + private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = + "CREATE TRIGGER update_note_content_on_delete " + + " AFTER delete ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=''" + + " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + + " END"; + + /** + * Delete datas belong to note which has been deleted + * 此触发器将在从数据库中删除笔记时自动触发。它将删除与被删除笔记相关联的所有数据记录。 + */ + private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = + "CREATE TRIGGER delete_data_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.DATA + + " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + + " END"; + + /** + * Delete notes belong to folder which has been deleted + * 此触发器将在从数据库中删除文件夹时自动触发,它将删除该文件夹下的所有笔记。 + */ + private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = + "CREATE TRIGGER folder_delete_notes_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END"; + + /** + * Move notes belong to folder which has been moved to trash folder + * 此触发器将在将某个文件夹移动到回收站时自动触发,它会将该文件夹下的所有笔记也移动到回收站。 + */ + private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = + "CREATE TRIGGER folder_move_notes_on_trash " + + " AFTER UPDATE ON " + TABLE.NOTE + + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END"; + + /** + * 这是 NotesDatabaseHelper 类的构造函数,用于创建数据库,并将数据库名称、版本等参数传递给基类 SQLiteOpenHelper 的构造函数。 + * @param context + */ + public NotesDatabaseHelper(Context context) { + super(context, DB_NAME, null, DB_VERSION); + } + + /** + * 此方法用于在给定的 SQLiteDatabase 对象上创建“note”表。 + * 它执行 CREATE_NOTE_TABLE_SQL 常量中指定的 SQL 语句, + * 并调用 reCreateNoteTableTriggers 和 createSystemFolder 方法以重置触发器并创建系统文件夹。 + * @param db + */ + public void createNoteTable(SQLiteDatabase db) { + db.execSQL(CREATE_NOTE_TABLE_SQL); + reCreateNoteTableTriggers(db); + createSystemFolder(db); + Log.d(TAG, "note table has been created"); + } + + /** + * 此私有方法用于重置所有触发器,即在调用此方法之前删除所有现有的触发器,然后重新创建所有触发器。 + * @param db + */ + private void reCreateNoteTableTriggers(SQLiteDatabase db) { + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); + + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); + db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER); + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER); + db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER); + db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); + } + + /** + * 此私有方法用于向数据库中插入四个系统文件夹。 + * 它通过为每个文件夹创建一个 ContentValues 对象来添加数据,并将其插入名为 "note" 的数据库表中。 + * 其中,每个文件夹具有唯一的 ID,类型为 TYPE_SYSTEM。 + * @param db + */ + private void createSystemFolder(SQLiteDatabase db) { + ContentValues values = new ContentValues(); + + /** + * call record foler for call notes + */ + values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + /** + * root folder which is default folder + */ + values.clear(); + values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + /** + * temporary folder which is used for moving note + */ + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + /** + * create trash folder + */ + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + /** + * 此方法用于创建数据表。 + * 它执行 CREATE_DATA_TABLE_SQL 常量中指定的 SQL 语句,并调用 reCreateDataTableTriggers 方法以重置触发器。 + * 最后,它还创建了 CREATE_DATA_NOTE_ID_INDEX_SQL 常量中指定的 ID 索引。 + * @param db + */ + public void createDataTable(SQLiteDatabase db) { + db.execSQL(CREATE_DATA_TABLE_SQL); + reCreateDataTableTriggers(db); + db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); + Log.d(TAG, "data table has been created"); + } + + /** + * 用于重置增删改触发器,删除所有现有的触发器,然后重新创建触发器。 + * @param db + */ + private void reCreateDataTableTriggers(SQLiteDatabase db) { + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); + + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); + } + + /** + * 此方法是 NotesDatabaseHelper 类的静态方法,通过传递上下文对象来获取数据库的实例。 + * 它将确保在多线程环境中只有一个实例创建。 + * @param context + * @return + */ + static synchronized NotesDatabaseHelper getInstance(Context context) { + if (mInstance == null) { + mInstance = new NotesDatabaseHelper(context); + } + return mInstance; + } + + /** + * 数据库被第一次创建时,此方法将调用。 + * createNoteTable() 和 createDataTable() 两个方法将被调用,用于创建表和触发器。 + * @param db + */ + @Override + public void onCreate(SQLiteDatabase db) { + createNoteTable(db); + createDataTable(db); + } + + /** + * 当数据库需要更新到一个新版本时,此方法将被调用。 + * 它通过指定旧版本和新版本号来确定进行哪些更新, + * 每个更新都会调用 upgradeToV2()、upgradeToV3() 和 upgradeToV4() 方法之一,以升级数据库结构。 + * @param db + * @param oldVersion + * @param newVersion + */ + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + boolean reCreateTriggers = false; + boolean skipV2 = false; + + if (oldVersion == 1) { + upgradeToV2(db); + skipV2 = true; // this upgrade including the upgrade from v2 to v3 + oldVersion++; + } + + if (oldVersion == 2 && !skipV2) { + upgradeToV3(db); + reCreateTriggers = true; + oldVersion++; + } + + if (oldVersion == 3) { + upgradeToV4(db); + oldVersion++; + } + + if (reCreateTriggers) { + reCreateNoteTableTriggers(db); + reCreateDataTableTriggers(db); + } + + if (oldVersion != newVersion) { + throw new IllegalStateException("Upgrade notes database to version " + newVersion + + "fails"); + } + } + + /** + * 此方法执行从 v1 升级到 v2 的数据迁移。它首先删除原来的表,然后创建新表,重新建立触发器。 + * @param db + */ + private void upgradeToV2(SQLiteDatabase db) { + db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); + db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); + createNoteTable(db); + createDataTable(db); + } + + /** + * 此方法执行从 v2 升级到 v3 的数据迁移。 + * 它删除不再需要的触发器并添加新的 note Gtask Id 列,以便允许在 Google Tasks 中同步任务到笔记应用程序中。 + * @param db + */ + private void upgradeToV3(SQLiteDatabase db) { + // drop unused triggers + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); + // add a column for gtask id + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID + + " TEXT NOT NULL DEFAULT ''"); + // add a trash system folder + ContentValues values = new ContentValues(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + /** + * 此方法执行从 v3 升级到 v4 的数据迁移。它为 notes 表添加了版本号列,以便在后续升级中进行版本验证。 + * @param db + */ + private void upgradeToV4(SQLiteDatabase db) { + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION + + " INTEGER NOT NULL DEFAULT 0"); + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/data/NotesProvider.java b/doc/精读代码(注释)/孔维屿注释/data/NotesProvider.java new file mode 100644 index 0000000..f8684ac --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/data/NotesProvider.java @@ -0,0 +1,374 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.data; + + +import android.app.SearchManager; +import android.content.ContentProvider; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Intent; +import android.content.UriMatcher; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.net.Uri; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE; + +/** + * 这个类中的方法可以处理来自应用程序的查询、插入、更新和删除等操作,并通过 UriMatcher 帮助确定请求的类型和内容。 + * 同时,它还定义了搜索查询结果的格式,并实现了一些自定义的功能,例如笔记的回收站文件夹。 + */ +public class NotesProvider extends ContentProvider { + + /** + * UriMatcher 用于匹配可能的 URI 请求,并将其映射到适当的代码路径。它被声明为静态常量,并在静态块中进行初始化。 + */ + private static final UriMatcher mMatcher; + + /** + * NotesDatabaseHelper 对象用于打开和操作笔记数据库。 + */ + private NotesDatabaseHelper mHelper; + + /** + * 日志标签,用于调试目的。 + */ + private static final String TAG = "NotesProvider"; + + //这几个静态常量是 URIs 返回时的返回值,它们分别对应笔记、单个笔记、数据和单个数据。这些常量被添加到 UriMatcher 中。 + private static final int URI_NOTE = 1; + private static final int URI_NOTE_ITEM = 2; + private static final int URI_DATA = 3; + private static final int URI_DATA_ITEM = 4; + + private static final int URI_SEARCH = 5; + private static final int URI_SEARCH_SUGGEST = 6; + + static { + /* + 这些语句将具有特定 URI 模式的请求添加到 UriMatcher 中, + 例如 "content://com.example.notes/note",并与与之关联的 UriMatcher 返回值进行映射。 + */ + mMatcher = new UriMatcher(UriMatcher.NO_MATCH); + mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); + mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); + mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); + mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); + mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); + } + + /** + * x'0A' represents the '\n' character in sqlite. For title and content in the search result, + * we will trim '\n' and white space in order to show more information. + * 用于定义搜索结果的内容,以及笔记的搜索查询SQL。 + * 它们用于返回包含搜索查询结果的 Cursor 对象,并传递给 CursorAdapter 来填充 ListView 或 RecyclerView。 + */ + private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," + + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," + + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," + + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + + /** + * 用于定义搜索结果的内容,以及笔记的搜索查询SQL。 + * 它们用于返回包含搜索查询结果的 Cursor 对象,并传递给 CursorAdapter 来填充 ListView 或 RecyclerView。 + */ + private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION + + " FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + + /** + * 在 ContentProvider 被创建之后,此方法将被调用,并且在这个例子中,它会初始化 mHelper 变量和返回 true。 + * @return + */ + @Override + public boolean onCreate() { + mHelper = NotesDatabaseHelper.getInstance(getContext()); + return true; + } + + /** + * 这个方法使用传递过来的参数来执行 SQL 查询,并返回一个 Cursor 对象,用于与 Activity 或 Fragment 中的 UI 控件进行交互。 + * @param uri + * @param projection + * @param selection + * @param selectionArgs + * @param sortOrder + * @return + */ + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + String sortOrder) { + Cursor c = null; + SQLiteDatabase db = mHelper.getReadableDatabase(); + String id = null; + switch (mMatcher.match(uri)) { + case URI_NOTE: + c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_NOTE_ITEM: + id = uri.getPathSegments().get(1); + c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_DATA: + c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_DATA_ITEM: + id = uri.getPathSegments().get(1); + c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_SEARCH: + case URI_SEARCH_SUGGEST: + if (sortOrder != null || projection != null) { + throw new IllegalArgumentException( + "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); + } + + String searchString = null; + if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { + if (uri.getPathSegments().size() > 1) { + searchString = uri.getPathSegments().get(1); + } + } else { + searchString = uri.getQueryParameter("pattern"); + } + + if (TextUtils.isEmpty(searchString)) { + return null; + } + + try { + searchString = String.format("%%%s%%", searchString); + c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, + new String[] { searchString }); + } catch (IllegalStateException ex) { + Log.e(TAG, "got exception: " + ex.toString()); + } + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + if (c != null) { + c.setNotificationUri(getContext().getContentResolver(), uri); + } + return c; + } + + /** + * 向 ContentProvider 中插入数据。 + * @param uri + * @param values + * @return + */ + @Override + public Uri insert(Uri uri, ContentValues values) { + SQLiteDatabase db = mHelper.getWritableDatabase(); + long dataId = 0, noteId = 0, insertedId = 0; + switch (mMatcher.match(uri)) { + case URI_NOTE: + insertedId = noteId = db.insert(TABLE.NOTE, null, values); + break; + case URI_DATA: + if (values.containsKey(DataColumns.NOTE_ID)) { + noteId = values.getAsLong(DataColumns.NOTE_ID); + } else { + Log.d(TAG, "Wrong data format without note id:" + values.toString()); + } + insertedId = dataId = db.insert(TABLE.DATA, null, values); + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + // Notify the note uri + if (noteId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); + } + + // Notify the data uri + if (dataId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); + } + + return ContentUris.withAppendedId(uri, insertedId); + } + + /** + * 从 ContentProvider 中删除数据。 + * @param uri + * @param selection + * @param selectionArgs + * @return + */ + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + int count = 0; + String id = null; + SQLiteDatabase db = mHelper.getWritableDatabase(); + boolean deleteData = false; + switch (mMatcher.match(uri)) { + case URI_NOTE: + selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; + count = db.delete(TABLE.NOTE, selection, selectionArgs); + break; + case URI_NOTE_ITEM: + id = uri.getPathSegments().get(1); + /** + * ID that smaller than 0 is system folder which is not allowed to + * trash + */ + long noteId = Long.valueOf(id); + if (noteId <= 0) { + break; + } + count = db.delete(TABLE.NOTE, + NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + break; + case URI_DATA: + count = db.delete(TABLE.DATA, selection, selectionArgs); + deleteData = true; + break; + case URI_DATA_ITEM: + id = uri.getPathSegments().get(1); + count = db.delete(TABLE.DATA, + DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + deleteData = true; + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + if (count > 0) { + if (deleteData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } + + /** + * 从 ContentProvider 中更新数据。 + * @param uri + * @param values + * @param selection + * @param selectionArgs + * @return + */ + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + int count = 0; + String id = null; + SQLiteDatabase db = mHelper.getWritableDatabase(); + boolean updateData = false; + switch (mMatcher.match(uri)) { + case URI_NOTE: + increaseNoteVersion(-1, selection, selectionArgs); + count = db.update(TABLE.NOTE, values, selection, selectionArgs); + break; + case URI_NOTE_ITEM: + id = uri.getPathSegments().get(1); + increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); + count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); + break; + case URI_DATA: + count = db.update(TABLE.DATA, values, selection, selectionArgs); + updateData = true; + break; + case URI_DATA_ITEM: + id = uri.getPathSegments().get(1); + count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); + updateData = true; + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + + if (count > 0) { + if (updateData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } + + /** + * 将查询字符串转换为 SQL 语句。如果查询字符串为空,则直接返回空字符串。 + * @param selection + * @return + */ + private String parseSelection(String selection) { + return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); + } + + /** + * 将笔记的版本号加一。如果 ID 大于 0 或查询字符串不为空,则将更新语句添加到 SQL 语句中。 + * @param id + * @param selection + * @param selectionArgs + */ + private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { + StringBuilder sql = new StringBuilder(120); + sql.append("UPDATE "); + sql.append(TABLE.NOTE); + sql.append(" SET "); + sql.append(NoteColumns.VERSION); + sql.append("=" + NoteColumns.VERSION + "+1 "); + + if (id > 0 || !TextUtils.isEmpty(selection)) { + sql.append(" WHERE "); + } + if (id > 0) { + sql.append(NoteColumns.ID + "=" + String.valueOf(id)); + } + if (!TextUtils.isEmpty(selection)) { + String selectString = id > 0 ? parseSelection(selection) : selection; + for (String args : selectionArgs) { + selectString = selectString.replaceFirst("\\?", args); + } + sql.append(selectString); + } + + mHelper.getWritableDatabase().execSQL(sql.toString()); + } + + @Override + public String getType(Uri uri) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/data/MetaData.java b/doc/精读代码(注释)/孔维屿注释/gtask/data/MetaData.java new file mode 100644 index 0000000..40cf17d --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/data/MetaData.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONException; +import org.json.JSONObject; + +/** + *Task类的拓展 + */ +public class MetaData extends Task { + private final static String TAG = MetaData.class.getSimpleName(); + + private String mRelatedGid = null; + + /** + * 设置一些元数据 + * @param gid + * @param metaInfo + */ + public void setMeta(String gid, JSONObject metaInfo) { + try { + metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); + } catch (JSONException e) { + Log.e(TAG, "failed to put related gid"); + } + setNotes(metaInfo.toString()); + setName(GTaskStringUtils.META_NOTE_NAME); + } + + /** + *返回私有变量"mRelatedGid"的值。 + * @return mRelatedGid + */ + public String getRelatedGid() { + return mRelatedGid; + } + + /** + * 一个被覆盖的方法 + * 如果当前实例的内容不为null,则返回true + * @return bool + */ + @Override + public boolean isWorthSaving() { + return getNotes() != null; + } + + /** + * 一个被覆盖的方法 + * 根据给定的JSONObject "js"设置当前实例的内容。如果当前实例的内容不为null,则从注释中提取相关的gid并将其设置为私有变量"mRelatedGid" + * @param js + */ + @Override + public void setContentByRemoteJSON(JSONObject js) { + super.setContentByRemoteJSON(js); + if (getNotes() != null) { + try { + JSONObject metaInfo = new JSONObject(getNotes().trim()); + mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); + } catch (JSONException e) { + Log.w(TAG, "failed to get related gid"); + mRelatedGid = null; + } + } + } + + /** + * 一个被覆盖的方法; + * 抛出"IllegalAccessError",因为不应该调用它 + * @param js + */ + @Override + public void setContentByLocalJSON(JSONObject js) { + // this function should not be called + throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); + } + + /** + * 一个被覆盖的方法; + * 抛出"IllegalAccessError",因为不应该调用它 + * @return + */ + @Override + public JSONObject getLocalJSONFromContent() { + throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); + } + + /** + * 一个被覆盖的方法; + * 抛出"IllegalAccessError",因为不应该调用它 + * @return + */ + @Override + public int getSyncAction(Cursor c) { + throw new IllegalAccessError("MetaData:getSyncAction should not be called"); + } + +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/data/Node.java b/doc/精读代码(注释)/孔维屿注释/gtask/data/Node.java new file mode 100644 index 0000000..a3311d9 --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/data/Node.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; + +import org.json.JSONObject; + +/** + * 一个Node抽象类 + */ +public abstract class Node { + public static final int SYNC_ACTION_NONE = 0; + + public static final int SYNC_ACTION_ADD_REMOTE = 1; + + public static final int SYNC_ACTION_ADD_LOCAL = 2; + + public static final int SYNC_ACTION_DEL_REMOTE = 3; + + public static final int SYNC_ACTION_DEL_LOCAL = 4; + + public static final int SYNC_ACTION_UPDATE_REMOTE = 5; + + public static final int SYNC_ACTION_UPDATE_LOCAL = 6; + + public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; + + public static final int SYNC_ACTION_ERROR = 8; + + private String mGid; + + private String mName; + + private long mLastModified; + + private boolean mDeleted; + + /** + * 构造函数,初始化成员变量 + */ + public Node() { + mGid = null; + mName = ""; + mLastModified = 0; + mDeleted = false; + } + + //五个抽象方法,需要实现 + public abstract JSONObject getCreateAction(int actionId); + + public abstract JSONObject getUpdateAction(int actionId); + + public abstract void setContentByRemoteJSON(JSONObject js); + + public abstract void setContentByLocalJSON(JSONObject js); + + public abstract JSONObject getLocalJSONFromContent(); + + /** + * 一个名为"getSyncAction"的抽象方法,接受一个游标参数,返回一个整数值,表示同步操作类型 + * @param c + * @return + */ + public abstract int getSyncAction(Cursor c); + + //setter和getter方法,分别用于设置或获取节点的各个属性 + public void setGid(String gid) { + this.mGid = gid; + } + + public void setName(String name) { + this.mName = name; + } + + public void setLastModified(long lastModified) { + this.mLastModified = lastModified; + } + + public void setDeleted(boolean deleted) { + this.mDeleted = deleted; + } + + public String getGid() { + return this.mGid; + } + + public String getName() { + return this.mName; + } + + public long getLastModified() { + return this.mLastModified; + } + + public boolean getDeleted() { + return this.mDeleted; + } + +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/data/SqlData.java b/doc/精读代码(注释)/孔维屿注释/gtask/data/SqlData.java new file mode 100644 index 0000000..9861fb3 --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/data/SqlData.java @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE; +import net.micode.notes.gtask.exception.ActionFailureException; + +import org.json.JSONException; +import org.json.JSONObject; + +/** + * 定义了同步操作的基本常量 + */ +public class SqlData { + private static final String TAG = SqlData.class.getSimpleName(); + + private static final int INVALID_ID = -99999; + + public static final String[] PROJECTION_DATA = new String[] { + DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, + DataColumns.DATA3 + }; + + public static final int DATA_ID_COLUMN = 0; + + public static final int DATA_MIME_TYPE_COLUMN = 1; + + public static final int DATA_CONTENT_COLUMN = 2; + + public static final int DATA_CONTENT_DATA_1_COLUMN = 3; + + public static final int DATA_CONTENT_DATA_3_COLUMN = 4; + + private ContentResolver mContentResolver; + + private boolean mIsCreate; + + private long mDataId; + + private String mDataMimeType; + + private String mDataContent; + + private long mDataContentData1; + + private String mDataContentData3; + + private ContentValues mDiffDataValues; + + /** + * 创建一个新的SqlData对象,并初始化成员变量。 + * @param context + */ + public SqlData(Context context) { + mContentResolver = context.getContentResolver(); + mIsCreate = true; + mDataId = INVALID_ID; + mDataMimeType = DataConstants.NOTE; + mDataContent = ""; + mDataContentData1 = 0; + mDataContentData3 = ""; + mDiffDataValues = new ContentValues(); + } + + /** + * 创建一个新的SqlData对象,并使用Cursor中的数据来初始化成员变量 + * @param context + * @param c + */ + public SqlData(Context context, Cursor c) { + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(c); + mDiffDataValues = new ContentValues(); + } + + /** + * 从游标中加载数据,并将其存储在成员变量中 + * @param c + */ + private void loadFromCursor(Cursor c) { + mDataId = c.getLong(DATA_ID_COLUMN); + mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); + mDataContent = c.getString(DATA_CONTENT_COLUMN); + mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); + mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); + } + + /** + * 用于设置数据的内容,并将其存储在mDiffDataValues变量中以便稍后提交更改。 + * 该方法接受JSONObject类型的参数,该参数包含要设置的内容。 + * 如果数据还未创建且尝试访问它,则会记录错误并返回null。 + * @param js + * @throws JSONException + */ + public void setContent(JSONObject js) throws JSONException { + long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; + if (mIsCreate || mDataId != dataId) { + mDiffDataValues.put(DataColumns.ID, dataId); + } + mDataId = dataId; + + String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) + : DataConstants.NOTE; + if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { + mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); + } + mDataMimeType = dataMimeType; + + String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; + if (mIsCreate || !mDataContent.equals(dataContent)) { + mDiffDataValues.put(DataColumns.CONTENT, dataContent); + } + mDataContent = dataContent; + + long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; + if (mIsCreate || mDataContentData1 != dataContentData1) { + mDiffDataValues.put(DataColumns.DATA1, dataContentData1); + } + mDataContentData1 = dataContentData1; + + String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; + if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { + mDiffDataValues.put(DataColumns.DATA3, dataContentData3); + } + mDataContentData3 = dataContentData3; + } + + /** + * 用于获取数据的内容,并将其作为一个JSONObject对象返回。 + * 如果数据尚未创建,则会记录错误并返回null。 + * @return + * @throws JSONException + */ + public JSONObject getContent() throws JSONException { + if (mIsCreate) { + Log.e(TAG, "it seems that we haven't created this in database yet"); + return null; + } + JSONObject js = new JSONObject(); + js.put(DataColumns.ID, mDataId); + js.put(DataColumns.MIME_TYPE, mDataMimeType); + js.put(DataColumns.CONTENT, mDataContent); + js.put(DataColumns.DATA1, mDataContentData1); + js.put(DataColumns.DATA3, mDataContentData3); + return js; + } + + /** + * 用于将数据提交到ContentProvider中。 + * 如果数据还未创建,则会插入新记录并更新mDataId变量的值。 + * 否则,它将更新现有记录的内容。如果要验证版本,则使用noteId和version参数。 + * @param noteId + * @param validateVersion + * @param version + */ + public void commit(long noteId, boolean validateVersion, long version) { + + if (mIsCreate) { + if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { + mDiffDataValues.remove(DataColumns.ID); + } + + mDiffDataValues.put(DataColumns.NOTE_ID, noteId); + Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); + try { + mDataId = Long.valueOf(uri.getPathSegments().get(1)); + } catch (NumberFormatException e) { + Log.e(TAG, "Get note id error :" + e.toString()); + throw new ActionFailureException("create note failed"); + } + } else { + if (mDiffDataValues.size() > 0) { + int result = 0; + if (!validateVersion) { + result = mContentResolver.update(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); + } else { + result = mContentResolver.update(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, + " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { + String.valueOf(noteId), String.valueOf(version) + }); + } + if (result == 0) { + Log.w(TAG, "there is no update. maybe user updates note when syncing"); + } + } + } + + mDiffDataValues.clear(); + mIsCreate = false; + } + + /** + * 返回数据ID的值,即mDataId的值 + * @return mDataId + */ + public long getId() { + return mDataId; + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/data/SqlNote.java b/doc/精读代码(注释)/孔维屿注释/gtask/data/SqlNote.java new file mode 100644 index 0000000..8c14b81 --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/data/SqlNote.java @@ -0,0 +1,553 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.appwidget.AppWidgetManager; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.tool.GTaskStringUtils; +import net.micode.notes.tool.ResourceParser; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + + +/** + * 数据库中便签数据以及相关方法 + */ +public class SqlNote { + private static final String TAG = SqlNote.class.getSimpleName(); + + private static final int INVALID_ID = -99999; + + public static final String[] PROJECTION_NOTE = new String[] { + NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, + NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, + NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE, + NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID, + NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID, + NoteColumns.VERSION + }; + + //一些成员变量 + public static final int ID_COLUMN = 0; + + public static final int ALERTED_DATE_COLUMN = 1; + + public static final int BG_COLOR_ID_COLUMN = 2; + + public static final int CREATED_DATE_COLUMN = 3; + + public static final int HAS_ATTACHMENT_COLUMN = 4; + + public static final int MODIFIED_DATE_COLUMN = 5; + + public static final int NOTES_COUNT_COLUMN = 6; + + public static final int PARENT_ID_COLUMN = 7; + + public static final int SNIPPET_COLUMN = 8; + + public static final int TYPE_COLUMN = 9; + + public static final int WIDGET_ID_COLUMN = 10; + + public static final int WIDGET_TYPE_COLUMN = 11; + + public static final int SYNC_ID_COLUMN = 12; + + public static final int LOCAL_MODIFIED_COLUMN = 13; + + public static final int ORIGIN_PARENT_ID_COLUMN = 14; + + public static final int GTASK_ID_COLUMN = 15; + + public static final int VERSION_COLUMN = 16; + + private Context mContext; + + private ContentResolver mContentResolver; + + private boolean mIsCreate; + + private long mId; + + private long mAlertDate; + + private int mBgColorId; + + private long mCreatedDate; + + private int mHasAttachment; + + private long mModifiedDate; + + private long mParentId; + + private String mSnippet; + + private int mType; + + private int mWidgetId; + + private int mWidgetType; + + private long mOriginParent; + + private long mVersion; + + private ContentValues mDiffNoteValues; + + private ArrayList mDataList; + + /** + * 构造函数 + * 需要传入一个 Context 对象作为参数,并在该构造函数中初始化了 SqlNote 中的一些属性 + * @param context + */ + public SqlNote(Context context) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = true; + mId = INVALID_ID; + mAlertDate = 0; + mBgColorId = ResourceParser.getDefaultBgId(context); + mCreatedDate = System.currentTimeMillis(); + mHasAttachment = 0; + mModifiedDate = System.currentTimeMillis(); + mParentId = 0; + mSnippet = ""; + mType = Notes.TYPE_NOTE; + mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; + mWidgetType = Notes.TYPE_WIDGET_INVALIDE; + mOriginParent = 0; + mVersion = 0; + mDiffNoteValues = new ContentValues(); + mDataList = new ArrayList(); + } + + /** + * 构造函数 + * 需要传入一个 Context 对象作为参数,以及一个 Cursor 对象 + * @param context + * @param c + */ + public SqlNote(Context context, Cursor c) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(c); + mDataList = new ArrayList(); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + mDiffNoteValues = new ContentValues(); + } + + /** + * 构造函数 + * 只需要传入一个 Context 对象和 Long 类型的 id 即可创建一个已有的 SqlNote 对象 + * @param context + * @param id + */ + public SqlNote(Context context, long id) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(id); + mDataList = new ArrayList(); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + mDiffNoteValues = new ContentValues(); + + } + + /** + * 利用该参数查询对应 id 的 SqlNote,返回一个 Cursor 对象。 + * 如果查询到了数据,就调用loadFromCursor方法 + * @param id long + */ + private void loadFromCursor(long id) { + Cursor c = null; + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", + new String[] { + String.valueOf(id) + }, null); + if (c != null) { + c.moveToNext(); + loadFromCursor(c); + } else { + Log.w(TAG, "loadFromCursor: cursor = null"); + } + } finally { + if (c != null) + c.close(); + } + } + + /** + * 从 Cursor 中读取数据,将这些数据设置为 SqlNote 对象的相应属性值 + * @param c cursor + */ + private void loadFromCursor(Cursor c) { + mId = c.getLong(ID_COLUMN); + mAlertDate = c.getLong(ALERTED_DATE_COLUMN); + mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); + mCreatedDate = c.getLong(CREATED_DATE_COLUMN); + mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); + mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); + mParentId = c.getLong(PARENT_ID_COLUMN); + mSnippet = c.getString(SNIPPET_COLUMN); + mType = c.getInt(TYPE_COLUMN); + mWidgetId = c.getInt(WIDGET_ID_COLUMN); + mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); + mVersion = c.getLong(VERSION_COLUMN); + } + + /** + * 来加载 SqlNote 对象的内容数据的 + */ + private void loadDataContent() { + Cursor c = null; + mDataList.clear(); + try { + c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, + "(note_id=?)", new String[] { + String.valueOf(mId) + }, null); + if (c != null) { + if (c.getCount() == 0) { + Log.w(TAG, "it seems that the note has not data"); + return; + } + while (c.moveToNext()) { + SqlData data = new SqlData(mContext, c); + mDataList.add(data); + } + } else { + Log.w(TAG, "loadDataContent: cursor = null"); + } + } finally { + if (c != null) + c.close(); + } + } + + /** + * 根据传入的 JSON 对象设置便签的内容 + * @param js JSONObject + * @return + */ + public boolean setContent(JSONObject js) { + try { + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { + Log.w(TAG, "cannot set system folder"); + } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { + // for folder we can only update the snnipet and type + String snippet = note.has(NoteColumns.SNIPPET) ? note + .getString(NoteColumns.SNIPPET) : ""; + if (mIsCreate || !mSnippet.equals(snippet)) { + mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); + } + mSnippet = snippet; + + int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) + : Notes.TYPE_NOTE; + if (mIsCreate || mType != type) { + mDiffNoteValues.put(NoteColumns.TYPE, type); + } + mType = type; + } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; + if (mIsCreate || mId != id) { + mDiffNoteValues.put(NoteColumns.ID, id); + } + mId = id; + + long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note + .getLong(NoteColumns.ALERTED_DATE) : 0; + if (mIsCreate || mAlertDate != alertDate) { + mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); + } + mAlertDate = alertDate; + + int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note + .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); + if (mIsCreate || mBgColorId != bgColorId) { + mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); + } + mBgColorId = bgColorId; + + long createDate = note.has(NoteColumns.CREATED_DATE) ? note + .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); + if (mIsCreate || mCreatedDate != createDate) { + mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); + } + mCreatedDate = createDate; + + int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note + .getInt(NoteColumns.HAS_ATTACHMENT) : 0; + if (mIsCreate || mHasAttachment != hasAttachment) { + mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); + } + mHasAttachment = hasAttachment; + + long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note + .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); + if (mIsCreate || mModifiedDate != modifiedDate) { + mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); + } + mModifiedDate = modifiedDate; + + long parentId = note.has(NoteColumns.PARENT_ID) ? note + .getLong(NoteColumns.PARENT_ID) : 0; + if (mIsCreate || mParentId != parentId) { + mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); + } + mParentId = parentId; + + String snippet = note.has(NoteColumns.SNIPPET) ? note + .getString(NoteColumns.SNIPPET) : ""; + if (mIsCreate || !mSnippet.equals(snippet)) { + mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); + } + mSnippet = snippet; + + int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) + : Notes.TYPE_NOTE; + if (mIsCreate || mType != type) { + mDiffNoteValues.put(NoteColumns.TYPE, type); + } + mType = type; + + int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) + : AppWidgetManager.INVALID_APPWIDGET_ID; + if (mIsCreate || mWidgetId != widgetId) { + mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); + } + mWidgetId = widgetId; + + int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note + .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; + if (mIsCreate || mWidgetType != widgetType) { + mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); + } + mWidgetType = widgetType; + + long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note + .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; + if (mIsCreate || mOriginParent != originParent) { + mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); + } + mOriginParent = originParent; + + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + SqlData sqlData = null; + if (data.has(DataColumns.ID)) { + long dataId = data.getLong(DataColumns.ID); + for (SqlData temp : mDataList) { + if (dataId == temp.getId()) { + sqlData = temp; + } + } + } + + if (sqlData == null) { + sqlData = new SqlData(mContext); + mDataList.add(sqlData); + } + + sqlData.setContent(data); + } + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 返回一个 类型的数据,用于保存笔记对象的信息 + * @return JSONObject + */ + public JSONObject getContent() { + try { + JSONObject js = new JSONObject(); + + if (mIsCreate) { + Log.e(TAG, "it seems that we haven't created this in database yet"); + return null; + } + + JSONObject note = new JSONObject(); + if (mType == Notes.TYPE_NOTE) { + note.put(NoteColumns.ID, mId); + note.put(NoteColumns.ALERTED_DATE, mAlertDate); + note.put(NoteColumns.BG_COLOR_ID, mBgColorId); + note.put(NoteColumns.CREATED_DATE, mCreatedDate); + note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); + note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); + note.put(NoteColumns.PARENT_ID, mParentId); + note.put(NoteColumns.SNIPPET, mSnippet); + note.put(NoteColumns.TYPE, mType); + note.put(NoteColumns.WIDGET_ID, mWidgetId); + note.put(NoteColumns.WIDGET_TYPE, mWidgetType); + note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); + js.put(GTaskStringUtils.META_HEAD_NOTE, note); + + JSONArray dataArray = new JSONArray(); + for (SqlData sqlData : mDataList) { + JSONObject data = sqlData.getContent(); + if (data != null) { + dataArray.put(data); + } + } + js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); + } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { + note.put(NoteColumns.ID, mId); + note.put(NoteColumns.TYPE, mType); + note.put(NoteColumns.SNIPPET, mSnippet); + js.put(GTaskStringUtils.META_HEAD_NOTE, note); + } + + return js; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + return null; + } + + //一些设置笔记属性的方法 + public void setParentId(long id) { + mParentId = id; + mDiffNoteValues.put(NoteColumns.PARENT_ID, id); + } + + public void setGtaskId(String gid) { + mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); + } + + public void setSyncId(long syncId) { + mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); + } + + public void resetLocalModified() { + mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); + } + + //一些获取笔记属性的方法 + public long getId() { + return mId; + } + + public long getParentId() { + return mParentId; + } + + public String getSnippet() { + return mSnippet; + } + + public boolean isNoteType() { + return mType == Notes.TYPE_NOTE; + } + + /** + * 将当前未保存的修改提交到数据库中 + * @param validateVersion + */ + public void commit(boolean validateVersion) { + if (mIsCreate) { + if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { + mDiffNoteValues.remove(NoteColumns.ID); + } + + Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); + try { + mId = Long.valueOf(uri.getPathSegments().get(1)); + } catch (NumberFormatException e) { + Log.e(TAG, "Get note id error :" + e.toString()); + throw new ActionFailureException("create note failed"); + } + if (mId == 0) { + throw new IllegalStateException("Create thread id failed"); + } + + if (mType == Notes.TYPE_NOTE) { + for (SqlData sqlData : mDataList) { + sqlData.commit(mId, false, -1); + } + } + } else { + if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { + Log.e(TAG, "No such note"); + throw new IllegalStateException("Try to update note with invalid id"); + } + if (mDiffNoteValues.size() > 0) { + mVersion ++; + int result = 0; + if (!validateVersion) { + result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" + + NoteColumns.ID + "=?)", new String[] { + String.valueOf(mId) + }); + } else { + result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" + + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", + new String[] { + String.valueOf(mId), String.valueOf(mVersion) + }); + } + if (result == 0) { + Log.w(TAG, "there is no update. maybe user updates note when syncing"); + } + } + + if (mType == Notes.TYPE_NOTE) { + for (SqlData sqlData : mDataList) { + sqlData.commit(mId, validateVersion, mVersion); + } + } + } + + // refresh local info + loadFromCursor(mId); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + + mDiffNoteValues.clear(); + mIsCreate = false; + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/data/Task.java b/doc/精读代码(注释)/孔维屿注释/gtask/data/Task.java new file mode 100644 index 0000000..c4daca3 --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/data/Task.java @@ -0,0 +1,387 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + + +public class Task extends Node { + private static final String TAG = Task.class.getSimpleName(); + + private boolean mCompleted; + + private String mNotes; + + private JSONObject mMetaInfo; + + private Task mPriorSibling; + + private TaskList mParent; + + /** + * 构造函数 + */ + public Task() { + super(); + mCompleted = false; + mNotes = null; + mPriorSibling = null; + mParent = null; + mMetaInfo = null; + } + + /** + * 返回一个 JSONObject 类型的数据,用于表示创建任务的操作 + * @param actionId int + * @return JSONObject + */ + public JSONObject getCreateAction(int actionId) { + JSONObject js = new JSONObject(); + + try { + // action_type + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); + + // action_id + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // index + js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); + + // entity_delta + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); + entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, + GTaskStringUtils.GTASK_JSON_TYPE_TASK); + if (getNotes() != null) { + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); + } + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + // parent_id + js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); + + // dest_parent_type + js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, + GTaskStringUtils.GTASK_JSON_TYPE_GROUP); + + // list_id + js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); + + // prior_sibling_id + if (mPriorSibling != null) { + js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate task-create jsonobject"); + } + + return js; + } + + /** + * 回一个 JSONObject 类型的数据,用于表示更新任务的操作 + * @return + */ + public JSONObject getUpdateAction(int actionId) { + JSONObject js = new JSONObject(); + + try { + // action_type + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); + + // action_id + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // id + js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); + + // entity_delta + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + if (getNotes() != null) { + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); + } + entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate task-update jsonobject"); + } + + return js; + } + + /** + * 用于根据从远程获取的 JSON 对象设置任务的内容 + * @param js + */ + public void setContentByRemoteJSON(JSONObject js) { + if (js != null) { + try { + // id + if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { + setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); + } + + // last_modified + if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { + setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); + } + + // name + if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { + setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); + } + + // notes + if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { + setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); + } + + // deleted + if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { + setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); + } + + // completed + if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { + setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to get task content from jsonobject"); + } + } + } + + /** + * 用于根据从本地获取的 JSON 对象设置任务的内容 + * @param js + */ + public void setContentByLocalJSON(JSONObject js) { + if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) + || !js.has(GTaskStringUtils.META_HEAD_DATA)) { + Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); + } + + try { + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + + if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { + Log.e(TAG, "invalid type"); + return; + } + + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { + setName(data.getString(DataColumns.CONTENT)); + break; + } + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + } + + /** + * 用于将当前 Task 对象的内容转化为本地 JSON 数据格式 + * @return + */ + public JSONObject getLocalJSONFromContent() { + String name = getName(); + try { + if (mMetaInfo == null) { + // new task created from web + if (name == null) { + Log.w(TAG, "the note seems to be an empty one"); + return null; + } + + JSONObject js = new JSONObject(); + JSONObject note = new JSONObject(); + JSONArray dataArray = new JSONArray(); + JSONObject data = new JSONObject(); + data.put(DataColumns.CONTENT, name); + dataArray.put(data); + js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + js.put(GTaskStringUtils.META_HEAD_NOTE, note); + return js; + } else { + // synced task + JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { + data.put(DataColumns.CONTENT, getName()); + break; + } + } + + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + return mMetaInfo; + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return null; + } + } + + /** + *用于根据从 MetaData 对象中获取的笔记数据设置 Task 的元数据信息 + * @param metaData + */ + public void setMetaInfo(MetaData metaData) { + if (metaData != null && metaData.getNotes() != null) { + try { + mMetaInfo = new JSONObject(metaData.getNotes()); + } catch (JSONException e) { + Log.w(TAG, e.toString()); + mMetaInfo = null; + } + } + } + + /** + * 用于根据传入的 Cursor 对象和当前 Task 对象的状态判断应该进行的同步操作 + * @param c + * @return + */ + public int getSyncAction(Cursor c) { + try { + JSONObject noteInfo = null; + if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { + noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + } + + if (noteInfo == null) { + Log.w(TAG, "it seems that note meta has been deleted"); + return SYNC_ACTION_UPDATE_REMOTE; + } + + if (!noteInfo.has(NoteColumns.ID)) { + Log.w(TAG, "remote note id seems to be deleted"); + return SYNC_ACTION_UPDATE_LOCAL; + } + + // validate the note id now + if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { + Log.w(TAG, "note id doesn't match"); + return SYNC_ACTION_UPDATE_LOCAL; + } + + if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { + // there is no local update + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // no update both side + return SYNC_ACTION_NONE; + } else { + // apply remote to local + return SYNC_ACTION_UPDATE_LOCAL; + } + } else { + // validate gtask id + if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { + Log.e(TAG, "gtask id doesn't match"); + return SYNC_ACTION_ERROR; + } + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // local modification only + return SYNC_ACTION_UPDATE_REMOTE; + } else { + return SYNC_ACTION_UPDATE_CONFLICT; + } + } + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + + return SYNC_ACTION_ERROR; + } + + //方法用于判断当前 Task 对象是否值得被保存 + public boolean isWorthSaving() { + return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) + || (getNotes() != null && getNotes().trim().length() > 0); + } + + //用于设置 Task 对象的完成状态、笔记信息、前一兄弟 Task 对象和父 TaskList 对象,这些方法将传入的参数设置到对应属性中。 + public void setCompleted(boolean completed) { + this.mCompleted = completed; + } + + public void setNotes(String notes) { + this.mNotes = notes; + } + + public void setPriorSibling(Task priorSibling) { + this.mPriorSibling = priorSibling; + } + + public void setParent(TaskList parent) { + this.mParent = parent; + } + + //别用于获取 Task 对象的完成状态、笔记信息、前一兄弟 Task 对象和父 TaskList 对象,这些方法将返回对应属性的值。 + public boolean getCompleted() { + return this.mCompleted; + } + + public String getNotes() { + return this.mNotes; + } + + public Task getPriorSibling() { + return this.mPriorSibling; + } + + public TaskList getParent() { + return this.mParent; + } + +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/data/TaskList.java b/doc/精读代码(注释)/孔维屿注释/gtask/data/TaskList.java new file mode 100644 index 0000000..82bd868 --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/data/TaskList.java @@ -0,0 +1,432 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + + +public class TaskList extends Node { + private static final String TAG = TaskList.class.getSimpleName(); + + private int mIndex; + + private ArrayList mChildren; + + public TaskList() { + super(); + mChildren = new ArrayList(); + mIndex = 1; + } + + /** + * 用于生成一个 JSONObject 对象,该对象表示一个用于创建当前 TaskList 对象的 Action + * @param actionId + * @return + */ + public JSONObject getCreateAction(int actionId) { + JSONObject js = new JSONObject(); + + try { + // action_type + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); + + // action_id + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // index + js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); + + // entity_delta + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); + entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, + GTaskStringUtils.GTASK_JSON_TYPE_GROUP); + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate tasklist-create jsonobject"); + } + + return js; + } + + /** + * 用于生成一个 JSONObject 对象,该对象表示一个用于更新当前 TaskList 对象的 Action + * @param actionId + * @return + */ + public JSONObject getUpdateAction(int actionId) { + JSONObject js = new JSONObject(); + + try { + // action_type + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); + + // action_id + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // id + js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); + + // entity_delta + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate tasklist-update jsonobject"); + } + + return js; + } + + /** + * 将从网络返回的JSONObject对象解析出任务列表的ID、最后修改时间和名称,并根据解析结果设置相应属性的值 + * @param js + */ + public void setContentByRemoteJSON(JSONObject js) { + if (js != null) { + try { + // id + if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { + setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); + } + + // last_modified + if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { + setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); + } + + // name + if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { + setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to get tasklist content from jsonobject"); + } + } + } + + /** + * 将从本地存储的JSONObject对象解析出便签的类型和名称,并根据解析结果设置相应任务列表的名称 + * @param js + */ + public void setContentByLocalJSON(JSONObject js) { + if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { + Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); + } + + try { + JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + + if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { + String name = folder.getString(NoteColumns.SNIPPET); + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); + } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { + if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); + else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_CALL_NOTE); + else + Log.e(TAG, "invalid system folder"); + } else { + Log.e(TAG, "error type"); + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + } + + /** + * 将任务列表的名称转换为本地存储JSONObject对象并返回。如果转换过程中出现异常,将返回null。 + * @return + */ + public JSONObject getLocalJSONFromContent() { + try { + JSONObject js = new JSONObject(); + JSONObject folder = new JSONObject(); + + String folderName = getName(); + if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) + folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), + folderName.length()); + folder.put(NoteColumns.SNIPPET, folderName); + if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) + || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) + folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + else + folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + + js.put(GTaskStringUtils.META_HEAD_NOTE, folder); + + return js; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return null; + } + } + + /** + * 根据传入的游标Cursor c判断需要同步的操作: + * 如果本地和远程都没有进行更新,则返回“无需同步”状态; + * 如果只有远程数据更新了,则返回“将远程更新应用到本地”状态; + * 如果既有本地数据更新又有远程数据更新,则返回“将本地更新应用到远程”状态; + * 如果出现错误,则返回“同步错误”状态。 + * @param c + * @return + */ + public int getSyncAction(Cursor c) { + try { + if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { + // there is no local update + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // no update both side + return SYNC_ACTION_NONE; + } else { + // apply remote to local + return SYNC_ACTION_UPDATE_LOCAL; + } + } else { + // validate gtask id + if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { + Log.e(TAG, "gtask id doesn't match"); + return SYNC_ACTION_ERROR; + } + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // local modification only + return SYNC_ACTION_UPDATE_REMOTE; + } else { + // for folder conflicts, just apply local modification + return SYNC_ACTION_UPDATE_REMOTE; + } + } + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + + return SYNC_ACTION_ERROR; + } + + /** + * 返回当前任务列表下子任务的数量 + * @return + */ + public int getChildTaskCount() { + return mChildren.size(); + } + + /** + * 向当前任务列表中添加一个子任务,如果添加成功则返回true。 + * @param task + * @return + */ + public boolean addChildTask(Task task) { + boolean ret = false; + if (task != null && !mChildren.contains(task)) { + ret = mChildren.add(task); + if (ret) { + // need to set prior sibling and parent + task.setPriorSibling(mChildren.isEmpty() ? null : mChildren + .get(mChildren.size() - 1)); + task.setParent(this); + } + } + return ret; + } + + /** + * 向当前任务列表中特定位置添加一个子任务。如果添加成功,则返回true。如果指定的索引不合法,则返回false。 + * @param task + * @param index + * @return + */ + public boolean addChildTask(Task task, int index) { + if (index < 0 || index > mChildren.size()) { + Log.e(TAG, "add child task: invalid index"); + return false; + } + + int pos = mChildren.indexOf(task); + if (task != null && pos == -1) { + mChildren.add(index, task); + + // update the task list + Task preTask = null; + Task afterTask = null; + if (index != 0) + preTask = mChildren.get(index - 1); + if (index != mChildren.size() - 1) + afterTask = mChildren.get(index + 1); + + task.setPriorSibling(preTask); + if (afterTask != null) + afterTask.setPriorSibling(task); + } + + return true; + } + + /** + * 从当前任务列表中删除一个子任务,并将该子任务的前一个同级任务的后继任务设置为该子任务的后继任务。如果删除成功则返回true,否则返回false。 + * @param task + * @return + */ + public boolean removeChildTask(Task task) { + boolean ret = false; + int index = mChildren.indexOf(task); + if (index != -1) { + ret = mChildren.remove(task); + + if (ret) { + // reset prior sibling and parent + task.setPriorSibling(null); + task.setParent(null); + + // update the task list + if (index != mChildren.size()) { + mChildren.get(index).setPriorSibling( + index == 0 ? null : mChildren.get(index - 1)); + } + } + } + return ret; + } + + /** + * 将指定的子任务移至当前任务列表中特定位置。如果移动成功,则返回true,否则返回false。 + * @param task + * @param index + * @return + */ + public boolean moveChildTask(Task task, int index) { + + if (index < 0 || index >= mChildren.size()) { + Log.e(TAG, "move child task: invalid index"); + return false; + } + + int pos = mChildren.indexOf(task); + if (pos == -1) { + Log.e(TAG, "move child task: the task should in the list"); + return false; + } + + if (pos == index) + return true; + return (removeChildTask(task) && addChildTask(task, index)); + } + + /** + * 查找并返回与指定任务ID相同的子任务。如果找到则返回该子任务,否则返回null。 + * @param gid + * @return + */ + public Task findChildTaskByGid(String gid) { + for (int i = 0; i < mChildren.size(); i++) { + Task t = mChildren.get(i); + if (t.getGid().equals(gid)) { + return t; + } + } + return null; + } + + /** + * 返回当前任务列表中指定子任务的索引。 + * @param task + * @return + */ + public int getChildTaskIndex(Task task) { + return mChildren.indexOf(task); + } + + /** + * 返回当前任务列表中指定索引下标的子任务对象。 + * @param index + * @return + */ + public Task getChildTaskByIndex(int index) { + if (index < 0 || index >= mChildren.size()) { + Log.e(TAG, "getTaskByIndex: invalid index"); + return null; + } + return mChildren.get(index); + } + + /** + * 根据指定任务ID查找并返回与之匹配的子任务。 + * @param gid + * @return + */ + public Task getChilTaskByGid(String gid) { + for (Task task : mChildren) { + if (task.getGid().equals(gid)) + return task; + } + return null; + } + + /** + * 返回当前任务列表中包含的所有子任务。 + * @return + */ + public ArrayList getChildTaskList() { + return this.mChildren; + } + + /** + * 将当前任务列表的索引设置为指定值。 + * @param index + */ + public void setIndex(int index) { + this.mIndex = index; + } + + /** + * 返回当前任务列表的索引值。 + * @return + */ + public int getIndex() { + return this.mIndex; + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/exception/ActionFailureException.java b/doc/精读代码(注释)/孔维屿注释/gtask/exception/ActionFailureException.java new file mode 100644 index 0000000..56ed92b --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/exception/ActionFailureException.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.exception; + +/** + * 一个继承了RuntimeException的自定义异常类,用于表示执行某个操作时出现了失败或错误。 + */ +public class ActionFailureException extends RuntimeException { + private static final long serialVersionUID = 4425249765923293627L; + + /** + * 默认构造函数,直接调用父类的默认构造函数。 + */ + public ActionFailureException() { + super(); + } + + /** + * 带有一个字符串参数的构造函数,用于设置异常的详细信息。 + * @param paramString + */ + public ActionFailureException(String paramString) { + super(paramString); + } + + /** + * 带有两个参数的构造函数,用于同时设置异常的详细信息和原因(即异常链)。 + * @param paramString + * @param paramThrowable + */ + public ActionFailureException(String paramString, Throwable paramThrowable) { + super(paramString, paramThrowable); + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/exception/NetworkFailureException.java b/doc/精读代码(注释)/孔维屿注释/gtask/exception/NetworkFailureException.java new file mode 100644 index 0000000..b72a4b9 --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/exception/NetworkFailureException.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.exception; + +/** + * 一个继承了Exception的自定义异常类,用于表示在进行网络请求时出现了失败或错误。 + */ +public class NetworkFailureException extends Exception { + private static final long serialVersionUID = 2107610287180234136L; + + /** + * 默认构造函数,直接调用父类的默认构造函数。 + */ + public NetworkFailureException() { + super(); + } + + /** + * 带有一个字符串参数的构造函数,用于设置异常的详细信息。 + * @param paramString + */ + public NetworkFailureException(String paramString) { + super(paramString); + } + + /** + * 带有两个参数的构造函数,用于同时设置异常的详细信息和原因(即异常链)。 + * @param paramString + * @param paramThrowable + */ + public NetworkFailureException(String paramString, Throwable paramThrowable) { + super(paramString, paramThrowable); + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskASyncTask.java b/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskASyncTask.java new file mode 100644 index 0000000..05a22c6 --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskASyncTask.java @@ -0,0 +1,158 @@ + +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.remote; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.os.AsyncTask; + +import net.micode.notes.R; +import net.micode.notes.ui.NotesListActivity; +import net.micode.notes.ui.NotesPreferenceActivity; + +/** + * 一个继承了AsyncTask的异步任务类,用于在后台执行与谷歌任务同步相关的操作,并向用户展示同步进度通知。 + */ +public class GTaskASyncTask extends AsyncTask { + + private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; + + /** + * 一个接口,用于在异步任务完成时回调。 + */ + public interface OnCompleteListener { + void onComplete(); + } + + + private Context mContext; + + private NotificationManager mNotifiManager; + + private GTaskManager mTaskManager; + + private OnCompleteListener mOnCompleteListener; + + public GTaskASyncTask(Context context, OnCompleteListener listener) { + mContext = context; + mOnCompleteListener = listener; + mNotifiManager = (NotificationManager) mContext + .getSystemService(Context.NOTIFICATION_SERVICE); + mTaskManager = GTaskManager.getInstance(); + } + + /** + * 取消同步操作的方法 + */ + public void cancelSync() { + mTaskManager.cancelSync(); + } + + /** + * 将同步进度信息发布到主线程中更新进度通知。 + * @param message + */ + public void publishProgess(String message) { + publishProgress(new String[] { + message + }); + } + + /** + * 根据传入的提示符ID和内容创建并展示通知。 + * @param tickerId + * @param content + */ + private void showNotification(int tickerId, String content) { + PendingIntent pendingIntent; + if (tickerId != R.string.ticker_success) { + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, + NotesPreferenceActivity.class), 0); + + } else { + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, + NotesListActivity.class), 0); + } + + + Notification.Builder builder = new Notification.Builder(mContext) + .setAutoCancel(true) + .setContentTitle(mContext.getString(R.string.app_name)) + .setContentText(content) + .setContentIntent(pendingIntent) + .setWhen(System.currentTimeMillis()) + .setOngoing(true); + Notification notification=builder.getNotification(); + mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); + } + + /** + * 在后台线程中执行任务的主要方法,用于启动同步操作并返回同步状态码。 + * @param unused + * @return + */ + @Override + protected Integer doInBackground(Void... unused) { + publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity + .getSyncAccountName(mContext))); + return mTaskManager.sync(mContext, this); + } + + /** + * 在主线程中更新同步进度通知的方法,用于将同步进度信息发布到通知栏中。 + * @param progress + */ + @Override + protected void onProgressUpdate(String... progress) { + showNotification(R.string.ticker_syncing, progress[0]); + if (mContext instanceof GTaskSyncService) { + ((GTaskSyncService) mContext).sendBroadcast(progress[0]); + } + } + + /** + * 在主线程中处理同步结果的方法,根据同步状态码显示相应的通知,并在任务完成时回调OnCompleteListener接口。 + * @param result + */ + @Override + protected void onPostExecute(Integer result) { + if (result == GTaskManager.STATE_SUCCESS) { + showNotification(R.string.ticker_success, mContext.getString( + R.string.success_sync_account, mTaskManager.getSyncAccount())); + NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); + } else if (result == GTaskManager.STATE_NETWORK_ERROR) { + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); + } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); + } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { + showNotification(R.string.ticker_cancel, mContext + .getString(R.string.error_sync_cancelled)); + } + if (mOnCompleteListener != null) { + new Thread(new Runnable() { + + public void run() { + mOnCompleteListener.onComplete(); + } + }).start(); + } + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskClient.java b/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskClient.java new file mode 100644 index 0000000..20f8bbd --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskClient.java @@ -0,0 +1,687 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.remote; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AccountManagerFuture; +import android.app.Activity; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.GTaskStringUtils; +import net.micode.notes.ui.NotesPreferenceActivity; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.cookie.Cookie; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpConnectionParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.Inflater; +import java.util.zip.InflaterInputStream; + + +public class GTaskClient { + + //一些常量的定义 + private static final String TAG = GTaskClient.class.getSimpleName(); + + private static final String GTASK_URL = "https://mail.google.com/tasks/"; + + private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; + + private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; + + private static GTaskClient mInstance = null; + + private DefaultHttpClient mHttpClient; + + private String mGetUrl; + + private String mPostUrl; + + private long mClientVersion; + + private boolean mLoggedin; + + private long mLastLoginTime; + + private int mActionId; + + private Account mAccount; + + private JSONArray mUpdateArray; + + /** + * Gtask服务器信息 + */ + private GTaskClient() { + mHttpClient = null; + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + mClientVersion = -1; + mLoggedin = false; + mLastLoginTime = 0; + mActionId = 1; + mAccount = null; + mUpdateArray = null; + } + + /** + * 静态方法,用于获取GTaskClient单例对象。 + * @return + */ + public static synchronized GTaskClient getInstance() { + if (mInstance == null) { + mInstance = new GTaskClient(); + } + return mInstance; + } + + /** + * 登录Google账户并获取GTask服务的授权Token。 + * 如果已经登录则不做处理,否则重新登录; + * 登录成功后,需要判断是否为自定义域名的Google账户,如是则使用对应的URL地址登录。 + * @param activity Activity + * @return bool + */ + public boolean login(Activity activity) { + // we suppose that the cookie would expire after 5 minutes + // then we need to re-login + final long interval = 1000 * 60 * 5; + if (mLastLoginTime + interval < System.currentTimeMillis()) { + mLoggedin = false; + } + + // need to re-login after account switch + if (mLoggedin + && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity + .getSyncAccountName(activity))) { + mLoggedin = false; + } + + if (mLoggedin) { + Log.d(TAG, "already logged in"); + return true; + } + + mLastLoginTime = System.currentTimeMillis(); + String authToken = loginGoogleAccount(activity, false); + if (authToken == null) { + Log.e(TAG, "login google account failed"); + return false; + } + + // login with custom domain if necessary + if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() + .endsWith("googlemail.com"))) { + StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); + int index = mAccount.name.indexOf('@') + 1; + String suffix = mAccount.name.substring(index); + url.append(suffix + "/"); + mGetUrl = url.toString() + "ig"; + mPostUrl = url.toString() + "r/ig"; + + if (tryToLoginGtask(activity, authToken)) { + mLoggedin = true; + } + } + + // try to login with google official url + if (!mLoggedin) { + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + if (!tryToLoginGtask(activity, authToken)) { + return false; + } + } + + mLoggedin = true; + return true; + } + + /** + *该方法实现了登录Google账户并获取授权Token的过程 + * @param activity Activity + * @param invalidateToken Token + * @return NULL or Token + */ + private String loginGoogleAccount(Activity activity, boolean invalidateToken) { + String authToken; + AccountManager accountManager = AccountManager.get(activity); + Account[] accounts = accountManager.getAccountsByType("com.google"); + + if (accounts.length == 0) { + Log.e(TAG, "there is no available google account"); + return null; + } + + String accountName = NotesPreferenceActivity.getSyncAccountName(activity); + Account account = null; + for (Account a : accounts) { + if (a.name.equals(accountName)) { + account = a; + break; + } + } + if (account != null) { + mAccount = account; + } else { + Log.e(TAG, "unable to get an account with the same name in the settings"); + return null; + } + + // get the token now + AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, + "goanna_mobile", null, activity, null, null); + try { + Bundle authTokenBundle = accountManagerFuture.getResult(); + authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); + if (invalidateToken) { + accountManager.invalidateAuthToken("com.google", authToken); + loginGoogleAccount(activity, false); + } + } catch (Exception e) { + Log.e(TAG, "get auth token failed"); + authToken = null; + } + + return authToken; + } + + /** + * 实现了尝试登录Gtask的过程 + * @param activity Activity + * @param authToken Token + * @return bool + */ + private boolean tryToLoginGtask(Activity activity, String authToken) { + if (!loginGtask(authToken)) { + // maybe the auth token is out of date, now let's invalidate the + // token and try again + authToken = loginGoogleAccount(activity, true); + if (authToken == null) { + Log.e(TAG, "login google account failed"); + return false; + } + + if (!loginGtask(authToken)) { + Log.e(TAG, "login gtask failed"); + return false; + } + } + return true; + } + + /** + * 该方法实现了Gtask登录的过程 + * @param authToken + * @return + */ + private boolean loginGtask(String authToken) { + int timeoutConnection = 10000; + int timeoutSocket = 15000; + HttpParams httpParameters = new BasicHttpParams(); + HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); + HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); + mHttpClient = new DefaultHttpClient(httpParameters); + BasicCookieStore localBasicCookieStore = new BasicCookieStore(); + mHttpClient.setCookieStore(localBasicCookieStore); + HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); + + // login gtask + try { + String loginUrl = mGetUrl + "?auth=" + authToken; + HttpGet httpGet = new HttpGet(loginUrl); + HttpResponse response = null; + response = mHttpClient.execute(httpGet); + + // get the cookie now + List cookies = mHttpClient.getCookieStore().getCookies(); + boolean hasAuthCookie = false; + for (Cookie cookie : cookies) { + if (cookie.getName().contains("GTL")) { + hasAuthCookie = true; + } + } + if (!hasAuthCookie) { + Log.w(TAG, "it seems that there is no auth cookie"); + } + + // get the client version + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin != -1 && end != -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + mClientVersion = js.getLong("v"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return false; + } catch (Exception e) { + // simply catch all exceptions + Log.e(TAG, "httpget gtask_url failed"); + return false; + } + + return true; + } + + /** + * 实现了获取当前操作id的功能,每次调用该方法时,将操作id加一并返回 + * @return + */ + private int getActionId() { + return mActionId++; + } + + /** + * 实现了创建一个HttpPost对象的功能,并设置了请求头信息。 + * @return + */ + private HttpPost createHttpPost() { + HttpPost httpPost = new HttpPost(mPostUrl); + httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); + httpPost.setHeader("AT", "1"); + return httpPost; + } + + /** + * 用于将返回结果的流数据读取并转化成字符串形式 + * @param entity + * @return + * @throws IOException + */ + private String getResponseContent(HttpEntity entity) throws IOException { + String contentEncoding = null; + if (entity.getContentEncoding() != null) { + contentEncoding = entity.getContentEncoding().getValue(); + Log.d(TAG, "encoding: " + contentEncoding); + } + + InputStream input = entity.getContent(); + if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { + input = new GZIPInputStream(entity.getContent()); + } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { + Inflater inflater = new Inflater(true); + input = new InflaterInputStream(entity.getContent(), inflater); + } + + try { + InputStreamReader isr = new InputStreamReader(input); + BufferedReader br = new BufferedReader(isr); + StringBuilder sb = new StringBuilder(); + + while (true) { + String buff = br.readLine(); + if (buff == null) { + return sb.toString(); + } + sb = sb.append(buff); + } + } finally { + input.close(); + } + } + + /** + * 实现了POST请求的功能 + * @param js + * @return + * @throws NetworkFailureException + */ + private JSONObject postRequest(JSONObject js) throws NetworkFailureException { + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + HttpPost httpPost = createHttpPost(); + try { + LinkedList list = new LinkedList(); + list.add(new BasicNameValuePair("r", js.toString())); + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); + httpPost.setEntity(entity); + + // execute the post + HttpResponse response = mHttpClient.execute(httpPost); + String jsString = getResponseContent(response.getEntity()); + return new JSONObject(jsString); + + } catch (ClientProtocolException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed"); + } catch (IOException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("unable to convert response content to jsonobject"); + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("error occurs when posting request"); + } + } + + /** + * 负责创建任务,在请求返回结果后将新增的任务的gid字段设置为返回结果中的新id。 + * @param task + * @throws NetworkFailureException + */ + public void createTask(Task task) throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // action_list + actionList.put(task.getCreateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // post + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("create task: handing jsonobject failed"); + } + } + + /** + * 负责创建任务列表,在请求返回结果后将新增的列表的gid字段设置为返回结果中的新id。 + * @param tasklist + * @throws NetworkFailureException + */ + public void createTaskList(TaskList tasklist) throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // action_list + actionList.put(tasklist.getCreateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // post + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("create tasklist: handing jsonobject failed"); + } + } + + /** + * 用于提交更新,即将所有等待提交的更新操作组成的JSON数组提交到服务器端 + * @throws NetworkFailureException + */ + public void commitUpdate() throws NetworkFailureException { + if (mUpdateArray != null) { + try { + JSONObject jsPost = new JSONObject(); + + // action_list + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + mUpdateArray = null; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("commit update: handing jsonobject failed"); + } + } + } + + /** + * 用于向待提交的更新操作数组中添加一个操作 + * @param node + * @throws NetworkFailureException + */ + public void addUpdateNode(Node node) throws NetworkFailureException { + if (node != null) { + // too many update items may result in an error + // set max to 10 items + if (mUpdateArray != null && mUpdateArray.length() > 10) { + commitUpdate(); + } + + if (mUpdateArray == null) + mUpdateArray = new JSONArray(); + mUpdateArray.put(node.getUpdateAction(getActionId())); + } + } + + /** + * 用于将一个任务从一个列表中移动到另一个列表中,或者在同一列表中进行位置调整 + * @param task + * @param preParent + * @param curParent + * @throws NetworkFailureException + */ + public void moveTask(Task task, TaskList preParent, TaskList curParent) + throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + // action_list + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); + if (preParent == curParent && task.getPriorSibling() != null) { + // put prioring_sibing_id only if moving within the tasklist and + // it is not the first one + action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); + } + action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); + action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); + if (preParent != curParent) { + // put the dest_list only if moving between tasklists + action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); + } + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("move task: handing jsonobject failed"); + } + } + + /** + * 用于删除一个节点,即设置节点的deleted属性为true,并将待提交的操作添加到提交数组中 + * @param node + * @throws NetworkFailureException + */ + public void deleteNode(Node node) throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // action_list + node.setDeleted(true); + actionList.put(node.getUpdateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + mUpdateArray = null; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("delete node: handing jsonobject failed"); + } + } + + /** + * 用于获取当前用户的任务列表 + * @return + * @throws NetworkFailureException + */ + public JSONArray getTaskLists() throws NetworkFailureException { + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + try { + HttpGet httpGet = new HttpGet(mGetUrl); + HttpResponse response = null; + response = mHttpClient.execute(httpGet); + + // get the task list + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin != -1 && end != -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); + } catch (ClientProtocolException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (IOException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task lists: handing jasonobject failed"); + } + } + + /** + * 用于获取指定任务列表中的所有任务。 + * @param listGid + * @return + * @throws NetworkFailureException + */ + public JSONArray getTaskList(String listGid) throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + // action_list + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); + action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + JSONObject jsResponse = postRequest(jsPost); + return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task list: handing jsonobject failed"); + } + } + + /** + * 返回当前同步的Google账号信息 + * @return + */ + public Account getSyncAccount() { + return mAccount; + } + + /** + * 则将待提交的操作数组mUpdateArray重置为null,以便进行下一轮的操作。 + */ + public void resetUpdateArray() { + mUpdateArray = null; + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskManager.java b/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskManager.java new file mode 100644 index 0000000..e69113e --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskManager.java @@ -0,0 +1,878 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.remote; + +import android.app.Activity; +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.data.MetaData; +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.SqlNote; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + + +public class GTaskManager { + //一些常量的定义 + private static final String TAG = GTaskManager.class.getSimpleName(); + + public static final int STATE_SUCCESS = 0; + + public static final int STATE_NETWORK_ERROR = 1; + + public static final int STATE_INTERNAL_ERROR = 2; + + public static final int STATE_SYNC_IN_PROGRESS = 3; + + public static final int STATE_SYNC_CANCELLED = 4; + + private static GTaskManager mInstance = null; + + private Activity mActivity; + + private Context mContext; + + private ContentResolver mContentResolver; + + private boolean mSyncing; + + private boolean mCancelled; + + private HashMap mGTaskListHashMap; + + private HashMap mGTaskHashMap; + + private HashMap mMetaHashMap; + + private TaskList mMetaList; + + private HashSet mLocalDeleteIdMap; + + private HashMap mGidToNid; + + private HashMap mNidToGid; + + /** + * 构造函数中初始化了该类使用到的各种变量,包括任务列表、任务、元数据等。 + */ + private GTaskManager() { + mSyncing = false; + mCancelled = false; + mGTaskListHashMap = new HashMap(); + mGTaskHashMap = new HashMap(); + mMetaHashMap = new HashMap(); + mMetaList = null; + mLocalDeleteIdMap = new HashSet(); + mGidToNid = new HashMap(); + mNidToGid = new HashMap(); + } + + /** + * 用于获取唯一的实例 + * @return + */ + public static synchronized GTaskManager getInstance() { + if (mInstance == null) { + mInstance = new GTaskManager(); + } + return mInstance; + } + + /** + * 用于设置当前活动的上下文环境,即调用该方法的Activity对象。该方法主要用于获取Google账号的AuthToken。 + * @param activity + */ + public synchronized void setActivityContext(Activity activity) { + // used for getting authtoken + mActivity = activity; + } + + /** + * 用于执行同步操作 + * @param context + * @param asyncTask + * @return + */ + public int sync(Context context, GTaskASyncTask asyncTask) { + if (mSyncing) { + Log.d(TAG, "Sync is in progress"); + return STATE_SYNC_IN_PROGRESS; + } + mContext = context; + mContentResolver = mContext.getContentResolver(); + mSyncing = true; + mCancelled = false; + mGTaskListHashMap.clear(); + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + + try { + GTaskClient client = GTaskClient.getInstance(); + client.resetUpdateArray(); + + // login google task + if (!mCancelled) { + if (!client.login(mActivity)) { + throw new NetworkFailureException("login google task failed"); + } + } + + // get the task list from google + asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); + initGTaskList(); + + // do content sync work + asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); + syncContent(); + } catch (NetworkFailureException e) { + Log.e(TAG, e.toString()); + return STATE_NETWORK_ERROR; + } catch (ActionFailureException e) { + Log.e(TAG, e.toString()); + return STATE_INTERNAL_ERROR; + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return STATE_INTERNAL_ERROR; + } finally { + mGTaskListHashMap.clear(); + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + mSyncing = false; + } + + return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; + } + + /** + * 用于初始化谷歌任务列表,包括元数据列表和所有任务列表以及它们的任务 + * @throws NetworkFailureException + */ + private void initGTaskList() throws NetworkFailureException { + if (mCancelled) + return; + GTaskClient client = GTaskClient.getInstance(); + try { + JSONArray jsTaskLists = client.getTaskLists(); + + // init meta list first + mMetaList = null; + for (int i = 0; i < jsTaskLists.length(); i++) { + JSONObject object = jsTaskLists.getJSONObject(i); + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); + + if (name + .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { + mMetaList = new TaskList(); + mMetaList.setContentByRemoteJSON(object); + + // load meta data + JSONArray jsMetas = client.getTaskList(gid); + for (int j = 0; j < jsMetas.length(); j++) { + object = (JSONObject) jsMetas.getJSONObject(j); + MetaData metaData = new MetaData(); + metaData.setContentByRemoteJSON(object); + if (metaData.isWorthSaving()) { + mMetaList.addChildTask(metaData); + if (metaData.getGid() != null) { + mMetaHashMap.put(metaData.getRelatedGid(), metaData); + } + } + } + } + } + + // create meta list if not existed + if (mMetaList == null) { + mMetaList = new TaskList(); + mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META); + GTaskClient.getInstance().createTaskList(mMetaList); + } + + // init task list + for (int i = 0; i < jsTaskLists.length(); i++) { + JSONObject object = jsTaskLists.getJSONObject(i); + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); + + if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) + && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META)) { + TaskList tasklist = new TaskList(); + tasklist.setContentByRemoteJSON(object); + mGTaskListHashMap.put(gid, tasklist); + mGTaskHashMap.put(gid, tasklist); + + // load tasks + JSONArray jsTasks = client.getTaskList(gid); + for (int j = 0; j < jsTasks.length(); j++) { + object = (JSONObject) jsTasks.getJSONObject(j); + gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + Task task = new Task(); + task.setContentByRemoteJSON(object); + if (task.isWorthSaving()) { + task.setMetaInfo(mMetaHashMap.get(gid)); + tasklist.addChildTask(task); + mGTaskHashMap.put(gid, task); + } + } + } + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("initGTaskList: handing JSONObject failed"); + } + } + + /** + * 用于执行内容同步操作 + * @throws NetworkFailureException + */ + private void syncContent() throws NetworkFailureException { + int syncType; + Cursor c = null; + String gid; + Node node; + + mLocalDeleteIdMap.clear(); + + if (mCancelled) { + return; + } + + // for local deleted note + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type<>? AND parent_id=?)", new String[] { + String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) + }, null); + if (c != null) { + while (c.moveToNext()) { + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); + } + + mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); + } + } else { + Log.w(TAG, "failed to query trash folder"); + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // sync folder first + syncFolder(); + + // for note existing in database + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type=? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c != null) { + while (c.moveToNext()) { + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); + syncType = node.getSyncAction(c); + } else { + if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { + // local add + syncType = Node.SYNC_ACTION_ADD_REMOTE; + } else { + // remote delete + syncType = Node.SYNC_ACTION_DEL_LOCAL; + } + } + doContentSync(syncType, node, c); + } + } else { + Log.w(TAG, "failed to query existing note in database"); + } + + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // go through remaining items + Iterator> iter = mGTaskHashMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + node = entry.getValue(); + doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); + } + + // mCancelled can be set by another thread, so we neet to check one by + // one + // clear local delete table + if (!mCancelled) { + if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { + throw new ActionFailureException("failed to batch-delete local deleted notes"); + } + } + + // refresh local sync id + if (!mCancelled) { + GTaskClient.getInstance().commitUpdate(); + refreshLocalSyncId(); + } + + } + + /** + * 同步本地文件夹和Google Tasks的文件夹 + * 对于根文件夹、通话录音文件夹、本地已存在的文件夹和远程添加的文件夹进行分别处理 + * @throws NetworkFailureException + */ + private void syncFolder() throws NetworkFailureException { + Cursor c = null; + String gid; + Node node; + int syncType; + + if (mCancelled) { + return; + } + + // for root folder + try { + c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, + Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); + if (c != null) { + c.moveToNext(); + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); + mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); + // for system folder, only update remote name if necessary + if (!node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) + doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); + } else { + doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); + } + } else { + Log.w(TAG, "failed to query root folder"); + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // for call-note folder + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", + new String[] { + String.valueOf(Notes.ID_CALL_RECORD_FOLDER) + }, null); + if (c != null) { + if (c.moveToNext()) { + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); + mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); + // for system folder, only update remote name if + // necessary + if (!node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_CALL_NOTE)) + doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); + } else { + doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); + } + } + } else { + Log.w(TAG, "failed to query call note folder"); + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // for local existing folders + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type=? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c != null) { + while (c.moveToNext()) { + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); + syncType = node.getSyncAction(c); + } else { + if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { + // local add + syncType = Node.SYNC_ACTION_ADD_REMOTE; + } else { + // remote delete + syncType = Node.SYNC_ACTION_DEL_LOCAL; + } + } + doContentSync(syncType, node, c); + } + } else { + Log.w(TAG, "failed to query existing folder"); + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // for remote add folders + Iterator> iter = mGTaskListHashMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + gid = entry.getKey(); + node = entry.getValue(); + if (mGTaskHashMap.containsKey(gid)) { + mGTaskHashMap.remove(gid); + doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); + } + } + + if (!mCancelled) + GTaskClient.getInstance().commitUpdate(); + } + + /** + * 具体的同步操作,利用参数syncType的不同,实现增加本地节点、增加远程节点、删除本地节点、删除远程节点、更新本地节点、更新远程节点等操作。 + * @param syncType + * @param node + * @param c + * @throws NetworkFailureException + */ + private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { + if (mCancelled) { + return; + } + + MetaData meta; + switch (syncType) { + case Node.SYNC_ACTION_ADD_LOCAL: + addLocalNode(node); + break; + case Node.SYNC_ACTION_ADD_REMOTE: + addRemoteNode(node, c); + break; + case Node.SYNC_ACTION_DEL_LOCAL: + meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN)); + if (meta != null) { + GTaskClient.getInstance().deleteNode(meta); + } + mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); + break; + case Node.SYNC_ACTION_DEL_REMOTE: + meta = mMetaHashMap.get(node.getGid()); + if (meta != null) { + GTaskClient.getInstance().deleteNode(meta); + } + GTaskClient.getInstance().deleteNode(node); + break; + case Node.SYNC_ACTION_UPDATE_LOCAL: + updateLocalNode(node, c); + break; + case Node.SYNC_ACTION_UPDATE_REMOTE: + updateRemoteNode(node, c); + break; + case Node.SYNC_ACTION_UPDATE_CONFLICT: + // merging both modifications maybe a good idea + // right now just use local update simply + updateRemoteNode(node, c); + break; + case Node.SYNC_ACTION_NONE: + break; + case Node.SYNC_ACTION_ERROR: + default: + throw new ActionFailureException("unkown sync action type"); + } + } + + /** + * 向本地添加新节点的具体操作,包括创建SqlNote、更新gid-nid映射等。 + * @param node + * @throws NetworkFailureException + */ + private void addLocalNode(Node node) throws NetworkFailureException { + if (mCancelled) { + return; + } + + SqlNote sqlNote; + if (node instanceof TaskList) { + if (node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { + sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); + } else if (node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { + sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); + } else { + sqlNote = new SqlNote(mContext); + sqlNote.setContent(node.getLocalJSONFromContent()); + sqlNote.setParentId(Notes.ID_ROOT_FOLDER); + } + } else { + sqlNote = new SqlNote(mContext); + JSONObject js = node.getLocalJSONFromContent(); + try { + if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + if (note.has(NoteColumns.ID)) { + long id = note.getLong(NoteColumns.ID); + if (DataUtils.existInNoteDatabase(mContentResolver, id)) { + // the id is not available, have to create a new one + note.remove(NoteColumns.ID); + } + } + } + + if (js.has(GTaskStringUtils.META_HEAD_DATA)) { + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + if (data.has(DataColumns.ID)) { + long dataId = data.getLong(DataColumns.ID); + if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { + // the data id is not available, have to create + // a new one + data.remove(DataColumns.ID); + } + } + } + + } + } catch (JSONException e) { + Log.w(TAG, e.toString()); + e.printStackTrace(); + } + sqlNote.setContent(js); + + Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); + if (parentId == null) { + Log.e(TAG, "cannot find task's parent id locally"); + throw new ActionFailureException("cannot add local node"); + } + sqlNote.setParentId(parentId.longValue()); + } + + // create the local node + sqlNote.setGtaskId(node.getGid()); + sqlNote.commit(false); + + // update gid-nid mapping + mGidToNid.put(node.getGid(), sqlNote.getId()); + mNidToGid.put(sqlNote.getId(), node.getGid()); + + // update meta + updateRemoteMeta(node.getGid(), sqlNote); + } + + /** + * 用于更新本地节点,即将Google任务列表或任务的信息更新到本地SQLite数据库中 + * @param node + * @param c + * @throws NetworkFailureException + */ + private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { + if (mCancelled) { + return; + } + + SqlNote sqlNote; + // update the note locally + sqlNote = new SqlNote(mContext, c); + sqlNote.setContent(node.getLocalJSONFromContent()); + + Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) + : new Long(Notes.ID_ROOT_FOLDER); + if (parentId == null) { + Log.e(TAG, "cannot find task's parent id locally"); + throw new ActionFailureException("cannot update local node"); + } + sqlNote.setParentId(parentId.longValue()); + sqlNote.commit(true); + + // update meta info + updateRemoteMeta(node.getGid(), sqlNote); + } + + /** + * 用于添加远程节点,即在Google服务端新建任务列表或者任务,然后根据返回的Gid来更新本地SQLite数据库,并更新元数据。 + * @param node + * @param c + * @throws NetworkFailureException + */ + private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { + if (mCancelled) { + return; + } + + SqlNote sqlNote = new SqlNote(mContext, c); + Node n; + + // update remotely + if (sqlNote.isNoteType()) { + Task task = new Task(); + task.setContentByLocalJSON(sqlNote.getContent()); + + String parentGid = mNidToGid.get(sqlNote.getParentId()); + if (parentGid == null) { + Log.e(TAG, "cannot find task's parent tasklist"); + throw new ActionFailureException("cannot add remote task"); + } + mGTaskListHashMap.get(parentGid).addChildTask(task); + + GTaskClient.getInstance().createTask(task); + n = (Node) task; + + // add meta + updateRemoteMeta(task.getGid(), sqlNote); + } else { + TaskList tasklist = null; + + // we need to skip folder if it has already existed + String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX; + if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) + folderName += GTaskStringUtils.FOLDER_DEFAULT; + else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER) + folderName += GTaskStringUtils.FOLDER_CALL_NOTE; + else + folderName += sqlNote.getSnippet(); + + Iterator> iter = mGTaskListHashMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + String gid = entry.getKey(); + TaskList list = entry.getValue(); + + if (list.getName().equals(folderName)) { + tasklist = list; + if (mGTaskHashMap.containsKey(gid)) { + mGTaskHashMap.remove(gid); + } + break; + } + } + + // no match we can add now + if (tasklist == null) { + tasklist = new TaskList(); + tasklist.setContentByLocalJSON(sqlNote.getContent()); + GTaskClient.getInstance().createTaskList(tasklist); + mGTaskListHashMap.put(tasklist.getGid(), tasklist); + } + n = (Node) tasklist; + } + + // update local note + sqlNote.setGtaskId(n.getGid()); + sqlNote.commit(false); + sqlNote.resetLocalModified(); + sqlNote.commit(true); + + // gid-id mapping + mGidToNid.put(n.getGid(), sqlNote.getId()); + mNidToGid.put(sqlNote.getId(), n.getGid()); + } + + /** + * 用于更新远程节点,即在Google服务端更新任务列表或者任务,在根据返回信息来更新本地SQLite数据库,并更新元数据。 + * @param node + * @param c + * @throws NetworkFailureException + */ + private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { + if (mCancelled) { + return; + } + + SqlNote sqlNote = new SqlNote(mContext, c); + + // update remotely + node.setContentByLocalJSON(sqlNote.getContent()); + GTaskClient.getInstance().addUpdateNode(node); + + // update meta + updateRemoteMeta(node.getGid(), sqlNote); + + // move task if necessary + if (sqlNote.isNoteType()) { + Task task = (Task) node; + TaskList preParentList = task.getParent(); + + String curParentGid = mNidToGid.get(sqlNote.getParentId()); + if (curParentGid == null) { + Log.e(TAG, "cannot find task's parent tasklist"); + throw new ActionFailureException("cannot update remote task"); + } + TaskList curParentList = mGTaskListHashMap.get(curParentGid); + + if (preParentList != curParentList) { + preParentList.removeChildTask(task); + curParentList.addChildTask(task); + GTaskClient.getInstance().moveTask(task, preParentList, curParentList); + } + } + + // clear local modified flag + sqlNote.resetLocalModified(); + sqlNote.commit(true); + } + + /** + * 用于更新笔记的元数据,即与笔记相关的元信息 + * @param gid + * @param sqlNote + * @throws NetworkFailureException + */ + private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { + if (sqlNote != null && sqlNote.isNoteType()) { + MetaData metaData = mMetaHashMap.get(gid); + if (metaData != null) { + metaData.setMeta(gid, sqlNote.getContent()); + GTaskClient.getInstance().addUpdateNode(metaData); + } else { + metaData = new MetaData(); + metaData.setMeta(gid, sqlNote.getContent()); + mMetaList.addChildTask(metaData); + mMetaHashMap.put(gid, metaData); + GTaskClient.getInstance().createTask(metaData); + } + } + } + + /** + * 用于刷新本地SQLite数据库中笔记的同步ID。 + * @throws NetworkFailureException + */ + private void refreshLocalSyncId() throws NetworkFailureException { + if (mCancelled) { + return; + } + + // get the latest gtask list + mGTaskHashMap.clear(); + mGTaskListHashMap.clear(); + mMetaHashMap.clear(); + initGTaskList(); + + Cursor c = null; + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type<>? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c != null) { + while (c.moveToNext()) { + String gid = c.getString(SqlNote.GTASK_ID_COLUMN); + Node node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + ContentValues values = new ContentValues(); + values.put(NoteColumns.SYNC_ID, node.getLastModified()); + mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, + c.getLong(SqlNote.ID_COLUMN)), values, null, null); + } else { + Log.e(TAG, "something is missed"); + throw new ActionFailureException( + "some local items don't have gid after sync"); + } + } + } else { + Log.w(TAG, "failed to query local note to refresh sync id"); + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + } + + /** + * 获取当前Google账户的同步账户名称。 + * @return + */ + public String getSyncAccount() { + return GTaskClient.getInstance().getSyncAccount().name; + } + + /** + * 取消同步过程。 + */ + public void cancelSync() { + mCancelled = true; + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskSyncService.java b/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskSyncService.java new file mode 100644 index 0000000..51ca7c7 --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/gtask/remote/GTaskSyncService.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.remote; + +import android.app.Activity; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.IBinder; + +/** + * 谷歌任务同步服务,用于将本地备忘录数据同步到Google Tasks中 + */ +public class GTaskSyncService extends Service { + public final static String ACTION_STRING_NAME = "sync_action_type"; + + public final static int ACTION_START_SYNC = 0; + + public final static int ACTION_CANCEL_SYNC = 1; + + public final static int ACTION_INVALID = 2; + + public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; + + public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; + + public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; + + private static GTaskASyncTask mSyncTask = null; + + private static String mSyncProgress = ""; + + /** + * 用于启动同步任务 + */ + private void startSync() { + if (mSyncTask == null) { + mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { + public void onComplete() { + mSyncTask = null; + sendBroadcast(""); + stopSelf(); + } + }); + sendBroadcast(""); + mSyncTask.execute(); + } + } + + /** + * 用于取消同步任务 + */ + private void cancelSync() { + if (mSyncTask != null) { + mSyncTask.cancelSync(); + } + } + + /** + * 用于在服务创建时初始化相关资源 + */ + @Override + public void onCreate() { + mSyncTask = null; + } + + /** + * 在接收同步操作命令时启动同步任务或取消同步任务 + * @param intent + * @param flags + * @param startId + * @return + */ + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + Bundle bundle = intent.getExtras(); + if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { + switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { + case ACTION_START_SYNC: + startSync(); + break; + case ACTION_CANCEL_SYNC: + cancelSync(); + break; + default: + break; + } + return START_STICKY; + } + return super.onStartCommand(intent, flags, startId); + } + + /** + * 在低内存情况下停止同步任务。 + */ + @Override + public void onLowMemory() { + if (mSyncTask != null) { + mSyncTask.cancelSync(); + } + } + + public IBinder onBind(Intent intent) { + return null; + } + + /** + * 向应用内发送广播消息,通知相关观察者同步任务的执行状态和进度信息。 + * @param msg + */ + public void sendBroadcast(String msg) { + mSyncProgress = msg; + Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); + intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); + intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); + sendBroadcast(intent); + } + + /** + * 用于在Activity中启动同步服务。 + * @param activity + */ + public static void startSync(Activity activity) { + GTaskManager.getInstance().setActivityContext(activity); + Intent intent = new Intent(activity, GTaskSyncService.class); + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); + activity.startService(intent); + } + + /** + * 用于在Activity中取消同步服务。 + * @param context + */ + public static void cancelSync(Context context) { + Intent intent = new Intent(context, GTaskSyncService.class); + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); + context.startService(intent); + } + + /** + * 用于检测当前是否正在执行同步任务 + * @return + */ + public static boolean isSyncing() { + return mSyncTask != null; + } + + /** + * 用于获取同步进度信息。 + * @return + */ + public static String getProgressString() { + return mSyncProgress; + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/model/Note.java b/doc/精读代码(注释)/孔维屿注释/model/Note.java new file mode 100644 index 0000000..4537e5e --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/model/Note.java @@ -0,0 +1,321 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.model; +import android.content.ContentProviderOperation; +import android.content.ContentProviderResult; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.content.OperationApplicationException; +import android.net.Uri; +import android.os.RemoteException; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.Notes.TextNote; + +import java.util.ArrayList; + +/** + * 要作用是封装了数据操作逻辑,并提供了方便的接口给外部进行调用。 + */ +public class Note { + private ContentValues mNoteDiffValues; + private NoteData mNoteData; + private static final String TAG = "Note"; + /** + * Create a new note id for adding a new note to databases + * 获取新的笔记 ID + */ + public static synchronized long getNewNoteId(Context context, long folderId) { + // Create a new note in the database + ContentValues values = new ContentValues(); + long createdTime = System.currentTimeMillis(); + values.put(NoteColumns.CREATED_DATE, createdTime); + values.put(NoteColumns.MODIFIED_DATE, createdTime); + values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + values.put(NoteColumns.LOCAL_MODIFIED, 1); + values.put(NoteColumns.PARENT_ID, folderId); + Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); + + long noteId = 0; + try { + noteId = Long.valueOf(uri.getPathSegments().get(1)); + } catch (NumberFormatException e) { + Log.e(TAG, "Get note id error :" + e.toString()); + noteId = 0; + } + if (noteId == -1) { + throw new IllegalStateException("Wrong note id:" + noteId); + } + return noteId; + } + + public Note() { + mNoteDiffValues = new ContentValues(); + mNoteData = new NoteData(); + } + + /** + * 设置笔记的值。 + * @param key + * @param value + */ + public void setNoteValue(String key, String value) { + mNoteDiffValues.put(key, value); + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + } + + /** + * 设置笔记数据的值。 + * @param key + * @param value + */ + public void setTextData(String key, String value) { + mNoteData.setTextData(key, value); + } + + /** + * 设置笔记数据的ID。 + * @param id + */ + public void setTextDataId(long id) { + mNoteData.setTextDataId(id); + } + + /** + * 获取笔记数据的ID。 + * @return + */ + public long getTextDataId() { + return mNoteData.mTextDataId; + } + + /** + * 设置笔记数据的ID。 + * @param id + */ + public void setCallDataId(long id) { + mNoteData.setCallDataId(id); + } + + /** + * 设置笔记数据的值。 + * @param key + * @param value + */ + public void setCallData(String key, String value) { + mNoteData.setCallData(key, value); + } + + /** + * 返回笔记是否已被本地修改。 + * @return + */ + public boolean isLocalModified() { + return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); + } + + /** + * 判断笔记是否需要同步,如果需要则更新笔记到 ContentProvider 中。 + * @param context + * @param noteId + * @return + */ + public boolean syncNote(Context context, long noteId) { + if (noteId <= 0) { + throw new IllegalArgumentException("Wrong note id:" + noteId); + } + + if (!isLocalModified()) { + return true; + } + + /** + * In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and + * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the + * note data info + */ + if (context.getContentResolver().update( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, + null) == 0) { + Log.e(TAG, "Update note error, should not happen"); + // Do not return, fall through + } + mNoteDiffValues.clear(); + + if (mNoteData.isLocalModified() + && (mNoteData.pushIntoContentResolver(context, noteId) == null)) { + return false; + } + + return true; + } + + private class NoteData { + private long mTextDataId; + + private ContentValues mTextDataValues; + + private long mCallDataId; + + private ContentValues mCallDataValues; + + private static final String TAG = "NoteData"; + + public NoteData() { + mTextDataValues = new ContentValues(); + mCallDataValues = new ContentValues(); + mTextDataId = 0; + mCallDataId = 0; + } + + /** + * 判断笔记数据是否已经被本地修改。 + * @return + */ + boolean isLocalModified() { + return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; + } + + /** + * 设置文本数据的 ID。 + * @param id + */ + void setTextDataId(long id) { + if(id <= 0) { + throw new IllegalArgumentException("Text data id should larger than 0"); + } + mTextDataId = id; + } + + /** + * 设置电话数据的 ID。 + * @param id + */ + void setCallDataId(long id) { + if (id <= 0) { + throw new IllegalArgumentException("Call data id should larger than 0"); + } + mCallDataId = id; + } + + /** + * 设置笔记中电话数据的值。 + * @param key + * @param value + */ + void setCallData(String key, String value) { + mCallDataValues.put(key, value); + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + } + + /** + * 设置笔记中文本数据的值。 + * @param key + * @param value + */ + void setTextData(String key, String value) { + mTextDataValues.put(key, value); + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + } + + /** + * 将笔记数据插入 ContentProvider 中,同时更新对应的数据 ID。 + * @param context + * @param noteId + * @return + */ + Uri pushIntoContentResolver(Context context, long noteId) { + /** + * Check for safety + */ + if (noteId <= 0) { + throw new IllegalArgumentException("Wrong note id:" + noteId); + } + + ArrayList operationList = new ArrayList(); + ContentProviderOperation.Builder builder = null; + + if(mTextDataValues.size() > 0) { + mTextDataValues.put(DataColumns.NOTE_ID, noteId); + if (mTextDataId == 0) { + mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, + mTextDataValues); + try { + setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); + } catch (NumberFormatException e) { + Log.e(TAG, "Insert new text data fail with noteId" + noteId); + mTextDataValues.clear(); + return null; + } + } else { + builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mTextDataId)); + builder.withValues(mTextDataValues); + operationList.add(builder.build()); + } + mTextDataValues.clear(); + } + + if(mCallDataValues.size() > 0) { + mCallDataValues.put(DataColumns.NOTE_ID, noteId); + if (mCallDataId == 0) { + mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, + mCallDataValues); + try { + setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); + } catch (NumberFormatException e) { + Log.e(TAG, "Insert new call data fail with noteId" + noteId); + mCallDataValues.clear(); + return null; + } + } else { + builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mCallDataId)); + builder.withValues(mCallDataValues); + operationList.add(builder.build()); + } + mCallDataValues.clear(); + } + + if (operationList.size() > 0) { + try { + ContentProviderResult[] results = context.getContentResolver().applyBatch( + Notes.AUTHORITY, operationList); + return (results == null || results.length == 0 || results[0] == null) ? null + : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); + } catch (RemoteException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + return null; + } catch (OperationApplicationException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); + return null; + } + } + return null; + } + } +} diff --git a/doc/精读代码(注释)/孔维屿注释/model/WorkingNote.java b/doc/精读代码(注释)/孔维屿注释/model/WorkingNote.java new file mode 100644 index 0000000..c20387f --- /dev/null +++ b/doc/精读代码(注释)/孔维屿注释/model/WorkingNote.java @@ -0,0 +1,436 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.model; + +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.database.Cursor; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.Notes.TextNote; +import net.micode.notes.tool.ResourceParser.NoteBgResources; + +/** + * 它用于代表一条笔记,并提供了一些操作笔记的方法。 + */ +public class WorkingNote { + // Note for the working note + private Note mNote; + // Note Id + private long mNoteId; + // Note content + private String mContent; + // Note mode + private int mMode; + + private long mAlertDate; + + private long mModifiedDate; + + private int mBgColorId; + + private int mWidgetId; + + private int mWidgetType; + + private long mFolderId; + + private Context mContext; + + private static final String TAG = "WorkingNote"; + + private boolean mIsDeleted; + + private NoteSettingChangedListener mNoteSettingStatusListener; + + public static final String[] DATA_PROJECTION = new String[] { + DataColumns.ID, + DataColumns.CONTENT, + DataColumns.MIME_TYPE, + DataColumns.DATA1, + DataColumns.DATA2, + DataColumns.DATA3, + DataColumns.DATA4, + }; + + public static final String[] NOTE_PROJECTION = new String[] { + NoteColumns.PARENT_ID, + NoteColumns.ALERTED_DATE, + NoteColumns.BG_COLOR_ID, + NoteColumns.WIDGET_ID, + NoteColumns.WIDGET_TYPE, + NoteColumns.MODIFIED_DATE + }; + + private static final int DATA_ID_COLUMN = 0; + + private static final int DATA_CONTENT_COLUMN = 1; + + private static final int DATA_MIME_TYPE_COLUMN = 2; + + private static final int DATA_MODE_COLUMN = 3; + + private static final int NOTE_PARENT_ID_COLUMN = 0; + + private static final int NOTE_ALERTED_DATE_COLUMN = 1; + + private static final int NOTE_BG_COLOR_ID_COLUMN = 2; + + private static final int NOTE_WIDGET_ID_COLUMN = 3; + + private static final int NOTE_WIDGET_TYPE_COLUMN = 4; + + private static final int NOTE_MODIFIED_DATE_COLUMN = 5; + + // New note construct + private WorkingNote(Context context, long folderId) { + mContext = context; + mAlertDate = 0; + mModifiedDate = System.currentTimeMillis(); + mFolderId = folderId; + mNote = new Note(); + mNoteId = 0; + mIsDeleted = false; + mMode = 0; + mWidgetType = Notes.TYPE_WIDGET_INVALIDE; + } + + // Existing note construct + private WorkingNote(Context context, long noteId, long folderId) { + mContext = context; + mNoteId = noteId; + mFolderId = folderId; + mIsDeleted = false; + mNote = new Note(); + loadNote(); + } + + private void loadNote() { + Cursor cursor = mContext.getContentResolver().query( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, + null, null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); + mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); + mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); + mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN); + mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN); + mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); + } + cursor.close(); + } else { + Log.e(TAG, "No note with id:" + mNoteId); + throw new IllegalArgumentException("Unable to find note with id " + mNoteId); + } + loadNoteData(); + } + + + private void loadNoteData() { + Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, + DataColumns.NOTE_ID + "=?", new String[] { + String.valueOf(mNoteId) + }, null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + do { + String type = cursor.getString(DATA_MIME_TYPE_COLUMN); + if (DataConstants.NOTE.equals(type)) { + mContent = cursor.getString(DATA_CONTENT_COLUMN); + mMode = cursor.getInt(DATA_MODE_COLUMN); + mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); + } else if (DataConstants.CALL_NOTE.equals(type)) { + mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); + } else { + Log.d(TAG, "Wrong note type with type:" + type); + } + } while (cursor.moveToNext()); + } + cursor.close(); + } else { + Log.e(TAG, "No data with id:" + mNoteId); + throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); + } + } + + /** + * 创建一个新的空笔记。 + * @param context + * @param folderId + * @param widgetId + * @param widgetType + * @param defaultBgColorId + * @return + */ + public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, + int widgetType, int defaultBgColorId) { + WorkingNote note = new WorkingNote(context, folderId); + note.setBgColorId(defaultBgColorId); + note.setWidgetId(widgetId); + note.setWidgetType(widgetType); + return note; + } + + /** + * 加载指定 Id 的笔记。 + * @param context + * @param id + * @return + */ + public static WorkingNote load(Context context, long id) { + return new WorkingNote(context, id, 0); + } + + /** + * 保存当前笔记。 + * @return + */ + public synchronized boolean saveNote() { + if (isWorthSaving()) { + if (!existInDatabase()) { + if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { + Log.e(TAG, "Create new note fail with id:" + mNoteId); + return false; + } + } + + mNote.syncNote(mContext, mNoteId); + + /** + * Update widget content if there exist any widget of this note + */ + if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && mWidgetType != Notes.TYPE_WIDGET_INVALIDE + && mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onWidgetChanged(); + } + return true; + } else { + return false; + } + } + + public boolean existInDatabase() { + return mNoteId > 0; + } + + private boolean isWorthSaving() { + if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) + || (existInDatabase() && !mNote.isLocalModified())) { + return false; + } else { + return true; + } + } + + /** + * 设置笔记设置变化的监听器。 + * @param l + */ + public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { + mNoteSettingStatusListener = l; + } + + /** + * 设置闹钟提醒时间。 + * @param date + * @param set + */ + public void setAlertDate(long date, boolean set) { + if (date != mAlertDate) { + mAlertDate = date; + mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); + } + if (mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onClockAlertChanged(date, set); + } + } + + /** + * 标记笔记是否被删除。 + * @param mark + */ + public void markDeleted(boolean mark) { + mIsDeleted = mark; + if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onWidgetChanged(); + } + } + + /** + * 设置笔记的背景颜色。 + * @param id + */ + public void setBgColorId(int id) { + if (id != mBgColorId) { + mBgColorId = id; + if (mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onBackgroundColorChanged(); + } + mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); + } + } + + /** + * 设置笔记的模式。 + * @param mode + */ + public void setCheckListMode(int mode) { + if (mMode != mode) { + if (mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); + } + mMode = mode; + mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); + } + } + + /** + * 设置笔记关联的小部件类型。 + * @param type + */ + public void setWidgetType(int type) { + if (type != mWidgetType) { + mWidgetType = type; + mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); + } + } + + /** + * 设置笔记关联的小部件 Id。 + * @param id + */ + public void setWidgetId(int id) { + if (id != mWidgetId) { + mWidgetId = id; + mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); + } + } + + /** + * 设置笔记的文本内容。 + * @param text + */ + public void setWorkingText(String text) { + if (!TextUtils.equals(mContent, text)) { + mContent = text; + mNote.setTextData(DataColumns.CONTENT, mContent); + } + } + + /** + * 将该笔记转化为呼叫记录。 + * @param phoneNumber + * @param callDate + */ + public void convertToCallNote(String phoneNumber, long callDate) { + mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); + mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); + mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); + } + + //一些获取方法 + public boolean hasClockAlert() { + return (mAlertDate > 0 ? true : false); + } + + public String getContent() { + return mContent; + } + + public long getAlertDate() { + return mAlertDate; + } + + public long getModifiedDate() { + return mModifiedDate; + } + + public int getBgColorResId() { + return NoteBgResources.getNoteBgResource(mBgColorId); + } + + public int getBgColorId() { + return mBgColorId; + } + + public int getTitleBgResId() { + return NoteBgResources.getNoteTitleBgResource(mBgColorId); + } + + public int getCheckListMode() { + return mMode; + } + + public long getNoteId() { + return mNoteId; + } + + public long getFolderId() { + return mFolderId; + } + + public int getWidgetId() { + return mWidgetId; + } + + public int getWidgetType() { + return mWidgetType; + } + + /** + * 用于监听笔记设置的变化。 + */ + public interface NoteSettingChangedListener { + /** + * Called when the background color of current note has just changed + * 当当前笔记的背景色改变时被调用。 + */ + void onBackgroundColorChanged(); + + /** + * Called when user set clock + * 当闹钟提醒设置改变时被调用,参数 date 表示提醒时间,set 表示是否设置了提醒。 + */ + void onClockAlertChanged(long date, boolean set); + + /** + * Call when user create note from widget + * 当用户从小部件创建新笔记时被调用。 + */ + void onWidgetChanged(); + + /** + * Call when switch between check list mode and normal mode + * 当切换到检查列表模式或常规模式时被调用,参数 oldMode 表示变化前的模式,newMode 表示新的模式。 + * @param oldMode is previous mode before change + * @param newMode is new mode + */ + void onCheckListModeChanged(int oldMode, int newMode); + } +} diff --git a/doc/精读代码(注释)/张嘉欣注释/ui/AlarmAlertActivity.java b/doc/精读代码(注释)/张嘉欣注释/ui/AlarmAlertActivity.java new file mode 100644 index 0000000..04b4a1c --- /dev/null +++ b/doc/精读代码(注释)/张嘉欣注释/ui/AlarmAlertActivity.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.content.DialogInterface.OnDismissListener; +import android.content.Intent; +import android.media.AudioManager; +import android.media.MediaPlayer; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Bundle; +import android.os.PowerManager; +import android.provider.Settings; +import android.view.Window; +import android.view.WindowManager; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.DataUtils; + +import java.io.IOException; + + +public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { + private long mNoteId; + private String mSnippet; + private static final int SNIPPET_PREW_MAX_LEN = 60; + MediaPlayer mPlayer; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState);//调用 super.onCreate(savedInstanceState) 方法来调用父类的 onCreate() 方法进行基本的活动初始化操作。 + requestWindowFeature(Window.FEATURE_NO_TITLE);//使用 requestWindowFeature(Window.FEATURE_NO_TITLE) 方法请求隐藏当前活动的标题栏。 + + final Window win = getWindow(); + win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); + //通过 win.addFlags 方法添加标识,以在不打扰用户的情况下点亮屏幕和保持屏幕亮度。 + if (!isScreenOn()) { + win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON + | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON + | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); + } + + Intent intent = getIntent(); + + try { + mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); + mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); + mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, + SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) + : mSnippet; + } catch (IllegalArgumentException e) { + e.printStackTrace(); + return; + } + /** + * 然后,获取传入的 Intent 并通过 DataUtils.getSnippetById 方法获取传入笔记 ID 对应的摘要信息。如果摘要信息长度超过预设的最大长度,则截取前 SNIPPET_PREW_MAX_LEN 个字符,并添加 R.string.notelist_string_info 字符串信息。 + */ + + mPlayer = new MediaPlayer(); + if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { + showActionDialog(); + playAlarmSound(); + } else { + finish(); + } + //创建一个 MediaPlayer 对象并调用 playAlarmSound 方法播放闹钟提醒铃声 + } + /** + *在创建活动时调用,用于执行初始化操作并显示AlertDialog对话框; + */ + 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 地址。 + int silentModeStreams = Settings.System.getInt(getContentResolver(), + Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); + //获取当前静音模式下会受到影响的流类型,并将返回值赋值给 silentModeStreams 变量。 + if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { + mPlayer.setAudioStreamType(silentModeStreams); + } else { + mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); + } + try { + mPlayer.setDataSource(this, url); + mPlayer.prepare(); + mPlayer.setLooping(true); + mPlayer.start(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + /** + * 通过 mPlayer.setDataSource(this, url) 方法为 MediaPlayer 设置数据源,调用 mPlayer.prepare()方法进行准备操作,设置循环播放模式 mPlayer.setLooping(true) 并最终调用 mPlayer.start() 方法启动闹钟提醒铃声的播放。 + */ + } + + /** + * 用于播放提醒铃声; + */ + + private void showActionDialog() { + AlertDialog.Builder dialog = new AlertDialog.Builder(this); + dialog.setTitle(R.string.app_name); + dialog.setMessage(mSnippet); + dialog.setPositiveButton(R.string.notealert_ok, this); + if (isScreenOn()) { + dialog.setNegativeButton(R.string.notealert_enter, this); + } + dialog.show().setOnDismissListener(this); + //dialog.show().setOnDismissListener(this) 方法来显示该 AlertDialog 对话框,并将当前的 AlarmAlertActivity 对象作为监听器传入。当对话框被取消时,将会自动调用 onDismiss() 方法。 + } + + /** + * 用于显示AlertDialog对话框; + */ + + 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);//使用 startActivity(intent) 方法启动 NoteEditActivity 活动,来编辑和查看该笔记。 + intent.putExtra(Intent.EXTRA_UID, mNoteId); + startActivity(intent); + break; + default: + break; + } + } + + /** + * 处理AlertDialog中的按钮点击事件; + */ + + public void onDismiss(DialogInterface dialog) { + stopAlarmSound(); + finish(); + } + + /** + * 处理AlertDialog对话框取消事件; + */ + + private void stopAlarmSound() { + if (mPlayer != null) { + mPlayer.stop(); + mPlayer.release(); + mPlayer = null; + } + } + /** + * 用于停止播放提醒铃声。 + */ +} diff --git a/doc/精读代码(注释)/张嘉欣注释/ui/AlarmInitReceiver.java b/doc/精读代码(注释)/张嘉欣注释/ui/AlarmInitReceiver.java new file mode 100644 index 0000000..8712c2a --- /dev/null +++ b/doc/精读代码(注释)/张嘉欣注释/ui/AlarmInitReceiver.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.ContentUris; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +public class AlarmInitReceiver extends BroadcastReceiver { + + private static final String [] PROJECTION = new String [] { + NoteColumns.ID, + NoteColumns.ALERTED_DATE + }; // 定义需要查询的笔记提醒的列名和对应的索引 + + private static final int COLUMN_ID = 0; + private static final int COLUMN_ALERTED_DATE = 1; + // 实现 BroadcastReceiver 的 onReceive 方法 + @Override + public void onReceive(Context context, Intent intent) { + long currentDate = System.currentTimeMillis(); // 获取当前系统时间戳 + Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, + PROJECTION, + NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, + new String[] { String.valueOf(currentDate) }, + null); + // 查询所有未过期的笔记提醒 + if (c != null) { + if (c.moveToFirst()) { + do { + long alertDate = c.getLong(COLUMN_ALERTED_DATE); + Intent sender = new Intent(context, AlarmReceiver.class); + sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); + PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); + AlarmManager alermManager = (AlarmManager) context + .getSystemService(Context.ALARM_SERVICE); + alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + } while (c.moveToNext()); + } // 如果有需要提醒的笔记,则注册闹钟事件 + c.close(); + } + } +} diff --git a/doc/精读代码(注释)/张嘉欣注释/ui/AlarmReceiver.java b/doc/精读代码(注释)/张嘉欣注释/ui/AlarmReceiver.java new file mode 100644 index 0000000..bc29a3d --- /dev/null +++ b/doc/精读代码(注释)/张嘉欣注释/ui/AlarmReceiver.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +public class AlarmReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + intent.setClass(context, AlarmAlertActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + //展示闹钟提醒窗口。 + } +} +//AlarmReceiver 类的代码,它继承了 BroadcastReceiver,用于接收 AlarmManager 触发的闹钟事件。 diff --git a/doc/精读代码(注释)/张嘉欣注释/ui/DateTimePicker.java b/doc/精读代码(注释)/张嘉欣注释/ui/DateTimePicker.java new file mode 100644 index 0000000..cbfc27e --- /dev/null +++ b/doc/精读代码(注释)/张嘉欣注释/ui/DateTimePicker.java @@ -0,0 +1,501 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import java.text.DateFormatSymbols; +import java.util.Calendar; + +import net.micode.notes.R; + + +import android.content.Context; +import android.text.format.DateFormat; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.NumberPicker; + +public class DateTimePicker extends FrameLayout { + + private static final boolean DEFAULT_ENABLE_STATE = true;//默认是否启用时间选择器 + + 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; + private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;//24 小时制小时选择器的最小值和最大值; + private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; + private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;//12 小时制小时选择器的最小值和最大值; + private static final int MINUT_SPINNER_MIN_VAL = 0; + private static final int MINUT_SPINNER_MAX_VAL = 59;//分钟选择器的最小值和最大值; + 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; + private final NumberPicker mAmPmSpinner;//日期、小时、分钟和上午/下午的数字选择器控件; + private Calendar mDate;//当前日历日期 + + private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];//日期显示值的数组 + + private boolean mIsAm;//当前是否为上午 + + private boolean mIs24HourView;//时间选择器是否使用 24 小时制; + + 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);// 数值从 0 开始,需要减 1 + updateDateControl();// 更新当前月份 + onDateTimeChanged();// 更新当前年份 + } + }; + // 获取日历日期对应的年月日 + private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + boolean isDateChanged = false; + Calendar cal = Calendar.getInstance(); + if (!mIs24HourView) { + if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, 1); + isDateChanged = true; + } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -1); + isDateChanged = true; + } + if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY || + oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { + mIsAm = !mIsAm; + updateAmPmControl(); + } + } else { + if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, 1); + isDateChanged = true; + } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -1); + isDateChanged = true; + } + } + int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY); + mDate.set(Calendar.HOUR_OF_DAY, newHour); + onDateTimeChanged(); + if (isDateChanged) { + setCurrentYear(cal.get(Calendar.YEAR)); // 数值从 0 开始,需要减 1 + setCurrentMonth(cal.get(Calendar.MONTH)); // 更新当前月份 + setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));// 更新当前年份 + } + } + }; + + private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + int minValue = mMinuteSpinner.getMinValue(); + int maxValue = mMinuteSpinner.getMaxValue(); + int offset = 0; + // 上一分钟为最大值且当前分钟为最小值 + if (oldVal == maxValue && newVal == minValue) { + offset += 1; + } else if (oldVal == minValue && newVal == maxValue) { + offset -= 1; // 减少一小时 + }// 上一分钟为最小值且当前分钟为最大值 + if (offset != 0) {// 更新日历时间和日期控件 + mDate.add(Calendar.HOUR_OF_DAY, offset); + mHourSpinner.setValue(getCurrentHour()); + updateDateControl(); + // 更新上午/下午选择器 + int newHour = getCurrentHourOfDay(); + if (newHour >= HOURS_IN_HALF_DAY) { + mIsAm = false; + updateAmPmControl(); + } else { + mIsAm = true; + updateAmPmControl(); + } + }// 根据新的数值更新日历分钟,并发送时间改变事件 + mDate.set(Calendar.MINUTE, newVal); + onDateTimeChanged(); + } + };// 监听分钟选择器数值变化事件的回调函数 + + private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mIsAm = !mIsAm;// 切换上下午标识 + if (mIsAm) { + mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); + } else { + mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); + }// 根据新的标识增加或减少 12 小时 + updateAmPmControl();// 更新上午/下午选择器和时间改变事件 + onDateTimeChanged(); + } + };// 监听上午/下午选择器数值变化事件的回调函数 + + public interface OnDateTimeChangedListener { + void onDateTimeChanged(DateTimePicker view, int year, int month, + int dayOfMonth, int hourOfDay, int minute); + } + //日期时间改变监听器接口 + + public DateTimePicker(Context context) { + this(context, System.currentTimeMillis()); + } + //调用带时间戳参数的构造函数 + public DateTimePicker(Context context, long date) { + this(context, date, DateFormat.is24HourFormat(context)); + }//构造函数 + + public DateTimePicker(Context context, long date, boolean is24HourView) { + super(context); + mDate = Calendar.getInstance(); // mDate = Calendar.getInstance(); + mInitialising = true; // 标识正在初始化 + mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; + inflate(context, R.layout.datetime_picker, this);// 加载布局文件 + + // 查找并设置日期、小时、分钟及上午/下午选择器控件的监听器 + mDateSpinner = (NumberPicker) findViewById(R.id.date); + mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); + mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); + mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); + + mHourSpinner = (NumberPicker) findViewById(R.id.hour); + mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); + mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); + mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL); + mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL); + mMinuteSpinner.setOnLongPressUpdateInterval(100); // 设置长按修改间隔时间 + mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); + + String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); + mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); + mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); + mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL); + mAmPmSpinner.setDisplayedValues(stringsForAmPm); + mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); + + // 更新日期、小时、上午/下午选择器控件的显示值 + updateDateControl(); + updateHourControl(); + updateAmPmControl(); + + set24HourView(is24HourView);// 设置是否启用 24 小时制 + + setCurrentDate(date);// 设置默认时间 + + setEnabled(isEnabled());// 设置是否启用视图 + + // 设置内容描述信息 + mInitialising = false; + } + + @Override + public void setEnabled(boolean enabled) { + if (mIsEnabled == enabled) { + return; + }// 如果当前状态与要设置的状态相同,则不进行任何操作 + super.setEnabled(enabled);// 调用父类的方法设置启用状态 + + // 设置各个子控件的启用状态 + mDateSpinner.setEnabled(enabled); + mMinuteSpinner.setEnabled(enabled); + mHourSpinner.setEnabled(enabled); + mAmPmSpinner.setEnabled(enabled); + + mIsEnabled = enabled;// 记录当前状态 + } + + @Override + public boolean isEnabled() { + return mIsEnabled; + } + + /** + *获取当前日期的时间戳 + *@return 当前日期的时间戳 + */ + public long getCurrentDateInTimeMillis() { + return mDate.getTimeInMillis(); + } + + /** + * 设置当前日期 + * + * @param date 当前日期的时间戳 + */ + public void setCurrentDate(long date) { + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(date); + setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), + cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)); + } + + /** + * 设置当前日期 + * + * @param year 当前年份 + * @param month 当前月份 + * @param dayOfMonth 当前日 + * @param hourOfDay 当前小时 + * @param minute 当前分钟 + */ + public void setCurrentDate(int year, int month, + int dayOfMonth, int hourOfDay, int minute) { + setCurrentYear(year); + setCurrentMonth(month); + setCurrentDay(dayOfMonth); + setCurrentHour(hourOfDay); + setCurrentMinute(minute); + } + + /** + * 获取当前年份 + * + * @return 当前年份 + */ + public int getCurrentYear() { + return mDate.get(Calendar.YEAR); + } + + /** + * 设置当前年份 + * + * @param year 当前年份 + */ + public void setCurrentYear(int year) { + if (!mInitialising && year == getCurrentYear()) { + return; + } + mDate.set(Calendar.YEAR, year); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * 获取当前月份 + * + * @return 当前月份 + */ + public int getCurrentMonth() { + return mDate.get(Calendar.MONTH); + } + + /** + * 设置当前月份 + * + * @param month 当前月份 + */ + public void setCurrentMonth(int month) { + if (!mInitialising && month == getCurrentMonth()) { + return; + } + mDate.set(Calendar.MONTH, month); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current day of the month + * + * @return The day of the month + */ + public int getCurrentDay() { + return mDate.get(Calendar.DAY_OF_MONTH); + } + + /** + * Set current day of the month + * + * @param dayOfMonth The day of the month + */ + public void setCurrentDay(int dayOfMonth) { + if (!mInitialising && dayOfMonth == getCurrentDay()) { + return; + } + mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current hour in 24 hour mode, in the range (0~23) + * @return The current hour in 24 hour mode + */ + public int getCurrentHourOfDay() { + return mDate.get(Calendar.HOUR_OF_DAY); + } + + private int getCurrentHour() { + if (mIs24HourView){ + return getCurrentHourOfDay(); + } else { + int hour = getCurrentHourOfDay(); + if (hour > HOURS_IN_HALF_DAY) { + return hour - HOURS_IN_HALF_DAY; + } else { + return hour == 0 ? HOURS_IN_HALF_DAY : hour; + } + } + } + + /** + * Set current hour in 24 hour mode, in the range (0~23) + * + * @param hourOfDay + */ + public void setCurrentHour(int hourOfDay) { + if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { + return; + } + mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); + if (!mIs24HourView) { + if (hourOfDay >= HOURS_IN_HALF_DAY) { + mIsAm = false; + if (hourOfDay > HOURS_IN_HALF_DAY) { + hourOfDay -= HOURS_IN_HALF_DAY; + } + } else { + mIsAm = true; + if (hourOfDay == 0) { + hourOfDay = HOURS_IN_HALF_DAY; + } + } + updateAmPmControl(); + } + mHourSpinner.setValue(hourOfDay); + onDateTimeChanged(); + } + + /** + * Get currentMinute + * + * @return The Current Minute + */ + public int getCurrentMinute() { + return mDate.get(Calendar.MINUTE); + } + + /** + * Set current minute + */ + public void setCurrentMinute(int minute) { + if (!mInitialising && minute == getCurrentMinute()) { + return; + } + mMinuteSpinner.setValue(minute); + mDate.set(Calendar.MINUTE, minute); + onDateTimeChanged(); + } + + /** + * @return true if this is in 24 hour view else false. + */ + 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. + */ + public void set24HourView(boolean is24HourView) { + if (mIs24HourView == is24HourView) { + return; + } + mIs24HourView = is24HourView; + mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); + int hour = getCurrentHourOfDay(); + updateHourControl(); + setCurrentHour(hour); + updateAmPmControl(); + } + /** + * 更新日期控件 + */ + private void updateDateControl() { + Calendar cal = Calendar.getInstance(); // 创建一个 Calendar 对象 + cal.setTimeInMillis(mDate.getTimeInMillis()); // 将 Calendar 对象设置为指定时间 + cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); // 将时间减去一周的天数的一半再减一天 + mDateSpinner.setDisplayedValues(null); // 清空日期选择器中的显示值 + for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) { + cal.add(Calendar.DAY_OF_YEAR, 1); + mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal); + } + mDateSpinner.setDisplayedValues(mDateDisplayValues); // 设置日期选择器的显示值 + mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); // 将日期选择器设置为一周的中间位置 + mDateSpinner.invalidate(); // 刷新日期选择器 + } + + private void updateAmPmControl() { + if (mIs24HourView) { + mAmPmSpinner.setVisibility(View.GONE); + } else { + int index = mIsAm ? Calendar.AM : Calendar.PM; + mAmPmSpinner.setValue(index); + mAmPmSpinner.setVisibility(View.VISIBLE); + } + } + /** + * 更新上下午选择控件的显示 + */ + + private void updateHourControl() { + if (mIs24HourView) { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW); + } else { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); + } + }/** + * 根据是否为24小时制来更新小时选择控件的显示 + */ + + + /** + * Set the callback that indicates the 'Set' button has been pressed. + * @param callback the callback, if null will do nothing + */ + public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { + mOnDateTimeChangedListener = callback; + } + + private void onDateTimeChanged() { + if (mOnDateTimeChangedListener != null) { + mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), + getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); + } + }/** + * 当日期或时间被更改时,调用此方法以通知所有监听器 + */ + +} diff --git a/doc/精读代码(注释)/张嘉欣注释/ui/DateTimePickerDialog.java b/doc/精读代码(注释)/张嘉欣注释/ui/DateTimePickerDialog.java new file mode 100644 index 0000000..afe1f47 --- /dev/null +++ b/doc/精读代码(注释)/张嘉欣注释/ui/DateTimePickerDialog.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import java.util.Calendar; + +import net.micode.notes.R; +import net.micode.notes.ui.DateTimePicker; +import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.text.format.DateFormat; +import android.text.format.DateUtils; + +public class DateTimePickerDialog extends AlertDialog implements OnClickListener { + + private Calendar mDate = Calendar.getInstance();// 当前日期和时间 + private boolean mIs24HourView;// 是否为24小时制 + private OnDateTimeSetListener mOnDateTimeSetListener;// 日期时间设置监听器 + private DateTimePicker mDateTimePicker;// 日期时间选择器 + + public interface OnDateTimeSetListener { + void OnDateTimeSet(AlertDialog dialog, long 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); // 将 mDate 对象设置为新的日期和时间 + updateTitle(mDate.getTimeInMillis()); //更新选择器的标题 + } + });// 为 mDateTimePicker 设置一个匿名内部类作为日期时间变化监听器 + + mDate.setTimeInMillis(date); + mDate.set(Calendar.SECOND, 0); + // 将传入的时间戳设置为 mDate 对象的时间,并将秒数设置为零 + + mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); // 将当前日期和时间设置为日期时间选择器的默认值 + + setButton(context.getString(R.string.datetime_dialog_ok), this); + setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); // 设置确定和取消按钮的文本 + + set24HourView(DateFormat.is24HourFormat(this.getContext())); // 根据系统的时间格式确定日期时间选择器是否为 24 小时制 + updateTitle(mDate.getTimeInMillis());// 更新选择器的标题 + } + + public void set24HourView(boolean is24HourView) { + mIs24HourView = is24HourView; + } + //设置日期时间选择器是否显示为24小时制 + + public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { + mOnDateTimeSetListener = callBack; + } + //设置日期时间设置监听器 + + private void updateTitle(long date) { + int flag = + DateUtils.FORMAT_SHOW_YEAR | + DateUtils.FORMAT_SHOW_DATE | + DateUtils.FORMAT_SHOW_TIME; + // 定义日期、时间和小时制格式的标志 + + flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; + setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); + // 格式化时间戳为指定的日期、时间和小时制格式的字符串,并设置为选择器的标题 + } + //更新选择器的标题 + + public void onClick(DialogInterface arg0, int arg1) { + // 如果日期时间设置监听器不为 null,则调用 OnDateTimeSet 方法并传递当前日期时间和对话框对象 + if (mOnDateTimeSetListener != null) { + mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); + } + }//当单击对话框的按钮时被调用 + +} \ No newline at end of file diff --git a/doc/精读代码(注释)/张嘉欣注释/ui/DropdownMenu.java b/doc/精读代码(注释)/张嘉欣注释/ui/DropdownMenu.java new file mode 100644 index 0000000..2be293c --- /dev/null +++ b/doc/精读代码(注释)/张嘉欣注释/ui/DropdownMenu.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.PopupMenu; +import android.widget.PopupMenu.OnMenuItemClickListener; + +import net.micode.notes.R; + +public class DropdownMenu { + private Button mButton; // 下拉菜单所在的按钮 + private PopupMenu mPopupMenu; // 下拉菜单所在的按钮 + private Menu mMenu;// 菜单对象 + + /** + * 构造方法,用于创建一个 DropdownMenu 对象。 + * @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(); + } + }); + } + + public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { + if (mPopupMenu != null) { + mPopupMenu.setOnMenuItemClickListener(listener); + } + } /** + * 设置下拉菜单项的点击监听器。 + * 下拉菜单项的点击监听器 + */ + + public MenuItem findItem(int id) { + return mMenu.findItem(id); + } + /** + * 根据菜单项 ID 查找对应的菜单项并返回它的对象。 + * id 菜单项 ID + * @return 对应的菜单项对象,如果未找到则返回 null。 + */ + + public void setTitle(CharSequence title) { + mButton.setText(title); + } + /** + * 设置下拉菜单的标题。 + * @param title 下拉菜单的标题 + */ +} + /** + * DropdownMenu 类,用于创建下拉菜单。 + */ diff --git a/doc/精读代码(注释)/张嘉欣注释/ui/FoldersListAdapter.java b/doc/精读代码(注释)/张嘉欣注释/ui/FoldersListAdapter.java new file mode 100644 index 0000000..898edb8 --- /dev/null +++ b/doc/精读代码(注释)/张嘉欣注释/ui/FoldersListAdapter.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +public class FoldersListAdapter extends CursorAdapter { + public static final String [] PROJECTION = { + NoteColumns.ID, + NoteColumns.SNIPPET + }; + + // 列索引 + public static final int ID_COLUMN = 0; + public static final int NAME_COLUMN = 1; + + 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);// 创建自定义的文件夹列表项视图 + } + + @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); + } + } + + 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); + } + /** + * 获取指定位置处文件夹的名称。 + * context 上下文对象 + * position 文件夹在列表中的位置 + * @return 指定位置处文件夹的名称 + */ + + private class FolderListItem extends LinearLayout { + private TextView mName; + + + public FolderListItem(Context context) { + super(context);// 填充布局 + inflate(context, R.layout.folder_list_item, this); + mName = (TextView) findViewById(R.id.tv_folder_name); + } + /** + * 构造方法,用于创建一个文件夹列表项视图。 + * context 上下文对象 + */ + + public void bind(String name) { + mName.setText(name); + } + } + +} diff --git a/doc/精读代码(注释)/张嘉欣注释/ui/NoteEditActivity.java b/doc/精读代码(注释)/张嘉欣注释/ui/NoteEditActivity.java new file mode 100644 index 0000000..d6050c0 --- /dev/null +++ b/doc/精读代码(注释)/张嘉欣注释/ui/NoteEditActivity.java @@ -0,0 +1,1051 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlarmManager; +import android.app.AlertDialog; +import android.app.PendingIntent; +import android.app.SearchManager; +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Paint; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.format.DateUtils; +import android.text.style.BackgroundColorSpan; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.WindowManager; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.TextNote; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.model.WorkingNote.NoteSettingChangedListener; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.tool.ResourceParser.TextAppearanceResources; +import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener; +import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class NoteEditActivity extends Activity implements OnClickListener, + NoteSettingChangedListener, OnTextViewChangeListener { + private class HeadViewHolder { + public TextView tvModified; // 文章修改时间 + + public ImageView ivAlertIcon;// 提醒图标 + + public TextView tvAlertDate; // 提醒日期 + + public ImageView ibSetBgColor;// 设置背景色按钮 + } + + private static final Map sBgSelectorBtnsMap = new HashMap();//存储背景选择器按钮的 ID 和颜色值映射关系 + static { + sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); + sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); + sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); + sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); + sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); + } + //具体来说,这个 Map 中保存了五个键值对,分别表示五个背景选择器按钮的 ID 和对应的颜色值,其中颜色值来自于 ResourceParser 类中的常量。 + + private static final Map sBgSelectorSelectionMap = new HashMap(); + //存储背景颜色和对应选择器按钮的 ID 映射关系 + static { + sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); + sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); + sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); + sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); + sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); + } + + private static final Map sFontSizeBtnsMap = new HashMap(); + //存储字体大小选择器按钮的 ID 和字体大小值的映射关系 + static { + sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); + sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); + sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); + sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); + } + //需要获取某个字体大小选择器按钮的大小值,只需要从 sFontSizeBtnsMap 中获取对应的键值即可 + + private static final Map sFontSelectorSelectionMap = new HashMap(); + //存储字体大小和对应的选中状态图标按钮的 ID 的映射关系。 + static { + sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); + } + + private static final String TAG = "NoteEditActivity";//一个字符串常量,用来标记日志输出中的标签 + + private HeadViewHolder mNoteHeaderHolder;//笔记头部布局中的视图控件的引用。 + + private View mHeadViewPanel;//记头部布局的根视图 + + private View mNoteBgColorSelector;//笔记背景颜色选择器。 + + private View mFontSizeSelector;//字体大小选择器。 + + private EditText mNoteEditor;//笔记编辑器视图 + + private View mNoteEditorPanel;//笔记编辑器的根视图 + + private WorkingNote mWorkingNote;//用于表示当前正在编辑的笔记 + + private SharedPreferences mSharedPrefs;//应用程序的偏好设置 + private int mFontSizeId;//当前选中的字体大小在选择器中的位置 + + private static final String PREFERENCE_FONT_SIZE = "pref_font_size";//字体大小偏好设置时使用的键名 + + 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'); + //已勾选和未勾选的状态标记。 + + private LinearLayout mEditTextList;//保存多个文本编辑器视图的引用 + + private String mUserQuery;//用户输入的查询字符串 + private Pattern mPattern;//保存用户输入的查询字符串对应的正则表达式模式 + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + this.setContentView(R.layout.note_edit); + + if (savedInstanceState == null && !initActivityState(getIntent())) { + finish(); + return; + } + initResources(); + } + + /** + * Current activity may be killed when the memory is low. Once it is killed, for another time + * user load this activity, we should restore the former state + */ + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); + if (!initActivityState(intent)) { + finish(); + return; + } + Log.d(TAG, "Restoring from killed activity"); + } + } + //Activity 被销毁并重新创建时,会调用此方法来恢复之前保存的状态。 + + private boolean initActivityState(Intent intent) { + /** + * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id, + * then jump to the NotesListActivity + */ + mWorkingNote = null; + if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { + long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); + mUserQuery = ""; + + /** + * Starting from the searched result + */ + if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) { + noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); + mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); + } + + // 判断该笔记是否存在于数据库中 + if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { + // 如果不存在,则跳转到 NoteListActivity 进行提示并结束当前 Activity 的运行 + Intent jump = new Intent(this, NotesListActivity.class); + startActivity(jump); + showToast(R.string.error_note_not_exist); + finish(); + return false; + } else { + // 如果存在,则加载笔记数据 + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + // 如果加载过程中出现异常,则输出错误日志并结束当前 Activity 的运行 + Log.e(TAG, "load note failed with note id" + noteId); + finish(); + return false; + } + } + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN//不自动弹出软键盘 + | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);//软键盘弹出时,调整窗口的大小以避免被软键盘覆盖。 + + } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) { + // New note + long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);//笔记所属的文件夹 ID。 + int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID,//笔记所属的小部件 ID + AppWidgetManager.INVALID_APPWIDGET_ID);//笔记所属的小部件 ID + int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, + Notes.TYPE_WIDGET_INVALIDE);//笔记的小部件类型 + int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, + ResourceParser.getDefaultBgId(this));//笔记的背景图片资源 ID + + // Parse call-record note + String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);//通话记录页面进入时的通话号码 + long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);//话记录页面进入时的通话时间戳 + if (callDate != 0 && phoneNumber != null) { + if (TextUtils.isEmpty(phoneNumber)) { + Log.w(TAG, "The call record number is null"); + } + long noteId = 0; + if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(), + phoneNumber, callDate)) > 0) { + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + Log.e(TAG, "load call note failed with note id" + noteId); + finish(); + return false; + } + } else { + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, + widgetType, bgResId); + mWorkingNote.convertToCallNote(phoneNumber, callDate); + } + } else { + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, + bgResId); + } + + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + } else { + Log.e(TAG, "Intent not specified action, should not support"); + finish(); + return false; + } + mWorkingNote.setOnSettingStatusChangedListener(this); + return true; + } + + @Override + protected void onResume() { + super.onResume(); + initNoteScreen(); + } + + /** + * 初始化笔记编辑界面,包括文本样式、背景、标题、时间等 + */ + private void initNoteScreen() { + // 设置笔记编辑器的文本样式 + mNoteEditor.setTextAppearance(this, TextAppearanceResources + .getTexAppearanceResource(mFontSizeId)); + + // 判断当前编辑的笔记类型,如果是待办清单模式则转换为清单模式;否则高亮显示内容并将光标定位到文本末尾 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + switchToListMode(mWorkingNote.getContent()); + } else { + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); + mNoteEditor.setSelection(mNoteEditor.getText().length()); + } + + // 更新背景选择器对象 ID 和对应的视图的可见性 + for (Integer id : sBgSelectorSelectionMap.keySet()) { + findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); + } + + // 更新背景选择器对象 ID 和对应的视图的可见性 + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + + // 将编辑器的修改时间戳格式化后,更新标题栏中的相应时间显示 + mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, + mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE + | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME + | DateUtils.FORMAT_SHOW_YEAR)); + + /** + * TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker + * is not ready + */ + showAlertHeader(); + } + + /** + * 在编辑器顶部显示提醒信息 + */ + private void showAlertHeader() { + // 检查当前编辑的笔记是否设置过提醒,如果设置过则显示提醒时间和图标,否则不显示 + if (mWorkingNote.hasClockAlert()) { + long time = System.currentTimeMillis(); + if (time > mWorkingNote.getAlertDate()) { + // 如果提醒时间已过期,则显示提醒过期的提示 + mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); + } else { + // 显示距离提醒时间还有多长时间 + mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( + mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS)); + } + + // 设置提醒时间和图标的可见性为可见 + mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); + } else { + + // 如果没有设置过提醒,则隐藏提醒时间和图标 + mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); + }; + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + initActivityState(intent); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + /** + * For new note without note id, we should firstly save it to + * generate a id. If the editing note is not worth saving, there + * is no id which is equivalent to create new note + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); + } + + /** + * 分发触摸事件,处理当用户点击页面其他区域时,隐藏字体大小和背景色选择器视图的操作 + */ + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + // 判断当前字体背景色选择器是否可见,且触点不在选择面板内,则隐藏选择器并返回 true 表示该事件已被消耗 + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE + && !inRangeOfView(mNoteBgColorSelector, ev)) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } + + // 判断当前字体大小选择器是否可见,且触点不在选择面板内,则隐藏选择器并返回 true 表示该事件已被消耗 + if (mFontSizeSelector.getVisibility() == View.VISIBLE + && !inRangeOfView(mFontSizeSelector, ev)) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + // 如果以上两种情况都不符合,则调用父类方法处理该事件 + return super.dispatchTouchEvent(ev); + } + + /** + * 判断触点是否在给定视图所在的矩形区域内 + * + * @param view 给定需要判断的视图 + * @param ev 触摸事件对象 + * @return 如果触点在该视图内,则返回 true;否则返回 false + */ + private boolean inRangeOfView(View view, MotionEvent ev) { + int []location = new int[2]; + // 将视图在屏幕中的坐标存储到 location 数组中 + + view.getLocationOnScreen(location); + int x = location[0]; + int y = location[1]; + if (ev.getX() < x + || ev.getX() > (x + view.getWidth()) + || ev.getY() < y + || ev.getY() > (y + view.getHeight())) { + return false; + }// 判断触点是否在该视图的矩形区域内,并根据结果返回相应的值 + return true; + } + + /** + * 初始化各种资源,包括界面元素、字体大小选择器和背景色选择器等 + */ + private void initResources() { + // 初始化标题栏和编辑器 + mHeadViewPanel = findViewById(R.id.note_title); + mNoteHeaderHolder = new HeadViewHolder(); + mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); + mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); + mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); + mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color); + mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); + mNoteEditor = (EditText) findViewById(R.id.note_edit_view); + mNoteEditorPanel = findViewById(R.id.sv_note_edit); + mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);// 设置背景色选择器中每个按钮的点击事件 + for (int id : sBgSelectorBtnsMap.keySet()) { + ImageView iv = (ImageView) findViewById(id); + iv.setOnClickListener(this); + } + // 设置字体大小选择器中每个按钮的点击事件 + mFontSizeSelector = findViewById(R.id.font_size_selector); + for (int id : sFontSizeBtnsMap.keySet()) { + View view = findViewById(id); + view.setOnClickListener(this); + }; + + // 初始化 SharedPreferences 对象,并读取保存的字体大小设置 + mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); + mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); + /** + * 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 超出了资源范围,则强制将其设置为默认大小 + if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { + mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; + } + mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);// 初始化编辑器中的文本列表容 + } + + /** + * 当 Activity 进入后台时,保存当前笔记数据并清除设置状态 + */ + @Override + protected void onPause() { + super.onPause(); + if(saveNote()) { + Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length()); + } + clearSettingState(); + } + + /** + * 更新小部件的显示内容 + */ + private void updateWidget() { + Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { + intent.setClass(this, NoteWidgetProvider_2x.class); + } else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) { + intent.setClass(this, NoteWidgetProvider_4x.class); + } else { + Log.e(TAG, "Unspported widget type"); + return; + } + + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { + mWorkingNote.getWidgetId() + }); + + sendBroadcast(intent); + setResult(RESULT_OK, intent); + } + + /** + * 当用户点击某个视图时,根据视图 ID 做出相应响应 + * + * @param v 被点击的视图 + */ + public void onClick(View v) { + int id = v.getId();// 如果点击 "设置背景色" 按钮,则显示背景色选择器 + if (id == R.id.btn_set_bg_color) { // 如果点击 "设置背景色" 按钮,则显示背景色选择器 + mNoteBgColorSelector.setVisibility(View.VISIBLE); + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.VISIBLE); + } else if (sBgSelectorBtnsMap.containsKey(id)) {// 如果点击背景色选择器中的某个按钮,则更新当前笔记的背景色 + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.GONE); + mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); + mNoteBgColorSelector.setVisibility(View.GONE); + } else if (sFontSizeBtnsMap.containsKey(id)) {// 如果点击字体大小选择器中的某个按钮,则更新当前编辑器的字体大小 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); + mFontSizeId = sFontSizeBtnsMap.get(id); + mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {// 如果此时编辑器处于清单模式,则切换到正常模式 + getWorkingText(); + switchToListMode(mWorkingNote.getContent()); + } else {// 否则更新编辑器的文本样式 + mNoteEditor.setTextAppearance(this, + TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + } + mFontSizeSelector.setVisibility(View.GONE); + } + } + + /** + * 当用户按下返回键时,清除设置状态并保存当前笔记数据 + */ + @Override + public void onBackPressed() { + if(clearSettingState()) { + return; + } + + saveNote(); + super.onBackPressed(); + } + + /** + * 清除所有设置状态 + * + * @return 如果成功清除了设置状态,则返回 true;否则返回 false + */ + private boolean clearSettingState() { + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return false; + } + + /** + * 当用户选择背景色后,更新编辑器和标题栏的背景色 + */ + public void onBackgroundColorChanged() { + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.VISIBLE); + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + } + + /** + * 在弹出菜单准备显示之前执行的操作 + * + * @param menu 菜单对象 + * @return 如果处理成功,则返回 true;否则返回 false + */ + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + if (isFinishing()) {// 如果当前 Activity 已经结束,直接返回 true + return true; + } + clearSettingState(); + menu.clear(); + if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { + getMenuInflater().inflate(R.menu.call_note_edit, menu); + } else { + getMenuInflater().inflate(R.menu.note_edit, menu); + } + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); + } else { + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); + } + if (mWorkingNote.hasClockAlert()) { + menu.findItem(R.id.menu_alert).setVisible(false); + } else { + menu.findItem(R.id.menu_delete_remind).setVisible(false); + } + return true; + } + + /** + * 当菜单项被点击时执行的操作 + * + * @param item 菜单项对象 + * @return 如果成功处理该菜单项,则返回 true;否则返回 false + */ + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_new_note: + createNewNote();// 新建笔记 + break; + case R.id.menu_delete:// 删除笔记 + + // 弹出确认对话框 + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(getString(R.string.alert_title_delete)); + builder.setIcon(android.R.drawable.ic_dialog_alert); + builder.setMessage(getString(R.string.alert_message_delete_note)); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteCurrentNote();// 确认删除当前笔记并结束编辑器 + finish(); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case R.id.menu_font_size:// 设置字体大小 + mFontSizeSelector.setVisibility(View.VISIBLE); + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); + break; + case R.id.menu_list_mode:// 切换清单模式和普通模式 + mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ? + TextNote.MODE_CHECK_LIST : 0); + break; + case R.id.menu_share:// 分享笔记 + getWorkingText(); + sendTo(this, mWorkingNote.getContent()); + break; + case R.id.menu_send_to_desktop: // 发送到桌面 + sendToDesktop(); + break; + case R.id.menu_alert:// 设置闹钟提醒 + setReminder(); + break; + case R.id.menu_delete_remind:// 删除闹钟提醒 + mWorkingNote.setAlertDate(0, false); + break; + default: + break; + } + return true; + } + + /** + * 设置笔记的闹钟提醒 + */ + private void setReminder() { + // 创建日期时间选择对话框 + DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); + + d.setOnDateTimeSetListener(new OnDateTimeSetListener() {// 设置日期时间设置监听器 + public void OnDateTimeSet(AlertDialog dialog, long date) { + mWorkingNote.setAlertDate(date , true); + } + }); + d.show(); + } + + /** + * Share note to apps that support {@link Intent#ACTION_SEND} action + * and {@text/plain} type + */ + private void sendTo(Context context, String info) { + Intent intent = new Intent(Intent.ACTION_SEND); + intent.putExtra(Intent.EXTRA_TEXT, info); + intent.setType("text/plain"); + context.startActivity(intent); + } + + /** + * 创建新的笔记 + */ + private void createNewNote() { + // Firstly, save current editing notes + saveNote(); + + // For safety, start a new NoteEditActivity + finish(); + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); + startActivity(intent); + } + + /** + * 删除当前笔记 + */ + private void deleteCurrentNote() { + if (mWorkingNote.existInDatabase()) { + HashSet ids = new HashSet(); + long id = mWorkingNote.getNoteId(); + if (id != Notes.ID_ROOT_FOLDER) { + ids.add(id); + } else { + Log.d(TAG, "Wrong note id, should not happen"); + } + if (!isSyncMode()) { + if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) { + Log.e(TAG, "Delete Note error"); + } + } else { + if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) { + Log.e(TAG, "Move notes to trash folder error, should not happens"); + } + } + } + mWorkingNote.markDeleted(true); + } + + /** + * 判断是否处于同步模式 + * + * @return 如果处于同步模式,返回 true;否则返回 false + */ + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + public void onClockAlertChanged(long date, boolean set) { + /** + * User could set clock to an unsaved note, so before setting the + * alert clock, we should save the note first + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + if (mWorkingNote.getNoteId() > 0) { + Intent intent = new Intent(this, AlarmReceiver.class); + intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId())); + PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); + AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE)); + showAlertHeader(); + if(!set) { + alarmManager.cancel(pendingIntent); + } else { + alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); + } + } else { + /** + * There is the condition that user has input nothing (the note is + * not worthy saving), we have no note id, remind the user that he + * should input something + */ + Log.e(TAG, "Clock alert setting error"); + showToast(R.string.error_note_empty_for_clock); + } + } + + public void onWidgetChanged() { + updateWidget(); + } + + /** + * 在编辑区域中删除一行文本 + * @param index 待删除的行号 + * @param text 待删除的文本内容 + */ + public void onEditTextDelete(int index, String text) { + int childCount = mEditTextList.getChildCount(); + if (childCount == 1) { + return; + } + + for (int i = index + 1; i < childCount; i++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i - 1); + } + + mEditTextList.removeViewAt(index); + NoteEditText edit = null; + if(index == 0) { + edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById( + R.id.et_edit_text); + } else { + edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById( + R.id.et_edit_text); + } + int length = edit.length(); + edit.append(text); + edit.requestFocus(); + edit.setSelection(length); + } + + /** + * 在编辑区域中插入一行文本 + * + * @param index 待插入的行号 + * @param text 待插入的文本内容 + */ + public void onEditTextEnter(int index, String text) { + /** + * Should not happen, check for debug + */ + if(index > mEditTextList.getChildCount()) { + Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); + } + + View view = getListItem(text, index); + mEditTextList.addView(view, index); + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.requestFocus(); + edit.setSelection(0); + for (int i = index + 1; i < mEditTextList.getChildCount(); i++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i); + } + } + + /** + * 切换到列表模式 + * @param text 列表文本内容 + */ + private void switchToListMode(String text) { + mEditTextList.removeAllViews();// 清空编辑视图中 + String[] items = text.split("\n"); + int index = 0; + for (String item : items) { + if(!TextUtils.isEmpty(item)) { + mEditTextList.addView(getListItem(item, index)); + index++; + } + } + mEditTextList.addView(getListItem("", index)); + mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); + + mNoteEditor.setVisibility(View.GONE); + mEditTextList.setVisibility(View.VISIBLE); + } + + /** + * 获取高亮展示查询结果的 Spannable 文本 + * @param fullText 全文本 + * @param userQuery 用户查询字符串 + * @return 高亮展示查询结果的 Spannable 文本 + */ + private Spannable getHighlightQueryResult(String fullText, String userQuery) { + SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); + if (!TextUtils.isEmpty(userQuery)) { + mPattern = Pattern.compile(userQuery); + Matcher m = mPattern.matcher(fullText); + int start = 0; + while (m.find(start)) { + spannable.setSpan( + new BackgroundColorSpan(this.getResources().getColor( + R.color.user_query_highlight)), m.start(), m.end(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + start = m.end(); + } + } + return spannable; + } + + /** + * 获取列表项的 View + * + * @param item 列表项内容 + * @param index 列表项索引 + * @return 列表项的 View + */ + private View getListItem(String item, int index) { + // 加载布局文件并获取对应组件 + View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); + final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); + + // 设置 CheckBox 的监听器 + cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + } else { + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); + } + } + }); + + // 根据标记设置 Checkbox 和 EditText 的状态 + if (item.startsWith(TAG_CHECKED)) { + cb.setChecked(true); + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + item = item.substring(TAG_CHECKED.length(), item.length()).trim(); + } else if (item.startsWith(TAG_UNCHECKED)) { + cb.setChecked(false); + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); + item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); + } + + // 设置 EditText 组件的监听器和属性 + edit.setOnTextViewChangeListener(this); + edit.setIndex(index); + edit.setText(getHighlightQueryResult(item, mUserQuery)); + return view; + } + + /** + * 处理 NoteEditText 中的文本变化事件 + * + * @param index NoteEditText 所处列表项的索引 + * @param hasText NoteEditText 是否包含文本内容 + */ + public void onTextChange(int index, boolean hasText) { + if (index >= mEditTextList.getChildCount()) { // 判断索引是否合法,如果不合法则打印日志并返回 + Log.e(TAG, "Wrong index, should not happen"); + return; + } + if(hasText) {// 根据 hasText 参数决定显示或隐藏 CheckBox + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE); + } else { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE); + } + } + + /** + * 响应清单模式变化事件 + * + * @param oldMode 旧的清单模式状态值 + * @param newMode 新的清单模式状态值 + */ + public void onCheckListModeChanged(int oldMode, int newMode) { + if (newMode == TextNote.MODE_CHECK_LIST) {// 切换到清单模式,显示列表项编辑控件 + switchToListMode(mNoteEditor.getText().toString()); + } else { + // 退出清单模式 + // 如果当前没有正在编辑的文本内容,将当前工作记事的内容中的标记 + if (!getWorkingText()) { + mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ", + "")); + } + // 设置 NoteEditText 组件的文本内容,并将列表项编辑控件设为不可见 + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); + mEditTextList.setVisibility(View.GONE); + mNoteEditor.setVisibility(View.VISIBLE); + } + } + + /** + * 获取当前工作记事的文本内容 + * + * @return 是否存在已选中的文本 + */ + private boolean getWorkingText() { + boolean hasChecked = false; + + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {// 判断当前是否处于清单模式 + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < mEditTextList.getChildCount(); i++) { + View view = mEditTextList.getChildAt(i); + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + if (!TextUtils.isEmpty(edit.getText())) { + if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) {// 如果该列表项已选中,标记其 TAG_CHECKED 后添加到字符串缓存中 + sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n"); + hasChecked = true; + } else { + // 如果该列表项未选中,标记其 TAG_UNCHECKED 后添加到字符串缓存中 + sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n"); + } + } + } + // 设置工作记事的文本内容为字符串缓存中的内容 + mWorkingNote.setWorkingText(sb.toString()); + } else {// 如果不处于清单模式,则直接获取 NoteEditText 组件的文本内容,并设置为工作记事的文本内容 + mWorkingNote.setWorkingText(mNoteEditor.getText().toString()); + } + return hasChecked; + } + + private boolean saveNote() { + getWorkingText(); + boolean saved = mWorkingNote.saveNote(); + if (saved) { + /** + * There are two modes from List view to edit view, open one note, + * create/edit a node. Opening node requires to the original + * position in the list when back from edit view, while creating a + * new node requires to the top of the list. This code + * {@link #RESULT_OK} is used to identify the create/edit state + */ + setResult(RESULT_OK); + } + return saved; + } + + private void sendToDesktop() { + /** + * Before send message to home, we should make sure that current + * editing note is exists in databases. So, for new note, firstly + * save it + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + + if (mWorkingNote.getNoteId() > 0) { + Intent sender = new Intent(); + Intent shortcutIntent = new Intent(this, NoteEditActivity.class); + shortcutIntent.setAction(Intent.ACTION_VIEW); + shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); + sender.putExtra(Intent.EXTRA_SHORTCUT_NAME, + makeShortcutIconTitle(mWorkingNote.getContent())); + sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, + Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app)); + sender.putExtra("duplicate", true); + sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); + showToast(R.string.info_note_enter_desktop); + sendBroadcast(sender); + } else { + /** + * There is the condition that user has input nothing (the note is + * not worthy saving), we have no note id, remind the user that he + * should input something + */ + Log.e(TAG, "Send to desktop error"); + showToast(R.string.error_note_empty_for_send_to_desktop); + } + } + + /** + * 生成应用图标快捷方式的标题 + * @param content 原文本内容 + * @return 应用图标快捷方式的标题 + */ + private String makeShortcutIconTitle(String content) { + content = content.replace(TAG_CHECKED, ""); + content = content.replace(TAG_UNCHECKED, ""); + return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0, + SHORTCUT_ICON_TITLE_MAX_LEN) : content; + } + + /** + * 显示 Toast 消息 + * @param resId 要显示的消息 ID + */ + private void showToast(int resId) { + showToast(resId, Toast.LENGTH_SHORT); + } + + /** + * 显示 Toast 消息 + * @param resId 要显示的消息 ID + * @param duration Toast 的显示时间 + */ + private void showToast(int resId, int duration) { + Toast.makeText(this, resId, duration).show(); + } +} diff --git a/doc/精读代码(注释)/张嘉欣注释/widget/NoteWidgetProvider.java b/doc/精读代码(注释)/张嘉欣注释/widget/NoteWidgetProvider.java new file mode 100644 index 0000000..9d7b067 --- /dev/null +++ b/doc/精读代码(注释)/张嘉欣注释/widget/NoteWidgetProvider.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.widget; +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.util.Log; +import android.widget.RemoteViews; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.ui.NoteEditActivity; +import net.micode.notes.ui.NotesListActivity; + +public abstract class NoteWidgetProvider extends AppWidgetProvider { + public static final String [] PROJECTION = new String [] { + NoteColumns.ID,//笔记的ID号 + NoteColumns.BG_COLOR_ID,//背景颜色的ID号 + NoteColumns.SNIPPET//笔记的片段 + }; + + /** + *抽象类NoteWidgetProvider,并在其中定义了一个名为PROJECTION的常量数组。该数组中包含三个元素,分别是NoteColumns.ID、NoteColumns.BG_COLOR_ID和NoteColumns.SNIPPET + */ + public static final int COLUMN_ID = 0; + public static final int COLUMN_BG_COLOR_ID = 1; + public static final int COLUMN_SNIPPET = 2; +//定义了三个常量 COLUMN_ID、COLUMN_BG_COLOR_ID 和 COLUMN_SNIPPET,它们分别被赋值为0、1和2。 + private static final String TAG = "NoteWidgetProvider"; +//定义了一个名为TAG的私有常量字符串,其值为 "NoteWidgetProvider",这个常量通常用于日志输出中,方便开发人员在调试时快速定位和识别日志信息来源。 + @Override + public void onDeleted(Context context, int[] appWidgetIds) { + ContentValues values = new ContentValues();//要更新到数据库中的键值对。 + values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + for (int i = 0; i < appWidgetIds.length; i++) { + context.getContentResolver().update(Notes.CONTENT_NOTE_URI, + values, + NoteColumns.WIDGET_ID + "=?", + new String[] { String.valueOf(appWidgetIds[i])}); + } + } + /** + *这段代码是一个名为 onDeleted() 的方法,用于在从主屏幕上删除指定的笔记小部件时调用。 + */ + + private Cursor getNoteWidgetInfo(Context context, int widgetId) { + return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, + PROJECTION, + NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", + new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },//用ID来筛选,同时要是存在于未被删除的文件夹中 + null); + } + /** + *查询数据库中与指定小部件 ID 相关联的所有笔记记录,并返回表示查询结果的 Cursor 对象 + */ + + + protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + update(context, appWidgetManager, appWidgetIds, false); + } + + /** + * 用于更新小部件的显示内容。该方法接受三个参数:context、appWidgetManager 和 appWidgetIds,分别表示上下文对象、小部件管理器和要更新的小部件 ID 列表。 + */ + + private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, + boolean privacyMode) { + for (int i = 0; i < appWidgetIds.length; i++) { + if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { + int bgId = ResourceParser.getDefaultBgId(context);//通过调用 ResourceParser.getDefaultBgId(context) 方法来获取默认背景 ID 并赋值给整型变量 bgId。 + String snippet = ""; + Intent intent = new Intent(context, NoteEditActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); + intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); + intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); + /** + * 创建一个 Intent 对象 intent,将 NoteEditActivity 类作为目标 Activity,并添加一些额外参数,如小部件 ID、小部件类型等信息,以及标志位 FLAG_ACTIVITY_SINGLE_TOP。 + * + */ + Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);//查询指定小部件所关联的笔记记录, + if (c != null && c.moveToFirst()) { + if (c.getCount() > 1) { + Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]); + c.close(); + return; + } + snippet = c.getString(COLUMN_SNIPPET); + bgId = c.getInt(COLUMN_BG_COLOR_ID); + intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); + intent.setAction(Intent.ACTION_VIEW); + } else { + snippet = context.getResources().getString(R.string.widget_havenot_content); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + } + /** + * 查询结果是否为空,分别进行不同操作 + */ + + if (c != null) { + c.close(); + }// Cursor 对象 c, + + RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());//rv,将其与小部件布局文件对应起来。 + rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); + intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); + /** + * Generate the pending intent to start host for the widget + */ + PendingIntent pendingIntent = null; + if (privacyMode) { + rv.setTextViewText(R.id.widget_text, + context.getString(R.string.widget_under_visit_mode));//设置小部件的背景图片。 + pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent( + context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); + } else { + rv.setTextViewText(R.id.widget_text, snippet); + pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, + PendingIntent.FLAG_UPDATE_CURRENT); + } + + rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); + appWidgetManager.updateAppWidget(appWidgetIds[i], rv);//更新指定小部件的布局和显示内容。 + } + } + } + /** + * update 的私有重载方法是一个私有方法,接受四个参数:上下文对象 context、小部件管理器 appWidgetManager、小部件 ID 列表 appWidgetIds 和一个布尔型参数 privacyMode,表示是否启用隐私模式。在该方法中,我们可以根据是否启用隐私模式来更新小部件的显示内容,例如显示隐私模式的提示信息等。 + */ + + protected abstract int getBgResourceId(int bgId); + + protected abstract int getLayoutId(); + + protected abstract int getWidgetType(); +} diff --git a/doc/精读代码(注释)/张嘉欣注释/widget/NoteWidgetProvider_2x.java b/doc/精读代码(注释)/张嘉欣注释/widget/NoteWidgetProvider_2x.java new file mode 100644 index 0000000..3840c1d --- /dev/null +++ b/doc/精读代码(注释)/张嘉欣注释/widget/NoteWidgetProvider_2x.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.ResourceParser; + + +public class NoteWidgetProvider_2x extends NoteWidgetProvider { + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + } + + /** + * 扩展了NoteWidgetProvider 类的 Java 类 NoteWidgetProvider_2x + * @return + */ + + @Override + protected int getLayoutId() { + return R.layout.widget_2x; + }//它返回一个布局资源 ID + + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); + }//背景 ID 返回相应的背景资源 ID + + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_2X; + }//用于获取小部件的类型 +} diff --git a/doc/精读代码(注释)/张嘉欣注释/widget/NoteWidgetProvider_4x.java b/doc/精读代码(注释)/张嘉欣注释/widget/NoteWidgetProvider_4x.java new file mode 100644 index 0000000..333a63a --- /dev/null +++ b/doc/精读代码(注释)/张嘉欣注释/widget/NoteWidgetProvider_4x.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.ResourceParser; + + +public class NoteWidgetProvider_4x extends NoteWidgetProvider { + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + }//NoteWidgetProvider_4x 是一个扩展自 NoteWidgetProvider 类的 Java 类 + + protected int getLayoutId() { + return R.layout.widget_4x; + }//它返回一个布局资源 ID + + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); + }//这是一个受保护的方法,其作用是根据传入的背景 ID 返回相应的背景资源 ID。 + + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_4X; + } +}//用于获取小部件的类型 diff --git a/doc/精读代码(注释)/闵心诚注释/ui/NoteEditText.java b/doc/精读代码(注释)/闵心诚注释/ui/NoteEditText.java new file mode 100644 index 0000000..e26a635 --- /dev/null +++ b/doc/精读代码(注释)/闵心诚注释/ui/NoteEditText.java @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +//许可证的声明 + +package net.micode.notes.ui;//引入net.minodes.notes.ui这个包 + +import android.content.Context;//上面的几个import引入了这个java类将要用到的功能包,以便提供实现便签文本编辑的必要工具 +import android.graphics.Rect; +import android.text.Layout; +import android.text.Selection;//选择 +import android.text.Spanned; +import android.text.TextUtils; +import android.text.style.URLSpan; +import android.util.AttributeSet;//属性,特征 +import android.util.Log; +import android.view.ContextMenu; +import android.view.KeyEvent; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.widget.EditText;//编辑文本 + +import net.micode.notes.R; + +import java.util.HashMap; +import java.util.Map;//上面的几个import引入了这个java类将要用到的功能包,以便提供实现便签文本编辑的必要工具 +//引入包库 +public class NoteEditText extends EditText {//声明了一个公有类NoteEditText,它继承了EditText + private static final String TAG = "NoteEditText";//标志为字符串"NoteEditText" + private int mIndex;//建立字符,整型的HASH表,用于进行电话、网站、邮箱的链接。 + private int mSelectionStartBeforeDelete;//语句:声明整型变量,获取删除文本前的位置 + + private static final String SCHEME_TEL = "tel:" ;//语句:声明字符串常量,标志电话、网址、邮件 + private static final String SCHEME_HTTP = "http:" ;//文本里 网页类型的内容 + private static final String SCHEME_EMAIL = "mailto:" ;//声明字符串常量,标志电话、网址及邮件 + + private static final Map sSchemaActionResMap = new HashMap();//语句块:建立一个字符和整数的hash表,用于链接电话,网站,还有邮箱 + 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); + } + + /** + * Call by the {@link NoteEditActivity} to delete or add edit text + */ + public interface OnTextViewChangeListener {//接口:该接口用于实现对TextView组件中的文字信息进行修改 + /** + * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens + * and the text is null + */ + void onEditTextDelete(int index, String text); + + /** + * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} + * happen + */ + void onEditTextEnter(int index, String text); + + /** + * Hide or show item option when text change + */ + void onTextChange(int index, boolean hasText);//当触发删除文本KeyEvent时删除文本 + } + + private OnTextViewChangeListener mOnTextViewChangeListener; + + public NoteEditText(Context context) { + super(context, null); + mIndex = 0; + } + + public void setIndex(int index) { + mIndex = index; + }//文字更改时隐藏或显示项目选项 + + public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { + mOnTextViewChangeListener = listener; + } + + public NoteEditText(Context context, AttributeSet attrs) { + super(context, attrs, android.R.attr.editTextStyle); + } + + public NoteEditText(Context context, AttributeSet attrs, int defStyle) {//自动初始化 + super(context, attrs, defStyle);//根据defstyle自动初始化 + // TODO Auto-generated constructor stub + } + + @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();//用布局控件layout根据x,y的新值设置新的位置 + int line = layout.getLineForVertical(y);//语句:获取纵向的行数 + int off = layout.getOffsetForHorizontal(line, x);//语句:获取横向的偏移量 + Selection.setSelection(getText(), off);//更新光标位置 + break; + } + + return super.onTouchEvent(event);//语句:这是调用父类的方法,当屏幕有Touch事件时,此方法就会被调用。 + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) {//这个函数规定了当用户按下按键瞬间系统的响应 + switch (keyCode) {//根据按键的KeyCode来处理 + case KeyEvent.KEYCODE_ENTER://按下回车时,如果mOnTextViewChangeListener存在则返回false + if (mOnTextViewChangeListener != null) { + return false; + } + break; + case KeyEvent.KEYCODE_DEL://按下删除时设置了光标位置 + mSelectionStartBeforeDelete = getSelectionStart();//“删除”按键 + break; + default: + break; + } + return super.onKeyDown(keyCode, event); + } + + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) {//这个函数规定了当用户松开按键瞬间系统的响应 + switch(keyCode) {//据按键的 Unicode 编码值来处理,有删除和进入2种操作 + case KeyEvent.KEYCODE_DEL://若触发修改且文档不为空,则调用前面代码的onEditTextDelete函数进行文本删除 + if (mOnTextViewChangeListener != null) {//若是被修改过 + if (0 == mSelectionStartBeforeDelete && mIndex != 0) {//之前被修改 + mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());//利用上文OnTextViewChangeListener对KEYCODE_DEL按键情况的删除函数进行删除 + return true;//利用上文OnTextViewChangeListener对KEYCODE_DEL按键情况的删除函数进行删除 + } + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted");//其他情况报错,文档的改动监听器并没有建立 + } + break; + case KeyEvent.KEYCODE_ENTER://若文档改动监听器已建立,则获取当前位置和文本,并根据获取的信息调用onEditTextEnter函数进行文本增添 + if (mOnTextViewChangeListener != null) {//同上也是分为监听器是否建立2种情况 + int selectionStart = getSelectionStart();//获取位置 + String text = getText().subSequence(selectionStart, length()).toString();//获取文本 + 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); + } + + @Override + protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {//函数功能:当焦点发生变化时,会自动调用该方法来处理焦点改变的事件 + if (mOnTextViewChangeListener != null) {//监听器已建立 + if (!focused && TextUtils.isEmpty(getText())) {//获取焦点文本不为空 + mOnTextViewChangeListener.onTextChange(mIndex, false);//隐藏事件选项 + } else { + mOnTextViewChangeListener.onTextChange(mIndex, true); + } + } + super.onFocusChanged(focused, direction, previouslyFocusedRect); + } + + @Override + protected void onCreateContextMenu(ContextMenu menu) {//这个重载函数定义了新建文本菜单的过程 + if (getText() instanceof Spanned) {//java 中的instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例。instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。 + 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);//设置url + if (urls.length == 1) {//设置url的信息的范围值 + int defaultResId = 0;//默认的资源ID值为0 + for(String schema: sSchemaActionResMap.keySet()) {//获取计划表中所有的key值 + if(urls[0].getURL().indexOf(schema) >= 0) {//若url可以添加则在添加后将defaultResId置为key所映射的值 + 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); + } +} diff --git a/doc/精读代码(注释)/闵心诚注释/ui/NoteItemData.java b/doc/精读代码(注释)/闵心诚注释/ui/NoteItemData.java new file mode 100644 index 0000000..9a52ea0 --- /dev/null +++ b/doc/精读代码(注释)/闵心诚注释/ui/NoteItemData.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui;//引入notes.ui这个包 + +import android.content.Context;//引入了一系列的功能包以便实现这个类的相关功能 +import android.database.Cursor;//光标 +import android.text.TextUtils; + +import net.micode.notes.data.Contact; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns;//便签栏 +import net.micode.notes.tool.DataUtils; + + +public class NoteItemData {//常量标记和数据 + static final String [] PROJECTION = new String [] {//常量标记和数据 + NoteColumns.ID,//每个note都有独一无二的id + NoteColumns.ALERTED_DATE,//设置的警报提醒时间 + NoteColumns.BG_COLOR_ID,//背景颜色的id + NoteColumns.CREATED_DATE,//创建的时间 + NoteColumns.HAS_ATTACHMENT,//是否有附件。如果是一个text note,它不会有附件,如果是一个多媒体附件,会有至少一个附件 + NoteColumns.MODIFIED_DATE,//修改日期 + NoteColumns.NOTES_COUNT,//便签数量 + NoteColumns.PARENT_ID,//父id + NoteColumns.SNIPPET,//文件夹名称或者文本注释内容 + NoteColumns.TYPE,// 某一列note的种类,是text note还是folder + NoteColumns.WIDGET_ID,// 小挂件的序号 + NoteColumns.WIDGET_TYPE,//小挂件的类型 + }; + + private static final int ID_COLUMN = 0; + private static final int ALERTED_DATE_COLUMN = 1; + private static final int BG_COLOR_ID_COLUMN = 2; + private static final int CREATED_DATE_COLUMN = 3; + private static final int HAS_ATTACHMENT_COLUMN = 4; + private static final int MODIFIED_DATE_COLUMN = 5; + private static final int NOTES_COUNT_COLUMN = 6; + private static final int PARENT_ID_COLUMN = 7; + private static final int SNIPPET_COLUMN = 8; + private static final int TYPE_COLUMN = 9; + private static final int WIDGET_ID_COLUMN = 10; + private static final int WIDGET_TYPE_COLUMN = 11; + + private long mId; + private long mAlertDate; + private int mBgColorId; + private long mCreatedDate; + private boolean mHasAttachment; + private long mModifiedDate; + private int mNotesCount; + private long mParentId; + private String mSnippet; + private int mType; + private int mWidgetId; + private int mWidgetType; + private String mName; + private String mPhoneNumber; + + private boolean mIsLastItem;//判断是否为最后的项 + private boolean mIsFirstItem;//判断是否为最开始的项 + private boolean mIsOnlyOneItem;// 判断是否只有一个便签,或者一个文件夹 + private boolean mIsOneNoteFollowingFolder;//判断文件夹下是否只有一个便签 + private boolean mIsMultiNotesFollowingFolder;//判断文件夹下是否有多个便签 + + public NoteItemData(Context context, Cursor cursor) {//第一个函数是类NoteItemData的构造函数,它完成了以下工作 + 1.对于这个类的所有私有m型变量,通过cursor调用json中相应数据进行初始化 + 2.对mPhoneNumber和mName进行单独处理 + 3.检查cursor的位置 + mId = cursor.getLong(ID_COLUMN);//getxxx为转换格式 + 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);//获得字符串 + 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); + + mPhoneNumber = "";//初始化电话号码的信息 + 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; + } + } + } + + if (mName == null) { + mName = ""; + } + checkPostion(cursor); + } + + private void checkPostion(Cursor cursor) {//根据光标位置设置标记 + mIsLastItem = cursor.isLast() ? true : false;//分别为各种描述状态的变量进行赋值 + mIsFirstItem = cursor.isFirst() ? true : false; + mIsOnlyOneItem = (cursor.getCount() == 1); + mIsMultiNotesFollowingFolder = false;//初始化“多重子文件”“单一子文件”2个标记 + mIsOneNoteFollowingFolder = false; + + if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { + int position = cursor.getPosition(); + 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; + } else { + mIsOneNoteFollowingFolder = true; + } + } + if (!cursor.moveToNext()) { + throw new IllegalStateException("cursor move to previous but can't move back"); + } + } + } + } + + public boolean isOneFollowingFolder() { + return mIsOneNoteFollowingFolder; + }//.接下来都是获取标记的函数 + + public boolean isMultiFollowingFolder() { + return mIsMultiNotesFollowingFolder; + }//若数据父id为保存至文件夹模式的id且满足电话号码单元不为空,则isCallRecord为true + + public boolean isLast() { + return mIsLastItem; + }//判断是否是最后一个项 + + public String getCallName() { + return mName; + }//获得便签的姓名 + + public boolean isFirst() { + return mIsFirstItem; + }// 判断是否是第一个项 + + public boolean isSingle() { + return mIsOnlyOneItem; + }//判断是否只有一个项 + + public long getId() { + return mId; + }//获得对应的ID值 + + public long getAlertDate() { + return mAlertDate; + }//获得对应的提醒时间 + + public long getCreatedDate() { + return mCreatedDate; + }//获得创建的时间 + + public boolean hasAttachment() { + return mHasAttachment; + }// 判断是否关联桌面挂件 + + public long getModifiedDate() { + return mModifiedDate; + }//获得修改的时间 + + public int getBgColorId() { + return mBgColorId; + }//获得背景颜色的索引 + + public long getParentId() { + return mParentId; + }//获得父进程的id + + public int getNotesCount() { + return mNotesCount; + }//获得便签数量 + + public long getFolderId () { + return mParentId; + }//获得文件夹id + + public int getType() { + return mType; + }//获得项的类型 + + public int getWidgetType() { + return mWidgetType; + }//获得桌面挂件的类型 + + public int getWidgetId() { + return mWidgetId; + }//获得获得桌面挂件id + + public String getSnippet() { + return mSnippet; + }//获得文件夹名称 + + public boolean hasAlert() { + return (mAlertDate > 0); + }//判读此便签是否有提醒 + + public boolean isCallRecord() {//判断便签项是否为CallRecord + return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));//如果父类id保存至文件夹模式并且电话号码单元不为空 + } + + public static int getNoteType(Cursor cursor) { + return cursor.getInt(TYPE_COLUMN); + }//获得便签的类型 +} diff --git a/doc/精读代码(注释)/闵心诚注释/ui/NotesListActivity.java b/doc/精读代码(注释)/闵心诚注释/ui/NotesListActivity.java new file mode 100644 index 0000000..45471a8 --- /dev/null +++ b/doc/精读代码(注释)/闵心诚注释/ui/NotesListActivity.java @@ -0,0 +1,966 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui;//这个类包含在net.micode.notes.ui这个包里 + +import android.app.Activity;//引入了一系列实现这个类功能所必须的类 +import android.app.AlertDialog; +import android.app.Dialog; +import android.appwidget.AppWidgetManager;//APP的界宽 +import android.content.AsyncQueryHandler; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.os.AsyncTask; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.util.Log; +import android.view.ActionMode; +import android.view.ContextMenu; +import android.view.ContextMenu.ContextMenuInfo; +import android.view.Display; +import android.view.HapticFeedbackConstants; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.View.OnCreateContextMenuListener; +import android.view.View.OnTouchListener; +import android.view.inputmethod.InputMethodManager; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.AdapterView.OnItemLongClickListener; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ListView; +import android.widget.PopupMenu; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.remote.GTaskSyncService; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.tool.BackupUtils; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.HashSet; + +public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener {//这个类继承于Activity类,实现了两个接口,分别是点击监听器,和长按监听器,即在这个类的界面实现对这两种操作的响应,这是整个project的主类 + private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;//声明并赋值一些不可更改的私有属性 + + private static final int FOLDER_LIST_QUERY_TOKEN = 1;//查询记号,同上,文件夹请求时使用(如:长按便签然后点移动到文件夹调用) + + private static final int MENU_FOLDER_DELETE = 0;//菜单中的删除文件夹项对应的int值,(个人决定使用int类型,是方便和其他数据处理,而且处理速度更快) + + private static final int MENU_FOLDER_VIEW = 1;//菜单中的查看文件夹对应的int值 + + private static final int MENU_FOLDER_CHANGE_NAME = 2;//菜单中改文件夹名项对应的int值 + + private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";//用于第一次打开小米便签的判断 + + private enum ListEditState {//列表编辑状态类 + NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER + }; + + private ListEditState mState;//利用其它类声明一些私有对象 + + private BackgroundQueryHandler mBackgroundQueryHandler;//后台疑问处理 + + private NotesListAdapter mNotesListAdapter;//便签列表配适器 + + private ListView mNotesListView;//主界面的视图 + + private Button mAddNewNote;//最下方添加便签的按钮 + + private boolean mDispatch;//是否调度的判断变量 + + private int mOriginY;// 首次触摸时屏幕上的垂直距离(y值) + + private int mDispatchY;//重新调度时的触摸的在屏幕上的垂直距离 + + private TextView mTitleBar;//子文件夹下的 标头 + + private long mCurrentFolderId;//当前文件夹的ID + + private ContentResolver mContentResolver;//提供内容分析 + + private ModeCallback mModeCallBack;//返回调用方法 + + private static final String TAG = "NotesListActivity";//名称(可用于日志文件调试) + + public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;//列表滚动速度 + + private NoteItemData mFocusNoteDataItem;//光标指向的物件的数据内容 + + private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";// 语句:定义私有字符串变量 + + private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"//用于表明处于父文件夹下(主列表) + + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" + + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + + NoteColumns.NOTES_COUNT + ">0)"; + + private final static int REQUEST_CODE_OPEN_NODE = 102;//语句:请求代码开放节点 + private final static int REQUEST_CODE_NEW_NODE = 103;//语句:请求代码新节点 + + @Override + protected void onCreate(Bundle savedInstanceState) {//创建类 + super.onCreate(savedInstanceState);//super相当于是指向当前对象的父类,可以用super.xxx来引用父类的成员 引用父类onCreate函数 + setContentView(R.layout.note_list);//设置内容的视图 + initResources();//语句:初始化资源 + + /** + * Insert an introduction when user firstly use this application + */ + setAppInfoFromRawRes(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) {//对子模块的一些数据进行分析 + if (resultCode == RESULT_OK//结果值与要求值正确 + && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { + mNotesListAdapter.changeCursor(null); + } else {//语句:super调用父类的protected函数,创建窗口时使用 + super.onActivityResult(requestCode, resultCode, data);//调用父类Activity的onActivityResult方法 将数据返回给父类处理 + } + } + + private void setAppInfoFromRawRes() {//通过原生资源设置APP信息 + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);//Android平台给我们提供了一个SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数 + if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {//其实可以进行反向判断,这样不用一段很长的代码放在一个if里面。 + StringBuilder sb = new StringBuilder();//读取原生资源信息 + InputStream in = null;//输入流初始设置为空 + try {//从原始配置文件当中获取基本信息 + in = getResources().openRawResource(R.raw.introduction);//加载Welcome to use MIUI notes!(本地xml文件) + if (in != null) {//如果信息不为空 + InputStreamReader isr = new InputStreamReader(in);//使用指定的字符集读取字节并将它们解码为字符 + BufferedReader br = new BufferedReader(isr);//构建输入管道 + char [] buf = new char[1024]; + int len = 0; + while ((len = br.read(buf)) > 0) { + sb.append(buf, 0, len); + } + } else { + Log.e(TAG, "Read introduction file error"); + return; + } + } catch (IOException e) {//IO错误处理 + e.printStackTrace(); + return; + } finally { + if(in != null) { + try { + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,//.新建笔记 + AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, + ResourceParser.RED); + note.setWorkingText(sb.toString());//设置文本数据 + if (note.saveNote()) {//这是一个判断语句,判断便签是否保存成功 + sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();//保存笔记 + } else { + Log.e(TAG, "Save introduction note error");//如果便签保存不成功,则把错误信息打印到日志里面。 + return; + } + } + } + + @Override + protected void onStart() {//功能描述:一个activity有生命周期,其中start代表生命周期开始 + 函数实现:调用父类(超类)中的onStart方法,并用startAsyncNotesListQuery同步列表的便签信息 + super.onStart();//调用父类,启动活动 + startAsyncNotesListQuery();//异步便签问题? + } + + private void initResources() {//初始化资源 + mContentResolver = this.getContentResolver();//获取应用数据 + mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());//动态创建后台请求处理器的实例 + mCurrentFolderId = Notes.ID_ROOT_FOLDER;//当前文件夹ID是根目录ID + mNotesListView = (ListView) findViewById(R.id.notes_list);//根据R文件中的id值查询到相应的View,然后返回 + mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null),//使用布局填充器增加页脚视图 + null, false); + mNotesListView.setOnItemClickListener(new OnListItemClickListener());//设置视图点击监听器 + mNotesListView.setOnItemLongClickListener(this);//设置长按监听器 + mNotesListAdapter = new NotesListAdapter(this);//创建便签视图配置器 + mNotesListView.setAdapter(mNotesListAdapter);//设置便签视图配置器 + mAddNewNote = (Button) findViewById(R.id.btn_new_note);//findViewById 是安卓编程的定位函数,主要是引用.R文件里的引用名,这里是在activity中获取该按钮 + mAddNewNote.setOnClickListener(this);//屏幕点击监视 + mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());//语句:屏幕点击监听 + mDispatch = false;//是否调度,主要用于新建便签模块 + mDispatchY = 0;//初始y值设置为0, + mOriginY = 0;//加载文件夹下的标头资源 + mTitleBar = (TextView) findViewById(R.id.tv_title_bar);//.功能描述:设置Title bar,也就是app页面顶部的返回、选项、信息描述 + mState = ListEditState.NOTE_LIST;// 功能描述:设置状态 + mModeCallBack = new ModeCallback();//implements是一个类实现连接一个接口用的关键字,它是用来实现接口中定义的抽象方法 + } + + private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {//implements声明自己使用一个或多个接口 + private DropdownMenu mDropDownMenu;//下拉菜单 + private ActionMode mActionMode;//动作方式 + private MenuItem mMoveMenu;//移动菜单 + + public boolean onCreateActionMode(ActionMode mode, Menu menu) {//ActionMode 是 Android 提供的一种实现菜单方式 + getMenuInflater().inflate(R.menu.note_list_options, menu);//语句:layout的xml布局文件实例化为View类对象 + menu.findItem(R.id.delete).setOnMenuItemClickListener(this);//这里关联上了listerner,专门关联在菜单的按键 + mMoveMenu = menu.findItem(R.id.move);//调用下面的更新菜单函数 + if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER//如果父类id在文件夹中保存或者用户文件数量为零,设置移动菜单为不可见,否者设为可见 + || DataUtils.getUserFolderCount(mContentResolver) == 0) { + mMoveMenu.setVisible(false); + } else {//代码块:设置菜单项目为可见 + mMoveMenu.setVisible(true); + mMoveMenu.setOnMenuItemClickListener(this); + } + mActionMode = mode; + mNotesListAdapter.setChoiceMode(true);//语句:进入选择模式 + mNotesListView.setLongClickable(false);//语句:关闭长按列表项发生事件功能 + mAddNewNote.setVisibility(View.GONE);//语句:隐藏了新增便签按钮 + + View customView = LayoutInflater.from(NotesListActivity.this).inflate(//设置用户界面 + R.layout.note_list_dropdown_menu, null);//加载下拉菜单的布局 + mode.setCustomView(customView); + mDropDownMenu = new DropdownMenu(NotesListActivity.this,//创建新的下拉菜单 + (Button) customView.findViewById(R.id.selection_menu), + R.menu.note_list_dropdown);//语句:为view添加dropDownMenu(包含一个全选操作) + mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ + public boolean onMenuItemClick(MenuItem item) {//点击菜单时,设置为全选并更新菜单 + mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); + updateMenu(); + return true; + } + + }); + return true; + } + + private void updateMenu() {///* + * 作用:在多选便签/便签文件夹时调用,用于更新多选下拉菜单 + * 实现:用便签列表管理器mNotesListAdapter中的函数getSelectedCount获取选中个数,设置菜单标题为选中个数, + * 当没有全选时,子菜单标题设为全选,否则,设为取消全选 + * 参数:无 + int selectedCount = mNotesListAdapter.getSelectedCount();//获取被勾选的条目数量 + // Update dropdown menu + String format = getResources().getString(R.string.menu_select_title, selectedCount);//从原始资源中读取信息更改下拉菜单内容 + mDropDownMenu.setTitle(format);//更改标题 + MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);//全选操作 + if (item != null) {//代码块:当全选成功,则将“全选”菜单项改为“取消全选”菜单,否则仍保持“全选”菜单项 + if (mNotesListAdapter.isAllSelected()) { + item.setChecked(true); + item.setTitle(R.string.menu_deselect_all); + } else { + item.setChecked(false); + item.setTitle(R.string.menu_select_all); + } + } + } + + public boolean onPrepareActionMode(ActionMode mode, Menu menu) {//准备动作模式 + // TODO Auto-generated method stub + return false; + } + + public boolean onActionItemClicked(ActionMode mode, MenuItem item) {//菜单动作触发标记 + // TODO Auto-generated method stub + return false; + } + + public void onDestroyActionMode(ActionMode mode) {//销毁动作模式,设置便签可见 + mNotesListAdapter.setChoiceMode(false);//设置笔记列表适配器选择方式 + mNotesListView.setLongClickable(true);//长按操作 + mAddNewNote.setVisibility(View.VISIBLE);//调整新建笔记为可见 + } + + public void finishActionMode() { + mActionMode.finish(); + }//动作模式结束 + + public void onItemCheckedStateChanged(ActionMode mode, int position, long id,//勾选状态改变时,更改勾选标志,更新菜单 + boolean checked) {//点击菜单选项触发操作 + mNotesListAdapter.setCheckedItem(position, checked); + updateMenu();//语句:更新菜单 + } + + public boolean onMenuItemClick(MenuItem item) {//判断菜单是否被点击 + if (mNotesListAdapter.getSelectedCount() == 0) {//当勾选数为零时(即未点击),创建文本并显示 + Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),//Toast-Android系统中一种消息框类型 + Toast.LENGTH_SHORT).show(); + return true; + } + + switch (item.getItemId()) {//根据id号判断是删除还是移动 + case R.id.delete://点击delete选项 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);//警告对话框 + builder.setTitle(getString(R.string.alert_title_delete));//设置“删除选中的便签”的title + builder.setIcon(android.R.drawable.ic_dialog_alert);//设置提醒删除的图片 + builder.setMessage(getString(R.string.alert_message_delete_notes,//语句:设置警告对话框的图标 + mNotesListAdapter.getSelectedCount())); + builder.setPositiveButton(android.R.string.ok,//设置否定按钮 + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + batchDelete(); + } + }); + builder.setNegativeButton(android.R.string.cancel, null);//取消的按键的视图 + builder.show(); + break; + case R.id.move://点击move选项 + startQueryDestinationFolders();//启动查询目标文件函数 + break; + default://语句:default,switch语句结束 + return false; + } + return true; + } + } + + private class NewNoteOnTouchListener implements OnTouchListener {//.触摸便签监听器 + + public boolean onTouch(View v, MotionEvent event) {//功能描述:响应触摸新建便签的按键的方法 + 函数实现:分为按下和移动和其他情况的判断 + 参数描述: + @v 视图 + switch (event.getAction()) {//获取不同动作对应不同操作 + case MotionEvent.ACTION_DOWN: {//如果是创建新便签,通过计算调整界面大小 + Display display = getWindowManager().getDefaultDisplay(); + int screenHeight = display.getHeight();//语句:获取屏幕高度 + int newNoteViewHeight = mAddNewNote.getHeight();//语句: 获取新增便签的高度 + int start = screenHeight - newNoteViewHeight;// 起始的y值 + int eventY = start + (int) event.getY();//event.getY相当于点击到的地方的y值 + /** + * Minus TitleBar's height + */ + if (mState == ListEditState.SUB_FOLDER) {//减去标题栏的高度 + eventY -= mTitleBar.getHeight(); + start -= mTitleBar.getHeight(); + } + /** + * HACKME:When click the transparent part of "New Note" button, dispatch + * the event to the list view behind this button. The transparent part of + * "New Note" button could be expressed by formula y=-0.12x+94(Unit:pixel) + * and the line top of the button. The coordinate based on left of the "New + * Note" button. The 94 represents maximum height of the transparent part. + * Notice that, if the background of the button changes, the formula should + * also change. This is very bad, just for the UI designer's strong requirement. + */ + if (event.getY() < (event.getX() * (-0.12) + 94)) {//如果当前点击的位置不在“写便签”区域内 + View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1//最后得到最后一个元素的view(视图) + - mNotesListView.getFooterViewsCount());//减去页脚下元素布局数量 + if (view != null && view.getBottom() > start//如果不在新建便签的按钮上,重新调度响应按键 + && (view.getTop() < (start + 94))) { + mOriginY = (int) event.getY();//初始按下时的垂直距离 + mDispatchY = eventY;//调度时的垂直距离 + event.setLocation(event.getX(), mDispatchY);//重新给触摸事件定位 + mDispatch = true;//触摸事件定位 + return mNotesListView.dispatchTouchEvent(event);//重新调度,即重新执行 + } + } + break; + } + case MotionEvent.ACTION_MOVE: {//如果是移动操作,调度动作顺序 + if (mDispatch) { + mDispatchY += (int) event.getY() - mOriginY;//移动后,触摸事件位置发生变换 + event.setLocation(event.getX(), mDispatchY);//重新赋值 + return mNotesListView.dispatchTouchEvent(event);//重新调度,即重新执行 + } + break; + } + default: {// 其他情况 + if (mDispatch) { + event.setLocation(event.getX(), mDispatchY); + mDispatch = false; + return mNotesListView.dispatchTouchEvent(event); + } + break; + } + } + return false; + } + + }; + + private void startAsyncNotesListQuery() {//同步便签列表请求 + String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION//如果当前文件id与保存在文件夹的id相同,selection为文件夹模式,否则为常规模式 + : NORMAL_SELECTION; + mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,//后台异步对数据库进行操作,加快数据处理速度 + Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { + String.valueOf(mCurrentFolderId) + }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); + } + + private final class BackgroundQueryHandler extends AsyncQueryHandler {//背景请求处理器 + public BackgroundQueryHandler(ContentResolver contentResolver) { + super(contentResolver); + } + + @Override + protected void onQueryComplete(int token, Object cookie, Cursor cursor) {//异步查询框架AsyncQueryHandler,当单查询完毕后,会调用onQueryComplete(token, cookie, cursor)通知查询完毕,并且传回cursor + switch (token) { + case FOLDER_NOTE_LIST_QUERY_TOKEN://便签列表请求 + mNotesListAdapter.changeCursor(cursor);//如果是便签查询被采用,更改光标位置 + break; + case FOLDER_LIST_QUERY_TOKEN://文件夹请求 + if (cursor != null && cursor.getCount() > 0) {//如果下面有便签,打开文件夹列表弹窗 + showFolderListMenu(cursor);//显示文件夹目录 + } else { + Log.e(TAG, "Query folder failed");//写入错误异常日志 + } + break; + default: + return; + } + } + } + + private void showFolderListMenu(Cursor cursor) {//批量删除 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);//语句:声明一个警告对话框 + builder.setTitle(R.string.menu_title_select_folder);//对话框的title是“选择文件夹” + final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor);//文件夹列表配适器 + builder.setAdapter(adapter, new DialogInterface.OnClickListener() { + + public void onClick(DialogInterface dialog, int which) {//代码块:为对话框设置监听事件 + DataUtils.batchMoveToFolder(mContentResolver,//移动到文件夹下 + mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); + Toast.makeText( + NotesListActivity.this, + getString(R.string.format_move_notes_to_folder, + mNotesListAdapter.getSelectedCount(), + adapter.getFolderName(NotesListActivity.this, which)), + Toast.LENGTH_SHORT).show(); + mModeCallBack.finishActionMode(); + } + }); + builder.show(); + } + + private void createNewNote() {//创建新便签 + Intent intent = new Intent(this, NoteEditActivity.class);//语句:新建一个意图,与NoteEditActivity相关联 + intent.setAction(Intent.ACTION_INSERT_OR_EDIT);//intent的隐式调用。ACTION_INSERT_OR_EDIT选择一个新条目或插入一个新条目去编辑它。setAction即为寻找能响应这个action的activity + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);//语句:设置键对值 + this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);//这个活动发出请求,等待下一个活动返回数据 + } + + private void batchDelete() {//批量删除便签 + new AsyncTask>() {//功能描述: 批量删除:删除时候,会判断是否为桌面挂件 + 函数实现:调用DataUtils的batchDeleteNotes + protected HashSet doInBackground(Void... unused) { + HashSet widgets = mNotesListAdapter.getSelectedWidget(); + if (!isSyncMode()) {//异步处理任务 + // if not synced, delete notes directly + if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter + .getSelectedItemIds())) { + } else {//如果不是同步模式则将笔记移到垃圾文件夹,若转移失败打印错误信息 + Log.e(TAG, "Delete notes error, should not happens"); + } + } else { + // in sync mode, we'll move the deleted note into the trash + // folder + if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter//同步状态先放入垃圾箱 + .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) {//同步状态先放入回收站 + Log.e(TAG, "Move notes to trash folder error, should not happens"); + } + } + return widgets; + } + + @Override + protected void onPostExecute(HashSet widgets) {//这是一个循环体结构,如果id不等的话,会进行更新id的操作。 + if (widgets != null) { + for (AppWidgetAttribute widget : widgets) { + if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID//此处判断是否为一个widget + && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {//更新widget信息 + updateWidget(widget.widgetId, widget.widgetType);//更新桌面挂件 + } + } + } + mModeCallBack.finishActionMode(); + } + }.execute(); + } + + private void deleteFolder(long folderId) {//删除文件夹 + if (folderId == Notes.ID_ROOT_FOLDER) {//不在列表里,输出错误信息 + Log.e(TAG, "Wrong folder id, should not happen " + folderId); + return; + } + + HashSet ids = new HashSet();//下面会判断删除的文件夹里是否包含与桌面挂件相关联的便签 + ids.add(folderId);//把文件夹id加入进去 + HashSet widgets = DataUtils.getFolderNoteWidget(mContentResolver, + folderId); + if (!isSyncMode()) {//如果不同步,直接删除 + // if not synced, delete folder directly + DataUtils.batchDeleteNotes(mContentResolver, ids); + } else {//否则放到回收站 + // in sync mode, we'll move the deleted folder into the trash folder + DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER); + } + if (widgets != null) {//如果存在对应桌面挂件,那么判断挂件信息,如果挂件id有效且挂件类型有效,则更新挂件信息 + for (AppWidgetAttribute widget : widgets) { + if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { + updateWidget(widget.widgetId, widget.widgetType); + } + } + } + } + + private void openNode(NoteItemData data) {//打开便签 + Intent intent = new Intent(this, NoteEditActivity.class);//功能描述:打开便签,创建新的活动,并且等待返回值 + 函数实现:用intent传递数据 + 参数描述: + @data 要打开的便签的数据项 + intent.setAction(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, data.getId()); + this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); + } + + private void openFolder(NoteItemData data) {//打开文件夹 + mCurrentFolderId = data.getId();//获取当前文件夹的ID + startAsyncNotesListQuery();//开始异步的便签列表反馈 + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {//对状态的操作 + mState = ListEditState.CALL_RECORD_FOLDER;//对标题栏的操作 + mAddNewNote.setVisibility(View.GONE);//语句:将button“新建便签”置为不可见 + } else {//不然状态设置为子文件夹 + mState = ListEditState.SUB_FOLDER; + } + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {// 如果当前id是保存在文件夹的id,设置标题内容为文件夹名字,否则设置为文本的前部片段内容 + mTitleBar.setText(R.string.call_record_folder_name);//title设置为call notes + } else { + mTitleBar.setText(data.getSnippet());//否则文本的前部片段内容,即文件夹名称 + } + mTitleBar.setVisibility(View.VISIBLE);// 语句:将Activity的title设置为可见 + } + + public void onClick(View v) {//点击时进行的响应 + switch (v.getId()) {//得到我们所点击组件的ID号并进行判断 + case R.id.btn_new_note://当点击的组件是btn_new_note的时候创建一个新的标签 + createNewNote();//当点击的组件是btn_new_note的时候创建一个新的标签 + break; + default: + break; + } + } + + private void showSoftInput() {//.显示软键盘 + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);//获得实例 + if (inputMethodManager != null) {//对输入的响应 + inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);//使软键盘显示,第二个参数hideFlags(用来设置是否隐藏)等于0 + } + } + + private void hideSoftInput(View view) {//关闭键盘 + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);//隐藏软键盘 + } + + private void showCreateOrModifyFolderDialog(final boolean create) {//显示创建或者修改文件夹的对话框 + final AlertDialog.Builder builder = new AlertDialog.Builder(this);//初始化对话框 + View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);//加载布局文件dialog_edit_text.xml + final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);//获得et_foler_name这个组件并将其转化为EditText类 + showSoftInput();//显示键盘 + if (!create) {//如果create==false将对话框标题设置为 修改文件夹名称,否则设置为新建文件夹 + if (mFocusNoteDataItem != null) {//关注项不为空 + etName.setText(mFocusNoteDataItem.getSnippet());//获取片段来设置文档 + builder.setTitle(getString(R.string.menu_folder_change_name));//通过构建器设置标题 + } else {//显示此次点击显示为空 + Log.e(TAG, "The long click data item is null");//载入标签tag,报错 + return; + } + } else { + etName.setText(""); + builder.setTitle(this.getString(R.string.menu_create_folder)); + } + + builder.setPositiveButton(android.R.string.ok, null);//对话框设置确定和取消按钮 + builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) {//构建器_创建取消的按键 + hideSoftInput(etName);//隐藏输入 + } + }); + + final Dialog dialog = builder.setView(view).show();//语句:将上述对话框实例化并显示在屏幕上 + final Button positive = (Button)dialog.findViewById(android.R.id.button1);//创建对话框的确认按钮 + positive.setOnClickListener(new OnClickListener() {//设置点击监听器 + public void onClick(View v) {//新建文件夹或者修改文件夹名同时判断其是否合法 + hideSoftInput(etName);//隐藏键盘 + String name = etName.getText().toString();//语句: 获取当前可编辑文本框etName的文本内容 + if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {//检测可视文件夹的名字 + Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),//创建文本 + Toast.LENGTH_LONG).show(); + etName.setSelection(0, etName.length());//语句:全选当前字符串 + return; + } + if (!create) {//若未创建 + if (!TextUtils.isEmpty(name)) {//语句:如果输入不为空 + ContentValues values = new ContentValues();//创建内容取值 + values.put(NoteColumns.SNIPPET, name);//将片段名字添加入value + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);//将文件夹类型添加入value + values.put(NoteColumns.LOCAL_MODIFIED, 1);//将本地修改添加入value + mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID//将内容笔记URI及笔记专栏ID更新至内容解决器 + + "=?", new String[] { + String.valueOf(mFocusNoteDataItem.getId()) + }); + } + } else if (!TextUtils.isEmpty(name)) {//代码块:如果是新建文件夹操作 + ContentValues values = new ContentValues(); + values.put(NoteColumns.SNIPPET, name);//将SNIPPET加入内容值中 + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);//将TYPE加入内容值中 + mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);//将内容_笔记的URI插入到内容解决器 + } + dialog.dismiss();//撤销对话框 + } + }); + + if (TextUtils.isEmpty(etName.getText())) {//etName为空设置按键不可用 + positive.setEnabled(false);//语句:右下的button“ok”不可用,即显示灰色不能点击 + } + /** + * When the name edit text is null, disable the positive button + */ + etName.addTextChangedListener(new TextWatcher() { + public void beforeTextChanged(CharSequence s, int start, int count, int after) {//判断是否在文本更改之前 + // TODO Auto-generated method stub + + } + + public void onTextChanged(CharSequence s, int start, int before, int count) {//当前文本改变触发,文本为空按键不可用,不为空则可用 + if (TextUtils.isEmpty(etName.getText())) {//判断:如果文件夹名称为空,那么便不可用 + positive.setEnabled(false); + } else { + positive.setEnabled(true);//语句:监听输入字符串,如果大于零,则button可以点击 + } + } + + public void afterTextChanged(Editable s) {//.判断是否在文本更改之后 + // TODO Auto-generated method stub + + } + }); + } + + @Override + public void onBackPressed() {//点击后退键时的操作 + switch (mState) {//判断目前所处的状态 + case SUB_FOLDER://前两个状态返回到初始界面最后一个状态返回到桌面 + mCurrentFolderId = Notes.ID_ROOT_FOLDER;//语句:如果是在文件夹中的状态 + mState = ListEditState.NOTE_LIST;//语句:将当前文件夹id修改为根文件夹 + startAsyncNotesListQuery();//语句:将当前状态改为一般状态 + mTitleBar.setVisibility(View.GONE);//语句:隐藏TitleBar,设置为不可见 + break; + case CALL_RECORD_FOLDER://响应已记录文件夹的操作 + mCurrentFolderId = Notes.ID_ROOT_FOLDER;//语句:将当前文件夹id修改为根文件夹 + mState = ListEditState.NOTE_LIST;//便签列表的返回 + mAddNewNote.setVisibility(View.VISIBLE);//语句:设置button“新增便签”可见 + mTitleBar.setVisibility(View.GONE);//语句:隐藏TitleBar,设置为不可见 + startAsyncNotesListQuery(); + break; + case NOTE_LIST://从主界面退出 + super.onBackPressed();//语句:调用原来的onBackPressed方法 + break; + default://其他情况直接break + break; + } + } + + private void updateWidget(int appWidgetId, int appWidgetType) {//更新窗口插件 + Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);//语句:初始化部件大小管理 + if (appWidgetType == Notes.TYPE_WIDGET_2X) {//下面是判断不同类型widget的操作并建立不同的类型 + intent.setClass(this, NoteWidgetProvider_2x.class);//将便签插件提供器的类型设置成内容的类型 + } else if (appWidgetType == Notes.TYPE_WIDGET_4X) {//若插件形式是_4X + intent.setClass(this, NoteWidgetProvider_4x.class); + } else { + Log.e(TAG, "Unspported widget type");//否则显示“不支持的插件类型 + return; + } + + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {// 语句:putExtra中两个参数为键对值,第一个参数为键名 + appWidgetId + }); + + sendBroadcast(intent);//设置成功的结果 + setResult(RESULT_OK, intent);//返回给上一个活动数据 + } + + private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {//对文件夹进行操作的菜单 + if (mFocusNoteDataItem != null) {//当笔记数据项不为空时,设置菜单 + menu.setHeaderTitle(mFocusNoteDataItem.getSnippet());//语句:设置菜单的题目是当前文件夹名字 + menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view);//语句:在菜单中新增项目“查看文件夹” + menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete);//语句:在菜单中新增项目“删除文件夹” + menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name);//语句:在菜单中新增项目“修改文件夹名称” + } + } + }; + + @Override + public void onContextMenuClosed(Menu menu) {//关闭菜单 + if (mNotesListView != null) { + mNotesListView.setOnCreateContextMenuListener(null);//语句:不设置监听事件 + } + super.onContextMenuClosed(menu); + } + + @Override + public boolean onContextItemSelected(MenuItem item) {//对菜单项进行选择对应的相应 + if (mFocusNoteDataItem == null) {//若笔记数据项为空 + Log.e(TAG, "The long click data item is null");//设置标签“长按数据项为空 + return false; + } + switch (item.getItemId()) {//通过获取项目ID,进行switch + case MENU_FOLDER_VIEW://打开文件夹 + openFolder(mFocusNoteDataItem); + break; + case MENU_FOLDER_DELETE://文件夹删除 + AlertDialog.Builder builder = new AlertDialog.Builder(this);//语句:新建一个警告对话框,来警告是否确认删除文件夹 + builder.setTitle(getString(R.string.alert_title_delete));//语句:设置警告对话框题目为“删除” + builder.setIcon(android.R.drawable.ic_dialog_alert);//语句:设置警告对话框图标为”三角感叹号“ + builder.setMessage(getString(R.string.alert_message_delete_folder));// 语句:设置警告信息文本“确认删除文件夹及所包含的便签” + builder.setPositiveButton(android.R.string.ok,//设置取消按键 + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteFolder(mFocusNoteDataItem.getId()); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case MENU_FOLDER_CHANGE_NAME://文件夹改名 + showCreateOrModifyFolderDialog(false);//不显示创建or修改文件夹的对话框 + break; + default: + break; + } + + return true; + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) {//创建菜单这个方法在每一次调用菜单的时候都会执行 + menu.clear();//菜单清空 + if (mState == ListEditState.NOTE_LIST) {//当状态为当前笔记列表状态时,设置同步或取消同步 + getMenuInflater().inflate(R.menu.note_list, menu);//加载目录的布局 + // set sync or sync_cancel + menu.findItem(R.id.menu_sync).setTitle( + GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync);//语句:为同步菜单项设置标题,如果正在同步中则显示“取消同步”,否则显示“同步” + } else if (mState == ListEditState.SUB_FOLDER) {//当状态为当前子文件夹状态时,扩充子文件夹 + getMenuInflater().inflate(R.menu.sub_folder, menu);//语句:采用布局文件R.menu.sub_folder来构建菜单项 + } else if (mState == ListEditState.CALL_RECORD_FOLDER) {//当状态为当调用记录文件夹时,扩充记录文件夹的菜单 + getMenuInflater().inflate(R.menu.call_record_folder, menu);//语句:采用布局文件R.menu.call_record_folder来构建菜单项 + } else {//否则设置标签为“错误状态”+当前状态 + Log.e(TAG, "Wrong state:" + mState);//语句:报错日志信息 + } + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) {//当主界面中的菜单项被选中时进行的工作 (case R.id.menu_new_note)这个选项没有在菜单中显示出来 + switch (item.getItemId()) {//选择不同的项目名称 + case R.id.menu_new_folder: {//.新建文件夹 + showCreateOrModifyFolderDialog(true); + break; + } + case R.id.menu_export_text: {//输出文本 + exportNoteToText(); + break; + } + case R.id.menu_sync: {//同步菜单 + if (isSyncMode()) {//同步 + if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) {//如果项目title与菜单同步相同,则进行同步 + GTaskSyncService.startSync(this);//利用到GTaskSyncService的类 + } else {//否则取消同步 + GTaskSyncService.cancelSync(this); + } + } else {//如果不是同步模式,则开始设置动作 + startPreferenceActivity();//否则进行Preference活动 + } + break; + } + case R.id.menu_setting: {//设置菜单 + startPreferenceActivity(); + break; + } + case R.id.menu_new_note: {//新建便签 + createNewNote(); + break; + } + case R.id.menu_search://搜索 + onSearchRequested();//查询 + break; + default: + break; + } + return true; + } + + @Override + public boolean onSearchRequested() {//查找请求的响应,好像没有实现? + startSearch(null, false, null /* appData */, false); + return true; + } + + private void exportNoteToText() {//将便签导出 + final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);//备份笔记信息 + new AsyncTask() {//异步任务 + + @Override + protected Integer doInBackground(Void... unused) { + return backup.exportToText(); + }//未被占用的话后台进行 + + @Override + protected void onPostExecute(Integer result) {//设置备份的结果响应 + if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {//根据结果为sd卡未装载、成功、系统错误三种进行处理,均是设置对话框、标题、信息以及确认按钮状态 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_unmounted)); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SUCCESS) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.success_sdcard_export));//导出文本 + builder.setMessage(NotesListActivity.this.getString( + R.string.format_exported_file_location, backup + .getExportedTextFileName(), backup.getExportedTextFileDir())); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SYSTEM_ERROR) {// 如果系统错误,则显示 导出失败,请检查SD卡 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this//设置标题 + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_export)); + builder.setPositiveButton(android.R.string.ok, null);//设置响应按钮 + builder.show(); + } + } + + }.execute(); + } + + private boolean isSyncMode() {//判断同步 + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;//转到PreferenceActivity + } + + private void startPreferenceActivity() {//跳转到设置界面 + Activity from = getParent() != null ? getParent() : this;//设置便签函数 + Intent intent = new Intent(from, NotesPreferenceActivity.class); + from.startActivityIfNeeded(intent, -1);//请求码为-1,表示此活动结束后不会通知原活动 + } + + private class OnListItemClickListener implements OnItemClickListener {//当短按标签列表项时的响应 + + public void onItemClick(AdapterView parent, View view, int position, long id) {//项目被点击的响应 + if (view instanceof NotesListItem) {//判断view是否是NotesListItem的一个实例,如果是就获取他的项目信息装入item中 + NoteItemData item = ((NotesListItem) view).getItemData();//判断view是否是NotesListItem的一个实例 是就获取他的项目信息装入item中 + if (mNotesListAdapter.isInChoiceMode()) {//如果列表适配器被选择并且项是便签类型的,则修改位置和状态信息 + if (item.getType() == Notes.TYPE_NOTE) {//如果点到的item是便签 + position = position - mNotesListView.getHeaderViewsCount();//减去头部视图的元素项,得到列表的元素索引值 + mModeCallBack.onItemCheckedStateChanged(null, position, id,//改变对应索引的Item是否被选中的状态 + !mNotesListAdapter.isSelectedItem(position)); + } + return; + } + + switch (mState) {//区别情况进行处理 + case NOTE_LIST://便签列表 + if (item.getType() == Notes.TYPE_FOLDER + || item.getType() == Notes.TYPE_SYSTEM) { + openFolder(item);//查询目标文件夹 + } else if (item.getType() == Notes.TYPE_NOTE) { + openNode(item);//语句:如果点击的是便签类型,则执行打开便签 + } else { + Log.e(TAG, "Wrong note type in NOTE_LIST"); + } + break; + case SUB_FOLDER: + case CALL_RECORD_FOLDER: + if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); + } else { + Log.e(TAG, "Wrong note type in SUB_FOLDER"); + } + break; + default: + break; + } + } + } + + } + + private void startQueryDestinationFolders() {//查询目标文件 + String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; + selection = (mState == ListEditState.NOTE_LIST) ? selection: + "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; + + mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, + null, + Notes.CONTENT_NOTE_URI,//长按某一项时进行的操作 如果长按的是便签,则通过ActionMode菜单实现;如果长按的是文件夹,则通过ContextMenu菜单实现; + FoldersListAdapter.PROJECTION, + selection,//长按某一项时进行的操作 如果长按的是便签,则通过ActionMode菜单实现;如果长按的是文件夹,则通过ContextMenu菜单实现; + new String[] {//新建字符列表 + String.valueOf(Notes.TYPE_FOLDER), + String.valueOf(Notes.ID_TRASH_FOLER), + String.valueOf(mCurrentFolderId) + }, + NoteColumns.MODIFIED_DATE + " DESC"); + } + + public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {//长按的响应 + if (view instanceof NotesListItem) {//判断view是否是NotesListItem的一个实例,如果是就获取他的项目信息装入item中 + mFocusNoteDataItem = ((NotesListItem) view).getItemData();//聚焦的Item对象 + if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {//长按的对象是便签时的处理,通过ActionMode实现 + if (mNotesListView.startActionMode(mModeCallBack) != null) { + mModeCallBack.onItemCheckedStateChanged(null, position, id, true);//开始对单个便签进行操作 + mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);//语句:执行长按动作触发震动,反馈机制 + } else { + Log.e(TAG, "startActionMode fails"); + } + } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {//语句:如果长按的的项目是文件夹类型,则执行ContextMenu菜单的实现 + mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); + } + } + return false; + } +} diff --git a/doc/精读代码(注释)/闵心诚注释/ui/NotesListAdapter.java b/doc/精读代码(注释)/闵心诚注释/ui/NotesListAdapter.java new file mode 100644 index 0000000..06c0a0b --- /dev/null +++ b/doc/精读代码(注释)/闵心诚注释/ui/NotesListAdapter.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui;//引入tools包 + +import android.content.Context; +import android.database.Cursor;//光标 +import android.util.Log; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; + +import net.micode.notes.data.Notes;//类名翻译:便签连接器 可能是 实现便签的编辑 + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; + + +public class NotesListAdapter extends CursorAdapter {//继承了CursorAdapter + private static final String TAG = "NotesListAdapter";//设置标签字符常量 + private Context mContext;//便签数 + private HashMap mSelectedIndex;//HashMap是一个散列表,储存键值对的映射关系 + private int mNotesCount;//便签数 + private boolean mChoiceMode;//选择模式标志 + + public static class AppWidgetAttribute {//桌面widget的属性,包括编号和类型 + public int widgetId;//函数功能:初始化便签链接器 + public int widgetType; + }; + + public NotesListAdapter(Context context) {//初始化便签链接 + super(context, null);//功能描述:NoteListAdapter的构造函数 + 函数实现:继承父类函数;设置HashMap的map表,实现选择item与是否选择的键值对;设置context上下文;初始化note数量为0 + mSelectedIndex = new HashMap();//新建HASH表 + mContext = context;//新建一个视图来存储光标所指向的数据 + mNotesCount = 0;//初始便签数为0 + } + + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) {//利用NotesListLtem类创建新布局 + return new NotesListItem(context);//使用noteslistitem类新建一个项目选项 + } + + @Override + public void bindView(View view, Context context, Cursor cursor) {//将已经存在的视图和鼠标指向的数据进行捆绑 + if (view instanceof NotesListItem) {//view是NotesListItem的实例 + NoteItemData itemData = new NoteItemData(context, cursor);//新建一个项目选项并且用bind跟将view和鼠标,内容,便签数据捆绑在一起 + ((NotesListItem) view).bind(context, itemData, mChoiceMode,//用光标指向的内容新建项目并将数据、项目、鼠标、视图捆绑起来 + isSelectedItem(cursor.getPosition())); + } + } + + public void setCheckedItem(final int position, final boolean checked) {//设置勾选框 + mSelectedIndex.put(position, checked);//根据定位和是否勾选设置下标 + notifyDataSetChanged();//在修改后刷新activity + } + + public boolean isInChoiceMode() { + return mChoiceMode; + }//判断单选按钮是否勾选 + + public void setChoiceMode(boolean mode) {//重置下标,并根据参数mode设置选项 + mSelectedIndex.clear();//清空勾选下表并根据当前mode设置 + mChoiceMode = mode; + } + + public void selectAll(boolean checked) {//选择全部选项,遍历所有光标可用的位置在判断为便签类型之后勾选单项框 + Cursor cursor = getCursor();//获取光标位置 + for (int i = 0; i < getCount(); i++) {//遍历可用光标位置,如果光标移动且光标当前指向的便签项目类型为TYPE_NOTE则设置为勾选状态 + if (cursor.moveToPosition(i)) {//遍历所有位置并设置勾选标志 + if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {//如果是便签状态 + setCheckedItem(i, checked);//将位置i标志为已勾选加入到 mSelectedIndex中 + } + } + } + } + + public HashSet getSelectedItemIds() {//建立选择项目的ID的HASH表 + HashSet itemSet = new HashSet();//建立hash表 + for (Integer position : mSelectedIndex.keySet()) {//遍历所有的关键 + if (mSelectedIndex.get(position) == true) {//判断光标位置是否可用 + Long id = getItemId(position); + if (id == Notes.ID_ROOT_FOLDER) {//原文件不需要添加,则将id该下标假如选项集合中 + Log.d(TAG, "Wrong item id, should not happen");//原文件不需要添加 + } else {//如果不是,则加入条目集合 + itemSet.add(id);//将该id加入到选项集合当中 + } + } + } + + return itemSet;//返回条目集合 + } + + public HashSet getSelectedWidget() {//建立桌面widget选项表 + HashSet itemSet = new HashSet();//类似于getselecteditemids的实现方法 + for (Integer position : mSelectedIndex.keySet()) {//如果光标位置可用 + if (mSelectedIndex.get(position) == true) { + Cursor c = (Cursor) getItem(position);//用c记录光标位置以判断是否选择了桌面挂件(可用) + if (c != null) {//获取光标位置可用 + AppWidgetAttribute widget = new AppWidgetAttribute();//.新建widget并更新ID和类型,最后添加到选项表中 + NoteItemData item = new NoteItemData(mContext, c);//初始化所选桌面挂件信息加入到itemSet中 + widget.widgetId = item.getWidgetId(); + widget.widgetType = item.getWidgetType(); + itemSet.add(widget);//加入条目集合 + /** + * Don't close cursor here, only the adapter could close it + */ + } else {//在这里,不关闭光标,而是在adapter中才能关闭光标 + Log.e(TAG, "Invalid cursor");//设置标签,无效的cursor + return null; + } + } + } + return itemSet; + } + + public int getSelectedCount() {//获取选项个数 + Collection values = mSelectedIndex.values();//获取选项下标的值 + if (null == values) {//如果此项值为空贼返回0 + return 0; + } + Iterator iter = values.iterator();//初始化迭代器 + int count = 0; + while (iter.hasNext()) {//如果iter后面还有,则count加一 + if (true == iter.next()) {//value值为真则count加一 + count++; + } + } + return count; + } + + public boolean isAllSelected() {//判断是否全选 + int checkedCount = getSelectedCount();//通过获得计数的结果与小米便签中的数量相比较 + return (checkedCount != 0 && checkedCount == mNotesCount);//对比选项数和总数是否一致且不为0 + } + + public boolean isSelectedItem(final int position) {//判断是否为选项表 + if (null == mSelectedIndex.get(position)) {//选项下标为空则不是 + return false; + } + return mSelectedIndex.get(position);//判断Item是否被选中的状态 + } + + @Override + protected void onContentChanged() {//activity内容变动时调用calcNotesCount计算便签数量 + super.onContentChanged();//执行父类函数 + calcNotesCount(); + } + + @Override + public void changeCursor(Cursor cursor) {//activity光标变动时调用calcNotesCount计算便签数量 + super.changeCursor(cursor);//重载父类函数 + calcNotesCount();//calcNotesCount函数实现 + } + + private void calcNotesCount() {//计算便签数量 + mNotesCount = 0; + for (int i = 0; i < getCount(); i++) {//获取总数同时遍历 + Cursor c = (Cursor) getItem(i);//遍历所有选项 + if (c != null) {//判断语句,如果光标不是null,那么便得到信息,便签数目加1 + if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {//如果数据是便签类型 九江计数+1 + mNotesCount++; + } + } else {//设置为无效的光标 + Log.e(TAG, "Invalid cursor");//否则就将设置为无效的光标 + return;//否则就将设为无效光标 + } + } + } +} diff --git a/doc/精读代码(注释)/闵心诚注释/ui/NotesListItem.java b/doc/精读代码(注释)/闵心诚注释/ui/NotesListItem.java new file mode 100644 index 0000000..76c805a --- /dev/null +++ b/doc/精读代码(注释)/闵心诚注释/ui/NotesListItem.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui;//引入需要用到的包 + +import android.content.Context;//第19到30行导入各种类 +import android.text.format.DateUtils; +import android.view.View;//导入类 +import android.widget.CheckBox; +import android.widget.ImageView; +import android.widget.LinearLayout;//标签列表项目选项 +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser.NoteItemBgResources; + + +public class NotesListItem extends LinearLayout {//构建便签列表的各个项目的详细具体信息 + private ImageView mAlert;//闹钟图片 + private TextView mTitle;//标题 + private TextView mTime;//时间 + private TextView mCallName;//名字 + private NoteItemData mItemData;//标签数据 + private CheckBox mCheckBox;//勾选框 + + public NotesListItem(Context context) {//初始化 + super(context);//super()它的主要作用是调整调用父类构造函数的顺序 + inflate(context, R.layout.note_item, this);//Inflate()作用就是将xml定义的一个布局找出来 + mAlert = (ImageView) findViewById(R.id.iv_alert_icon);//语句: 获取题目(文件夹或便签项上的文本) + mTitle = (TextView) findViewById(R.id.tv_title);//语句: 获取题目(文件夹或便签项上的文本) + mTime = (TextView) findViewById(R.id.tv_time);// 语句:获取创建或修改时间 + mCallName = (TextView) findViewById(R.id.tv_name);//语句:获取联系人姓名 + mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);//语句:获取复选框 + } + + public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {//根据data的属性对各个控件的属性的控制,主要是可见性Visibility,内容setText,格式setTextAppearance + if (choiceMode && data.getType() == Notes.TYPE_NOTE) {//语句:如果当前处于选择模式下且数据类型为便签 + mCheckBox.setVisibility(View.VISIBLE);//设置View可见 + mCheckBox.setChecked(checked);//设置勾选 + } else { + mCheckBox.setVisibility(View.GONE); + } + + mItemData = data;//把数据传给标签 + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {//设置控件属性,通过判断保存到文件夹的ID、当前ID以及父ID之间关系决定 + mCallName.setVisibility(View.GONE);//设置setText 的style + mAlert.setVisibility(View.VISIBLE);//语句:设置闹钟图标可见 + mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);//设置外观风格 + mTitle.setText(context.getString(R.string.call_record_folder_name)//设置内容 + + context.getString(R.string.format_folder_files_count, data.getNotesCount())); + mAlert.setImageResource(R.drawable.call_record); + } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {//设置闹钟 + mCallName.setVisibility(View.VISIBLE);//语句: 设置联系人姓名可见 + mCallName.setText(data.getCallName());//语句:设置联系人姓名的文本内容 + mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);//语句:设置title文本风格 + mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));//语句:设置title的文本内容为便签内容的前面片段 + if (data.hasAlert()) {//语句:如果当前便签存在提醒时间 + mAlert.setImageResource(R.drawable.clock);//图片来源的设置 + mAlert.setVisibility(View.VISIBLE);//语句:将提醒图标设置为可见 + } else { + mAlert.setVisibility(View.GONE);//语句:否则将提醒图标设置为不可见 + } + } else { + mCallName.setVisibility(View.GONE);//语句:设置联系人姓名不可见 + mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);//语句:设置title的文本格式 + + if (data.getType() == Notes.TYPE_FOLDER) {//设置Type格式 + mTitle.setText(data.getSnippet()//设置便签标题内容为便签的前面部分的内容+文件数+便签数 + + context.getString(R.string.format_folder_files_count,//语句:设置文件夹的title为“名字+(count)” + data.getNotesCount()));//设置时间,从data编辑的日期获取 + mAlert.setVisibility(View.GONE);//语句:设置图标不可见 + } else {//如果不是文件夹类型 + mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));//语句:设置便签的title为便签内容的前面片段 + if (data.hasAlert()) {//语句:如果当前便签存在提醒闹钟时间 + mAlert.setImageResource(R.drawable.clock);//语句:将提醒图标设置为闹钟样式 + mAlert.setVisibility(View.VISIBLE);//语句:设置提醒闹钟可见 + } else { + mAlert.setVisibility(View.GONE);//语句:否则设置提醒图标不可见 + } + } + } + mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));//将时间设置为编辑便签的时间 + + setBackground(data); + } + + private void setBackground(NoteItemData data) {//通过data设置背景 + int id = data.getBgColorId();//语句:获取id,用此id用来获取背景颜色 + if (data.getType() == Notes.TYPE_NOTE) {//四种不同背景来源 + if (data.isSingle() || data.isOneFollowingFolder()) {//单个数据或只有一个子文件夹 + setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));//设置背景来源为id的单个数据 + } else if (data.isLast()) {//最后一个数据 + setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));//设置背景来源为id的最后一个数据 + } else if (data.isFirst() || data.isMultiFollowingFolder()) {//第一个数据或多个子文件夹 + setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); + } else { + setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));//设置背景来源为id的普通数据 + } + } else { + setBackgroundResource(NoteItemBgResources.getFolderBgRes());//设置背景来源为文件夹 + } + } + + public NoteItemData getItemData() { + return mItemData; + }//返回当前便签的数据信息 +} diff --git a/doc/精读代码(注释)/闵心诚注释/ui/NotesPreferenceActivity.java b/doc/精读代码(注释)/闵心诚注释/ui/NotesPreferenceActivity.java new file mode 100644 index 0000000..c5065ec --- /dev/null +++ b/doc/精读代码(注释)/闵心诚注释/ui/NotesPreferenceActivity.java @@ -0,0 +1,399 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui;////引入ui包 + +import android.accounts.Account;//引入ui包//该类主要实现的是对背景颜色和字体大小的数据储存, 继承了PreferenceActivity主要功能为对系统信息和配置进行自动保存的Activity +import android.accounts.AccountManager; +import android.app.ActionBar; +import android.app.AlertDialog; +import android.content.BroadcastReceiver; +import android.content.ContentValues; +import android.content.Context;//文本 +import android.content.DialogInterface;//对话 +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.Preference; +import android.preference.Preference.OnPreferenceClickListener; +import android.preference.PreferenceActivity; +import android.preference.PreferenceCategory;//继承PreferenceActivity,主要功能为对系统配置进行自动保存以及实现用户同步的操作 +import android.text.TextUtils; +import android.text.format.DateFormat; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button;//按钮 +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes;//引入R包 +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.remote.GTaskSyncService; + + +public class NotesPreferenceActivity extends PreferenceActivity {//类:NotesPreferenceActivity,在小米便签中主要实现的是对背景颜色和字体大小的数据储存。 + 继承了PreferenceActivity主要功能为对系统信息和配置进行自动保存的Activity + public static final String PREFERENCE_NAME = "notes_preferences";//NotesPreferenceActivity,在小米便签中主要实现的是对背景颜色和字体大小的数据储存。继承了PreferenceActivity主要功能为对系统信息和配置进行自动保存的Activity + + public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";//同步账户名 + + public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";//最后同步时间 + + public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";//设置颜色按键 + + private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";//账户同步密码 + + private static final String AUTHORITIES_FILTER_KEY = "authorities";//本地密码 + + private PreferenceCategory mAccountCategory; + + private GTaskReceiver mReceiver; + + private Account[] mOriAccounts; + + private boolean mHasAddedAccount; + + @Override + protected void onCreate(Bundle icicle) {//新建Activity + super.onCreate(icicle);//执行父类创建函数 + + /* using the app icon for navigation */ + getActionBar().setDisplayHomeAsUpEnabled(true);//给左上角图标的左边加上一个返回的图标 + + addPreferencesFromResource(R.xml.preferences);//给左上角图标的左边加上一个返回的图标 + mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);//添加xml来源并显示 xml + mReceiver = new GTaskReceiver();//根据同步账户关键码来初始化分组 + IntentFilter filter = new IntentFilter();//设置过滤项 + filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); + registerReceiver(mReceiver, filter); + + mOriAccounts = null; + View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); + getListView().addHeaderView(header, null, true); + } + + @Override + protected void onResume() {//函数功能:activity交互功能的实现,用于接受用户的输入 + super.onResume();//函数功能:activity交互功能的实现,用于接受用户的输入 + + // need to set sync account automatically if user has added a new + // account + if (mHasAddedAccount) {//代码块:若用户新加了账户则自动设置同步账户 + Account[] accounts = getGoogleAccounts();//获取google账户 + if (mOriAccounts != null && accounts.length > mOriAccounts.length) { + for (Account accountNew : accounts) {//遍历账户 + boolean found = false;//更新账户 + for (Account accountOld : mOriAccounts) {//循环判断当前账户列表中的账户是否与新建账户名相同 + if (TextUtils.equals(accountOld.name, accountNew.name)) {//若没找到旧账户则只设置新账户为同步账户 + found = true;// 语句:更新账户 + break; + } + } + if (!found) { + setSyncAccount(accountNew.name); + break; + } + } + } + } + + refreshUI(); + } + + @Override + protected void onDestroy() {//销毁Activity + if (mReceiver != null) {//销毁接收器 + unregisterReceiver(mReceiver);//语句:注销接收器 + } + super.onDestroy();//语句:执行销毁动作 + } + + private void loadAccountPreference() {//设置账户信息 + mAccountCategory.removeAll();//移除所有分组 + + Preference accountPref = new Preference(this);//销毁所有的分组 + final String defaultAccount = getSyncAccountName(this);//建立首选项 + accountPref.setTitle(getString(R.string.preferences_account_title));//首选项的大小标题 + accountPref.setSummary(getString(R.string.preferences_account_summary));//类似title的副标题 + accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) {//设置首选项的大标题和小标题 + if (!GTaskSyncService.isSyncing()) {//不处于同步状态 + if (TextUtils.isEmpty(defaultAccount)) { + // the first time to set account + showSelectAccountAlertDialog(); + } else {//代码块:若是账户已经存在,则显示修改对话框并进行修改操作 + // if the account has already been set, we need to promp + // user about the risk + showChangeAccountConfirmAlertDialog();//已有账户则显示确认对话框 + } + } else {//代码块:若在没有同步的情况下,则在toast中显示不能修改 + Toast.makeText(NotesPreferenceActivity.this,//若正在同步则显示不能修改账户 + R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) + .show(); + } + return true; + } + }); + + mAccountCategory.addPreference(accountPref);//语句:根据新建首选项编辑新的账户分组 + } + + private void loadSyncButton() {//设置同步按键和最近同步时间 + Button syncButton = (Button) findViewById(R.id.preference_sync_button); + TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);//获取同步按钮控件和最终同步时间的的窗口 + + // set button state + if (GTaskSyncService.isSyncing()) { + syncButton.setText(getString(R.string.preferences_button_sync_cancel)); + syncButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) {//设置点击监听器 + GTaskSyncService.cancelSync(NotesPreferenceActivity.this); + } + }); + } else {//非同步状态下按键显示“立即同步”,设置相关监听器 + syncButton.setText(getString(R.string.preferences_button_sync_immediately));//若是不同步则设置按钮显示的文本为“立即同步”以及对应监听器 + syncButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) {//若是不同步则设置按钮显示的文本为“立即同步”以及对应监听器 + GTaskSyncService.startSync(NotesPreferenceActivity.this);//点击行为 + } + }); + } + syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));//语句:若是不同步则设置按钮显示的文本为“立即同步”以及对应监听器 + 设置按键可用还是不可用 + + // set last sync time + if (GTaskSyncService.isSyncing()) {//设置按键的可用性 + lastSyncTimeView.setText(GTaskSyncService.getProgressString()); + lastSyncTimeView.setVisibility(View.VISIBLE); + } else {//根据当前同步服务器设置时间显示框的文本以及可见性 + long lastSyncTime = getLastSyncTime(this); + if (lastSyncTime != 0) {//设置一些显示的内容 + lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,//非同步时,若最近同步时间不为0则显示最近同步时间 + DateFormat.format(getString(R.string.preferences_last_sync_time_format), + lastSyncTime))); + lastSyncTimeView.setVisibility(View.VISIBLE); + } else {//根据最后同步时间的信息来编辑时间显示框的文本内容和可见性 + lastSyncTimeView.setVisibility(View.GONE);//最近同步时间为空设置同步时间不可见 + } + } + } + + private void refreshUI() {// 函数:刷新标签界面 + loadAccountPreference(); + loadSyncButton(); + } + + private void showSelectAccountAlertDialog() {//函数:显示账户选择的对话框并进行账户的设置 + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);//语句:创建一个新的对话框 + + View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); + TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); + titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); + TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);//文本试图设置 + subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); + + dialogBuilder.setCustomTitle(titleView);//代码块:设置标题以及子标题的内容 + dialogBuilder.setPositiveButton(null, null); + + Account[] accounts = getGoogleAccounts();//获得谷歌账户 + String defAccount = getSyncAccountName(this); + + mOriAccounts = accounts;//语句:获取同步账户信息 + mHasAddedAccount = false; + + if (accounts.length > 0) {//语句:若账户不为空 + CharSequence[] items = new CharSequence[accounts.length]; + final CharSequence[] itemMapping = items; + int checkedItem = -1; + int index = 0; + for (Account account : accounts) {//通过循环检查账户列表 + if (TextUtils.equals(account.name, defAccount)) { + checkedItem = index; + } + items[index++] = account.name; + } + dialogBuilder.setSingleChoiceItems(items, checkedItem,//语句:在对话框建立一个单选的复选框 + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + setSyncAccount(itemMapping[which].toString());//点击则开始设置同步账户 + dialog.dismiss();//语句:取消对话框 + refreshUI();//刷新界面 + } + }); + } + + View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);//视图,添加新的账户 + dialogBuilder.setView(addAccountView);//语句:给新加账户对话框设置自定义样式 + + final AlertDialog dialog = dialogBuilder.show();//语句:显示对话框 + addAccountView.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) {//设置监听器 + mHasAddedAccount = true;//功能描述:响应点击添加账户的请求 + 函数实现:除了调用父类的onCreate,还有一些自己的个性化配置 + 参数描述: + @v 视图,包括很多设置参数 + Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");//语句:建立网络建立组件 + intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { + "gmail-ls" + }); + startActivityForResult(intent, -1); + dialog.dismiss(); + } + }); + } + + private void showChangeAccountConfirmAlertDialog() {//刷新标签界面 + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);//语句:创建一个新的对话框 + + View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); + TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); + titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, + getSyncAccountName(this))); + TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); + subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));//语句:根据同步修改的账户信息设置标题以及子标题的内容 + dialogBuilder.setCustomTitle(titleView); + + CharSequence[] menuItemArray = new CharSequence[] {//代码块:设置对话框的自定义标题 + getString(R.string.preferences_menu_change_account), + getString(R.string.preferences_menu_remove_account), + getString(R.string.preferences_menu_cancel) + }; + dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + if (which == 0) {//语句:进入账户选择对话框 + showSelectAccountAlertDialog();//显示账户选择提示对话框 + } else if (which == 1) {//删除同步账户 + removeSyncAccount();//语句:删除账户并且跟新便签界面 + refreshUI(); + } + } + }); + dialogBuilder.show();//语句:显示对话框 + } + + private Account[] getGoogleAccounts() {//函数:获取谷歌账户,可通过账户管理器直接获取 + AccountManager accountManager = AccountManager.get(this); + return accountManager.getAccountsByType("com.google"); + } + + private void setSyncAccount(String account) {//函数:设置同步账户 + if (!getSyncAccountName(this).equals(account)) {//代码块:如果该账号不在同步账号列表中 + SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = settings.edit();//编辑共享首选项 + if (account != null) {//语句:编辑共享的首选项 + editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); + } else { + editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); + } + editor.commit(); + + // clean up last sync time + setLastSyncTime(this, 0);// 语句:将最后同步时间清零 + + // clean up local gtask related info + new Thread(new Runnable() { + public void run() {//新线程的创建 + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); + values.put(NoteColumns.SYNC_ID, 0); + getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); + } + }).start();//代码块:重置当地同步任务的信息 + + Toast.makeText(NotesPreferenceActivity.this,//设置一个toast提示信息,提示用户成功设置同步 + getString(R.string.preferences_toast_success_set_accout, account), + Toast.LENGTH_SHORT).show(); + } + } + + private void removeSyncAccount() {//函数:删除同步账户 + SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);//SharedPreferences是以键值对的形式存储数据的,其使用非常简单,能够轻松的存放数据和读取数据 + SharedPreferences.Editor editor = settings.edit();//语句:设置共享首选项 + if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {//代码块:假如当前首选项中有账户就删除 + editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); + } + if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {//代码块:删除当前首选项中有账户时间 + editor.remove(PREFERENCE_LAST_SYNC_TIME); + } + editor.commit(); + + // clean up local gtask related info + new Thread(new Runnable() { + public void run() {//新线程 + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); + values.put(NoteColumns.SYNC_ID, 0); + getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); + } + }).start(); + } + + public static String getSyncAccountName(Context context) {//函数:获取同步账户名称 + 通过共享的首选项里的信息直接获取 + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,//获取同步账户名称 + Context.MODE_PRIVATE); + return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); + } + + public static void setLastSyncTime(Context context, long time) {//设置最终同步的时间 + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); + SharedPreferences.Editor editor = settings.edit();//语句:从共享首选项中找到相关账户并获取其编辑器 + editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); + editor.commit();//语句:编辑最终同步时间并提交更新 + } + + public static long getLastSyncTime(Context context) {//函数:获取最终同步时间 + 通过共享的首选项里的信息直接获取 + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,//通过共享,获取时间 + Context.MODE_PRIVATE); + return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); + } + + private class GTaskReceiver extends BroadcastReceiver {//函数:接受同步信息 + + @Override + public void onReceive(Context context, Intent intent) //功能描述:响应接收广播的情况 + 函数实现:刷新界面,判断是否同步状态下 + 参数描述: + @intent携带了活动的数据, + @context是有关的内容 + refreshUI(); + if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {// 代码块:获取随广播而来的Intent中的同步服务的数据 + TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);//通过获取的数据在设置系统的状态 + syncStatus.setText(intent + .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); + } + + } + } + + public boolean onOptionsItemSelected(MenuItem item) {//函数:处理菜单的选项 + switch (item.getItemId()) {//代码块:根据选项的id选择,这里只有一个主页 + case android.R.id.home://返回主界面 + Intent intent = new Intent(this, NotesListActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(intent);//创建活动 + return true; + default://代码块:在主页情况下在创建连接组件intent,发出清空的信号并开始一个相应的activity + return false; + } + } +} diff --git a/src/.idea/deploymentTargetDropDown.xml b/src/.idea/deploymentTargetDropDown.xml index 42459af..a35bc82 100644 --- a/src/.idea/deploymentTargetDropDown.xml +++ b/src/.idea/deploymentTargetDropDown.xml @@ -12,6 +12,6 @@ - + \ No newline at end of file diff --git a/src/app/build.gradle b/src/app/build.gradle index 5cb5898..163b09c 100644 --- a/src/app/build.gradle +++ b/src/app/build.gradle @@ -19,3 +19,7 @@ android { } } } +dependencies { + implementation 'androidx.appcompat:appcompat:1.6.1' +// implementation 'com.android.support:appcompat-v7:28.0.0' +} \ No newline at end of file diff --git a/src/app/src/main/AndroidManifest.xml b/src/app/src/main/AndroidManifest.xml index e5c7d47..006f76f 100644 --- a/src/app/src/main/AndroidManifest.xml +++ b/src/app/src/main/AndroidManifest.xml @@ -40,9 +40,10 @@ android:configChanges="keyboardHidden|orientation|screenSize" android:label="@string/app_name" android:launchMode="singleTop" - android:theme="@style/NoteTheme" + android:theme="@style/Theme.AppCompat" android:uiOptions="splitActionBarWhenNarrow" - android:windowSoftInputMode="adjustPan" > + android:windowSoftInputMode="adjustPan" + android:exported="true" > @@ -54,7 +55,8 @@ android:name=".ui.NoteEditActivity" android:configChanges="keyboardHidden|orientation|screenSize" android:launchMode="singleTop" - android:theme="@style/NoteTheme" > + android:theme="@style/NoteTheme" + android:exported="true" > @@ -87,7 +89,8 @@ + android:label="@string/app_widget2x2" + android:exported="true" > @@ -100,7 +103,8 @@ + android:label="@string/app_widget4x4" + android:exported="true" > @@ -113,7 +117,8 @@ android:resource="@xml/widget_4x_info" /> - + @@ -135,7 +140,7 @@ android:name="net.micode.notes.ui.NotesPreferenceActivity" android:label="@string/preferences_title" android:launchMode="singleTop" - android:theme="@android:style/Theme.Holo.Light" > + android:theme="@style/Theme.AppCompat.Light" > sContactCache; + + /** + * 声明了一个静态常量TAG,用于在日志中标识该类名。 + */ private static final String TAG = "Contact"; + /** + 定义了一个SQL查询字符串,用于查询满足指定条件的联系人信息。 + */ private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + " AND " + Data.RAW_CONTACT_ID + " IN " @@ -36,6 +50,12 @@ public class Contact { + " FROM phone_lookup" + " WHERE min_match = '+')"; + /** + * 公共方法,用于获取给定电话号码所对应联系人的姓名。 + * @param context + * @param phoneNumber + * @return + */ public static String getContact(Context context, String phoneNumber) { if(sContactCache == null) { sContactCache = new HashMap(); diff --git a/src/app/src/main/java/net/micode/notes/data/Notes.java b/src/app/src/main/java/net/micode/notes/data/Notes.java index f240604..8de418f 100644 --- a/src/app/src/main/java/net/micode/notes/data/Notes.java +++ b/src/app/src/main/java/net/micode/notes/data/Notes.java @@ -18,8 +18,18 @@ package net.micode.notes.data; import android.net.Uri; public class Notes { + + /** + * 这是一个静态的字符串常量,表示内容提供者的授权标识。 + */ public static final String AUTHORITY = "micode_notes"; + + /** + * 这是一个静态的字符串常量,用于在日志中标识该类名。 + */ public static final String TAG = "Notes"; + + //这些静态的整数常量表示不同类型的便签笔记。 public static final int TYPE_NOTE = 0; public static final int TYPE_FOLDER = 1; public static final int TYPE_SYSTEM = 2; @@ -30,11 +40,13 @@ public class Notes { * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records */ + //这些静态的整数常量表示不同类型的系统文件夹的标识符 public static final int ID_ROOT_FOLDER = 0; public static final int ID_TEMPARAY_FOLDER = -1; public static final int ID_CALL_RECORD_FOLDER = -2; public static final int ID_TRASH_FOLER = -3; + //这些静态的字符串常量表示传递给Intent对象的额外数据的键名。 public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; @@ -42,10 +54,14 @@ public class Notes { public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; + //这些静态的整数常量表示小部件的类型。 public static final int TYPE_WIDGET_INVALIDE = -1; public static final int TYPE_WIDGET_2X = 0; public static final int TYPE_WIDGET_4X = 1; + /** + * 这是一个静态的内部类,定义了一些用于数据类型的常量字符串。 + */ public static class DataConstants { public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; @@ -53,14 +69,19 @@ public class Notes { /** * Uri to query all notes and folders + * 这静态的Uri常量表示查询的基础地址。 */ public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); /** * Uri to query data + * 这静态的Uri常量表示查询的基础地址。 */ public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); + /** + * 标准接口,声明了列名。 + */ public interface NoteColumns { /** * The unique ID for a row @@ -167,6 +188,9 @@ public class Notes { public static final String VERSION = "version"; } + /** + * 这些是标准接口,声明了数据类型。 + */ public interface DataColumns { /** * The unique ID for a row @@ -241,6 +265,9 @@ public class Notes { public static final String DATA5 = "data5"; } + /** + * 这个静态的内部类扩展了DataColumns接口,表示不同类型的便签笔记。包含一些额外的列。 + */ public static final class TextNote implements DataColumns { /** * Mode to indicate the text in check list mode or not @@ -257,6 +284,9 @@ public class Notes { public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); } + /** + * 这个静态的内部类扩展了DataColumns接口,表示不同类型的便签笔记。包含一些额外的数据类型。 + */ public static final class CallNote implements DataColumns { /** * Call date for this record diff --git a/src/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java b/src/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java index ffe5d57..d6dec55 100644 --- a/src/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java +++ b/src/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java @@ -26,12 +26,17 @@ import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.NoteColumns; - +/** + * 用于打开、创建和管理Note应用程序的数据库 + */ public class NotesDatabaseHelper extends SQLiteOpenHelper { private static final String DB_NAME = "note.db"; private static final int DB_VERSION = 4; + /** + * 这是一个接口,内部定义了一个笔记表和一个数据表的表名常量。 + */ public interface TABLE { public static final String NOTE = "note"; @@ -42,6 +47,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { private static NotesDatabaseHelper mInstance; + /** + * 该字符串表示用于创建“note”表的SQL语句。该表用于存储笔记的基本信息。 + */ private static final String CREATE_NOTE_TABLE_SQL = "CREATE TABLE " + TABLE.NOTE + "(" + NoteColumns.ID + " INTEGER PRIMARY KEY," + @@ -63,6 +71,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + ")"; + /** + * SQL语句用于创建“data”表的字符串常量 + */ private static final String CREATE_DATA_TABLE_SQL = "CREATE TABLE " + TABLE.DATA + "(" + DataColumns.ID + " INTEGER PRIMARY KEY," + @@ -78,12 +89,16 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + ")"; + /** + * SQL语句在"data"表上创建索引的字符串常量 + */ private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = "CREATE INDEX IF NOT EXISTS note_id_index ON " + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; /** * Increase folder's note count when move note to the folder + * 在将笔记移动到文件夹时增加文件夹的笔记计数 */ private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = "CREATE TRIGGER increase_folder_count_on_update "+ @@ -96,6 +111,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { /** * Decrease folder's note count when move note from folder + * 在将笔记移出文件夹时减少文件夹的笔记计数 */ private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = "CREATE TRIGGER decrease_folder_count_on_update " + @@ -109,6 +125,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { /** * Increase folder's note count when insert new note to the folder + * 此触发器将在向数据库中添加新的笔记时自动触发。当向某个文件夹添加新的笔记时,此触发器将使该文件夹的“notes_count”值增加 1。 */ private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = "CREATE TRIGGER increase_folder_count_on_insert " + @@ -121,6 +138,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { /** * Decrease folder's note count when delete note from the folder + * 此触发器将在从数据库中删除笔记时自动触发。当从某个文件夹删除笔记时,此触发器将使该文件夹的“notes_count”值减少 1。 */ private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = "CREATE TRIGGER decrease_folder_count_on_delete " + @@ -134,6 +152,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { /** * Update note's content when insert data with type {@link DataConstants#NOTE} + * 此触发器将在向数据库中添加一个数据记录时自动触发。 + * 当添加类型为“note”的数据记录时,此触发器将更新笔记的“snippet”列,将其设置为新增数据记录的“content”列值。 */ private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = "CREATE TRIGGER update_note_content_on_insert " + @@ -147,6 +167,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { /** * Update note's content when data with {@link DataConstants#NOTE} type has changed + * 此触发器将在数据库中的数据记录被更新时自动触发。 + * 当更新的数据记录类型为“note”时,此触发器将更新笔记的“snippet”列,将其设置为更新后的数据记录的“content”列的值。 */ private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = "CREATE TRIGGER update_note_content_on_update " + @@ -160,6 +182,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { /** * Update note's content when data with {@link DataConstants#NOTE} type has deleted + * 此触发器将在从数据库中删除一个数据记录时自动触发。 + * 当被删除的数据记录类型为“note”时,此触发器将更新笔记的“snippet”列,并将其设置为空字符串。 */ private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = "CREATE TRIGGER update_note_content_on_delete " + @@ -173,6 +197,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { /** * Delete datas belong to note which has been deleted + * 此触发器将在从数据库中删除笔记时自动触发。它将删除与被删除笔记相关联的所有数据记录。 */ private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = "CREATE TRIGGER delete_data_on_delete " + @@ -184,6 +209,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { /** * Delete notes belong to folder which has been deleted + * 此触发器将在从数据库中删除文件夹时自动触发,它将删除该文件夹下的所有笔记。 */ private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = "CREATE TRIGGER folder_delete_notes_on_delete " + @@ -195,6 +221,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { /** * Move notes belong to folder which has been moved to trash folder + * 此触发器将在将某个文件夹移动到回收站时自动触发,它会将该文件夹下的所有笔记也移动到回收站。 */ private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = "CREATE TRIGGER folder_move_notes_on_trash " + @@ -206,10 +233,20 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " END"; + /** + * 这是 NotesDatabaseHelper 类的构造函数,用于创建数据库,并将数据库名称、版本等参数传递给基类 SQLiteOpenHelper 的构造函数。 + * @param context + */ public NotesDatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } + /** + * 此方法用于在给定的 SQLiteDatabase 对象上创建“note”表。 + * 它执行 CREATE_NOTE_TABLE_SQL 常量中指定的 SQL 语句, + * 并调用 reCreateNoteTableTriggers 和 createSystemFolder 方法以重置触发器并创建系统文件夹。 + * @param db + */ public void createNoteTable(SQLiteDatabase db) { db.execSQL(CREATE_NOTE_TABLE_SQL); reCreateNoteTableTriggers(db); @@ -217,6 +254,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { Log.d(TAG, "note table has been created"); } + /** + * 此私有方法用于重置所有触发器,即在调用此方法之前删除所有现有的触发器,然后重新创建所有触发器。 + * @param db + */ private void reCreateNoteTableTriggers(SQLiteDatabase db) { db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); @@ -235,6 +276,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); } + /** + * 此私有方法用于向数据库中插入四个系统文件夹。 + * 它通过为每个文件夹创建一个 ContentValues 对象来添加数据,并将其插入名为 "note" 的数据库表中。 + * 其中,每个文件夹具有唯一的 ID,类型为 TYPE_SYSTEM。 + * @param db + */ private void createSystemFolder(SQLiteDatabase db) { ContentValues values = new ContentValues(); @@ -270,6 +317,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { db.insert(TABLE.NOTE, null, values); } + /** + * 此方法用于创建数据表。 + * 它执行 CREATE_DATA_TABLE_SQL 常量中指定的 SQL 语句,并调用 reCreateDataTableTriggers 方法以重置触发器。 + * 最后,它还创建了 CREATE_DATA_NOTE_ID_INDEX_SQL 常量中指定的 ID 索引。 + * @param db + */ public void createDataTable(SQLiteDatabase db) { db.execSQL(CREATE_DATA_TABLE_SQL); reCreateDataTableTriggers(db); @@ -277,6 +330,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { Log.d(TAG, "data table has been created"); } + /** + * 用于重置增删改触发器,删除所有现有的触发器,然后重新创建触发器。 + * @param db + */ private void reCreateDataTableTriggers(SQLiteDatabase db) { db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); @@ -287,6 +344,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); } + /** + * 此方法是 NotesDatabaseHelper 类的静态方法,通过传递上下文对象来获取数据库的实例。 + * 它将确保在多线程环境中只有一个实例创建。 + * @param context + * @return + */ static synchronized NotesDatabaseHelper getInstance(Context context) { if (mInstance == null) { mInstance = new NotesDatabaseHelper(context); @@ -294,12 +357,25 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { return mInstance; } + /** + * 数据库被第一次创建时,此方法将调用。 + * createNoteTable() 和 createDataTable() 两个方法将被调用,用于创建表和触发器。 + * @param db + */ @Override public void onCreate(SQLiteDatabase db) { createNoteTable(db); createDataTable(db); } + /** + * 当数据库需要更新到一个新版本时,此方法将被调用。 + * 它通过指定旧版本和新版本号来确定进行哪些更新, + * 每个更新都会调用 upgradeToV2()、upgradeToV3() 和 upgradeToV4() 方法之一,以升级数据库结构。 + * @param db + * @param oldVersion + * @param newVersion + */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { boolean reCreateTriggers = false; @@ -333,6 +409,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { } } + /** + * 此方法执行从 v1 升级到 v2 的数据迁移。它首先删除原来的表,然后创建新表,重新建立触发器。 + * @param db + */ private void upgradeToV2(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); @@ -340,6 +420,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { createDataTable(db); } + /** + * 此方法执行从 v2 升级到 v3 的数据迁移。 + * 它删除不再需要的触发器并添加新的 note Gtask Id 列,以便允许在 Google Tasks 中同步任务到笔记应用程序中。 + * @param db + */ private void upgradeToV3(SQLiteDatabase db) { // drop unused triggers db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); @@ -355,6 +440,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { db.insert(TABLE.NOTE, null, values); } + /** + * 此方法执行从 v3 升级到 v4 的数据迁移。它为 notes 表添加了版本号列,以便在后续升级中进行版本验证。 + * @param db + */ private void upgradeToV4(SQLiteDatabase db) { db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0"); diff --git a/src/app/src/main/java/net/micode/notes/data/NotesProvider.java b/src/app/src/main/java/net/micode/notes/data/NotesProvider.java index edb0a60..f8684ac 100644 --- a/src/app/src/main/java/net/micode/notes/data/NotesProvider.java +++ b/src/app/src/main/java/net/micode/notes/data/NotesProvider.java @@ -34,14 +34,28 @@ import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.NotesDatabaseHelper.TABLE; - +/** + * 这个类中的方法可以处理来自应用程序的查询、插入、更新和删除等操作,并通过 UriMatcher 帮助确定请求的类型和内容。 + * 同时,它还定义了搜索查询结果的格式,并实现了一些自定义的功能,例如笔记的回收站文件夹。 + */ public class NotesProvider extends ContentProvider { + + /** + * UriMatcher 用于匹配可能的 URI 请求,并将其映射到适当的代码路径。它被声明为静态常量,并在静态块中进行初始化。 + */ private static final UriMatcher mMatcher; + /** + * NotesDatabaseHelper 对象用于打开和操作笔记数据库。 + */ private NotesDatabaseHelper mHelper; + /** + * 日志标签,用于调试目的。 + */ private static final String TAG = "NotesProvider"; + //这几个静态常量是 URIs 返回时的返回值,它们分别对应笔记、单个笔记、数据和单个数据。这些常量被添加到 UriMatcher 中。 private static final int URI_NOTE = 1; private static final int URI_NOTE_ITEM = 2; private static final int URI_DATA = 3; @@ -51,6 +65,10 @@ public class NotesProvider extends ContentProvider { private static final int URI_SEARCH_SUGGEST = 6; static { + /* + 这些语句将具有特定 URI 模式的请求添加到 UriMatcher 中, + 例如 "content://com.example.notes/note",并与与之关联的 UriMatcher 返回值进行映射。 + */ mMatcher = new UriMatcher(UriMatcher.NO_MATCH); mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); @@ -64,6 +82,8 @@ public class NotesProvider extends ContentProvider { /** * x'0A' represents the '\n' character in sqlite. For title and content in the search result, * we will trim '\n' and white space in order to show more information. + * 用于定义搜索结果的内容,以及笔记的搜索查询SQL。 + * 它们用于返回包含搜索查询结果的 Cursor 对象,并传递给 CursorAdapter 来填充 ListView 或 RecyclerView。 */ private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," @@ -73,18 +93,35 @@ public class NotesProvider extends ContentProvider { + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + /** + * 用于定义搜索结果的内容,以及笔记的搜索查询SQL。 + * 它们用于返回包含搜索查询结果的 Cursor 对象,并传递给 CursorAdapter 来填充 ListView 或 RecyclerView。 + */ private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION + " FROM " + TABLE.NOTE + " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + /** + * 在 ContentProvider 被创建之后,此方法将被调用,并且在这个例子中,它会初始化 mHelper 变量和返回 true。 + * @return + */ @Override public boolean onCreate() { mHelper = NotesDatabaseHelper.getInstance(getContext()); return true; } + /** + * 这个方法使用传递过来的参数来执行 SQL 查询,并返回一个 Cursor 对象,用于与 Activity 或 Fragment 中的 UI 控件进行交互。 + * @param uri + * @param projection + * @param selection + * @param selectionArgs + * @param sortOrder + * @return + */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { @@ -147,6 +184,12 @@ public class NotesProvider extends ContentProvider { return c; } + /** + * 向 ContentProvider 中插入数据。 + * @param uri + * @param values + * @return + */ @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = mHelper.getWritableDatabase(); @@ -181,6 +224,13 @@ public class NotesProvider extends ContentProvider { return ContentUris.withAppendedId(uri, insertedId); } + /** + * 从 ContentProvider 中删除数据。 + * @param uri + * @param selection + * @param selectionArgs + * @return + */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0; @@ -227,6 +277,14 @@ public class NotesProvider extends ContentProvider { return count; } + /** + * 从 ContentProvider 中更新数据。 + * @param uri + * @param values + * @param selection + * @param selectionArgs + * @return + */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = 0; @@ -267,10 +325,21 @@ public class NotesProvider extends ContentProvider { return count; } + /** + * 将查询字符串转换为 SQL 语句。如果查询字符串为空,则直接返回空字符串。 + * @param selection + * @return + */ private String parseSelection(String selection) { return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); } + /** + * 将笔记的版本号加一。如果 ID 大于 0 或查询字符串不为空,则将更新语句添加到 SQL 语句中。 + * @param id + * @param selection + * @param selectionArgs + */ private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { StringBuilder sql = new StringBuilder(120); sql.append("UPDATE "); diff --git a/src/app/src/main/java/net/micode/notes/gtask/data/MetaData.java b/src/app/src/main/java/net/micode/notes/gtask/data/MetaData.java index 3a2050b..40cf17d 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/data/MetaData.java +++ b/src/app/src/main/java/net/micode/notes/gtask/data/MetaData.java @@ -24,12 +24,19 @@ import net.micode.notes.tool.GTaskStringUtils; import org.json.JSONException; import org.json.JSONObject; - +/** + *Task类的拓展 + */ public class MetaData extends Task { private final static String TAG = MetaData.class.getSimpleName(); private String mRelatedGid = null; + /** + * 设置一些元数据 + * @param gid + * @param metaInfo + */ public void setMeta(String gid, JSONObject metaInfo) { try { metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); @@ -40,15 +47,29 @@ public class MetaData extends Task { setName(GTaskStringUtils.META_NOTE_NAME); } + /** + *返回私有变量"mRelatedGid"的值。 + * @return mRelatedGid + */ public String getRelatedGid() { return mRelatedGid; } + /** + * 一个被覆盖的方法 + * 如果当前实例的内容不为null,则返回true + * @return bool + */ @Override public boolean isWorthSaving() { return getNotes() != null; } + /** + * 一个被覆盖的方法 + * 根据给定的JSONObject "js"设置当前实例的内容。如果当前实例的内容不为null,则从注释中提取相关的gid并将其设置为私有变量"mRelatedGid" + * @param js + */ @Override public void setContentByRemoteJSON(JSONObject js) { super.setContentByRemoteJSON(js); @@ -63,17 +84,32 @@ public class MetaData extends Task { } } + /** + * 一个被覆盖的方法; + * 抛出"IllegalAccessError",因为不应该调用它 + * @param js + */ @Override public void setContentByLocalJSON(JSONObject js) { // this function should not be called throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); } + /** + * 一个被覆盖的方法; + * 抛出"IllegalAccessError",因为不应该调用它 + * @return + */ @Override public JSONObject getLocalJSONFromContent() { throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); } + /** + * 一个被覆盖的方法; + * 抛出"IllegalAccessError",因为不应该调用它 + * @return + */ @Override public int getSyncAction(Cursor c) { throw new IllegalAccessError("MetaData:getSyncAction should not be called"); diff --git a/src/app/src/main/java/net/micode/notes/gtask/data/Node.java b/src/app/src/main/java/net/micode/notes/gtask/data/Node.java index 63950e0..a3311d9 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/data/Node.java +++ b/src/app/src/main/java/net/micode/notes/gtask/data/Node.java @@ -20,6 +20,9 @@ import android.database.Cursor; import org.json.JSONObject; +/** + * 一个Node抽象类 + */ public abstract class Node { public static final int SYNC_ACTION_NONE = 0; @@ -47,6 +50,9 @@ public abstract class Node { private boolean mDeleted; + /** + * 构造函数,初始化成员变量 + */ public Node() { mGid = null; mName = ""; @@ -54,6 +60,7 @@ public abstract class Node { mDeleted = false; } + //五个抽象方法,需要实现 public abstract JSONObject getCreateAction(int actionId); public abstract JSONObject getUpdateAction(int actionId); @@ -64,8 +71,14 @@ public abstract class Node { public abstract JSONObject getLocalJSONFromContent(); + /** + * 一个名为"getSyncAction"的抽象方法,接受一个游标参数,返回一个整数值,表示同步操作类型 + * @param c + * @return + */ public abstract int getSyncAction(Cursor c); + //setter和getter方法,分别用于设置或获取节点的各个属性 public void setGid(String gid) { this.mGid = gid; } diff --git a/src/app/src/main/java/net/micode/notes/gtask/data/SqlData.java b/src/app/src/main/java/net/micode/notes/gtask/data/SqlData.java index d3ec3be..9861fb3 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/data/SqlData.java +++ b/src/app/src/main/java/net/micode/notes/gtask/data/SqlData.java @@ -34,7 +34,9 @@ import net.micode.notes.gtask.exception.ActionFailureException; import org.json.JSONException; import org.json.JSONObject; - +/** + * 定义了同步操作的基本常量 + */ public class SqlData { private static final String TAG = SqlData.class.getSimpleName(); @@ -71,6 +73,10 @@ public class SqlData { private ContentValues mDiffDataValues; + /** + * 创建一个新的SqlData对象,并初始化成员变量。 + * @param context + */ public SqlData(Context context) { mContentResolver = context.getContentResolver(); mIsCreate = true; @@ -82,6 +88,11 @@ public class SqlData { mDiffDataValues = new ContentValues(); } + /** + * 创建一个新的SqlData对象,并使用Cursor中的数据来初始化成员变量 + * @param context + * @param c + */ public SqlData(Context context, Cursor c) { mContentResolver = context.getContentResolver(); mIsCreate = false; @@ -89,6 +100,10 @@ public class SqlData { mDiffDataValues = new ContentValues(); } + /** + * 从游标中加载数据,并将其存储在成员变量中 + * @param c + */ private void loadFromCursor(Cursor c) { mDataId = c.getLong(DATA_ID_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); @@ -97,6 +112,13 @@ public class SqlData { mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); } + /** + * 用于设置数据的内容,并将其存储在mDiffDataValues变量中以便稍后提交更改。 + * 该方法接受JSONObject类型的参数,该参数包含要设置的内容。 + * 如果数据还未创建且尝试访问它,则会记录错误并返回null。 + * @param js + * @throws JSONException + */ public void setContent(JSONObject js) throws JSONException { long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; if (mIsCreate || mDataId != dataId) { @@ -130,6 +152,12 @@ public class SqlData { mDataContentData3 = dataContentData3; } + /** + * 用于获取数据的内容,并将其作为一个JSONObject对象返回。 + * 如果数据尚未创建,则会记录错误并返回null。 + * @return + * @throws JSONException + */ public JSONObject getContent() throws JSONException { if (mIsCreate) { Log.e(TAG, "it seems that we haven't created this in database yet"); @@ -144,6 +172,14 @@ public class SqlData { return js; } + /** + * 用于将数据提交到ContentProvider中。 + * 如果数据还未创建,则会插入新记录并更新mDataId变量的值。 + * 否则,它将更新现有记录的内容。如果要验证版本,则使用noteId和version参数。 + * @param noteId + * @param validateVersion + * @param version + */ public void commit(long noteId, boolean validateVersion, long version) { if (mIsCreate) { @@ -183,6 +219,10 @@ public class SqlData { mIsCreate = false; } + /** + * 返回数据ID的值,即mDataId的值 + * @return mDataId + */ public long getId() { return mDataId; } diff --git a/src/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java b/src/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java index 79a4095..8c14b81 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java +++ b/src/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java @@ -38,6 +38,9 @@ import org.json.JSONObject; import java.util.ArrayList; +/** + * 数据库中便签数据以及相关方法 + */ public class SqlNote { private static final String TAG = SqlNote.class.getSimpleName(); @@ -52,6 +55,7 @@ public class SqlNote { NoteColumns.VERSION }; + //一些成员变量 public static final int ID_COLUMN = 0; public static final int ALERTED_DATE_COLUMN = 1; @@ -122,6 +126,11 @@ public class SqlNote { private ArrayList mDataList; + /** + * 构造函数 + * 需要传入一个 Context 对象作为参数,并在该构造函数中初始化了 SqlNote 中的一些属性 + * @param context + */ public SqlNote(Context context) { mContext = context; mContentResolver = context.getContentResolver(); @@ -143,6 +152,12 @@ public class SqlNote { mDataList = new ArrayList(); } + /** + * 构造函数 + * 需要传入一个 Context 对象作为参数,以及一个 Cursor 对象 + * @param context + * @param c + */ public SqlNote(Context context, Cursor c) { mContext = context; mContentResolver = context.getContentResolver(); @@ -154,6 +169,12 @@ public class SqlNote { mDiffNoteValues = new ContentValues(); } + /** + * 构造函数 + * 只需要传入一个 Context 对象和 Long 类型的 id 即可创建一个已有的 SqlNote 对象 + * @param context + * @param id + */ public SqlNote(Context context, long id) { mContext = context; mContentResolver = context.getContentResolver(); @@ -166,6 +187,11 @@ public class SqlNote { } + /** + * 利用该参数查询对应 id 的 SqlNote,返回一个 Cursor 对象。 + * 如果查询到了数据,就调用loadFromCursor方法 + * @param id long + */ private void loadFromCursor(long id) { Cursor c = null; try { @@ -185,6 +211,10 @@ public class SqlNote { } } + /** + * 从 Cursor 中读取数据,将这些数据设置为 SqlNote 对象的相应属性值 + * @param c cursor + */ private void loadFromCursor(Cursor c) { mId = c.getLong(ID_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN); @@ -200,6 +230,9 @@ public class SqlNote { mVersion = c.getLong(VERSION_COLUMN); } + /** + * 来加载 SqlNote 对象的内容数据的 + */ private void loadDataContent() { Cursor c = null; mDataList.clear(); @@ -226,6 +259,11 @@ public class SqlNote { } } + /** + * 根据传入的 JSON 对象设置便签的内容 + * @param js JSONObject + * @return + */ public boolean setContent(JSONObject js) { try { JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); @@ -359,6 +397,10 @@ public class SqlNote { return true; } + /** + * 返回一个 类型的数据,用于保存笔记对象的信息 + * @return JSONObject + */ public JSONObject getContent() { try { JSONObject js = new JSONObject(); @@ -407,6 +449,7 @@ public class SqlNote { return null; } + //一些设置笔记属性的方法 public void setParentId(long id) { mParentId = id; mDiffNoteValues.put(NoteColumns.PARENT_ID, id); @@ -424,6 +467,7 @@ public class SqlNote { mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); } + //一些获取笔记属性的方法 public long getId() { return mId; } @@ -440,6 +484,10 @@ public class SqlNote { return mType == Notes.TYPE_NOTE; } + /** + * 将当前未保存的修改提交到数据库中 + * @param validateVersion + */ public void commit(boolean validateVersion) { if (mIsCreate) { if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { diff --git a/src/app/src/main/java/net/micode/notes/gtask/data/Task.java b/src/app/src/main/java/net/micode/notes/gtask/data/Task.java index 6a19454..c4daca3 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/data/Task.java +++ b/src/app/src/main/java/net/micode/notes/gtask/data/Task.java @@ -45,6 +45,9 @@ public class Task extends Node { private TaskList mParent; + /** + * 构造函数 + */ public Task() { super(); mCompleted = false; @@ -54,6 +57,11 @@ public class Task extends Node { mMetaInfo = null; } + /** + * 返回一个 JSONObject 类型的数据,用于表示创建任务的操作 + * @param actionId int + * @return JSONObject + */ public JSONObject getCreateAction(int actionId) { JSONObject js = new JSONObject(); @@ -103,6 +111,10 @@ public class Task extends Node { return js; } + /** + * 回一个 JSONObject 类型的数据,用于表示更新任务的操作 + * @return + */ public JSONObject getUpdateAction(int actionId) { JSONObject js = new JSONObject(); @@ -135,6 +147,10 @@ public class Task extends Node { return js; } + /** + * 用于根据从远程获取的 JSON 对象设置任务的内容 + * @param js + */ public void setContentByRemoteJSON(JSONObject js) { if (js != null) { try { @@ -175,6 +191,10 @@ public class Task extends Node { } } + /** + * 用于根据从本地获取的 JSON 对象设置任务的内容 + * @param js + */ public void setContentByLocalJSON(JSONObject js) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) || !js.has(GTaskStringUtils.META_HEAD_DATA)) { @@ -204,6 +224,10 @@ public class Task extends Node { } } + /** + * 用于将当前 Task 对象的内容转化为本地 JSON 数据格式 + * @return + */ public JSONObject getLocalJSONFromContent() { String name = getName(); try { @@ -247,6 +271,10 @@ public class Task extends Node { } } + /** + *用于根据从 MetaData 对象中获取的笔记数据设置 Task 的元数据信息 + * @param metaData + */ public void setMetaInfo(MetaData metaData) { if (metaData != null && metaData.getNotes() != null) { try { @@ -258,6 +286,11 @@ public class Task extends Node { } } + /** + * 用于根据传入的 Cursor 对象和当前 Task 对象的状态判断应该进行的同步操作 + * @param c + * @return + */ public int getSyncAction(Cursor c) { try { JSONObject noteInfo = null; @@ -311,11 +344,13 @@ public class Task extends Node { return SYNC_ACTION_ERROR; } + //方法用于判断当前 Task 对象是否值得被保存 public boolean isWorthSaving() { return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) || (getNotes() != null && getNotes().trim().length() > 0); } + //用于设置 Task 对象的完成状态、笔记信息、前一兄弟 Task 对象和父 TaskList 对象,这些方法将传入的参数设置到对应属性中。 public void setCompleted(boolean completed) { this.mCompleted = completed; } @@ -332,6 +367,7 @@ public class Task extends Node { this.mParent = parent; } + //别用于获取 Task 对象的完成状态、笔记信息、前一兄弟 Task 对象和父 TaskList 对象,这些方法将返回对应属性的值。 public boolean getCompleted() { return this.mCompleted; } diff --git a/src/app/src/main/java/net/micode/notes/gtask/data/TaskList.java b/src/app/src/main/java/net/micode/notes/gtask/data/TaskList.java index 4ea21c5..82bd868 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/data/TaskList.java +++ b/src/app/src/main/java/net/micode/notes/gtask/data/TaskList.java @@ -43,6 +43,11 @@ public class TaskList extends Node { mIndex = 1; } + /** + * 用于生成一个 JSONObject 对象,该对象表示一个用于创建当前 TaskList 对象的 Action + * @param actionId + * @return + */ public JSONObject getCreateAction(int actionId) { JSONObject js = new JSONObject(); @@ -74,6 +79,11 @@ public class TaskList extends Node { return js; } + /** + * 用于生成一个 JSONObject 对象,该对象表示一个用于更新当前 TaskList 对象的 Action + * @param actionId + * @return + */ public JSONObject getUpdateAction(int actionId) { JSONObject js = new JSONObject(); @@ -103,6 +113,10 @@ public class TaskList extends Node { return js; } + /** + * 将从网络返回的JSONObject对象解析出任务列表的ID、最后修改时间和名称,并根据解析结果设置相应属性的值 + * @param js + */ public void setContentByRemoteJSON(JSONObject js) { if (js != null) { try { @@ -129,6 +143,10 @@ public class TaskList extends Node { } } + /** + * 将从本地存储的JSONObject对象解析出便签的类型和名称,并根据解析结果设置相应任务列表的名称 + * @param js + */ public void setContentByLocalJSON(JSONObject js) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); @@ -157,6 +175,10 @@ public class TaskList extends Node { } } + /** + * 将任务列表的名称转换为本地存储JSONObject对象并返回。如果转换过程中出现异常,将返回null。 + * @return + */ public JSONObject getLocalJSONFromContent() { try { JSONObject js = new JSONObject(); @@ -183,6 +205,15 @@ public class TaskList extends Node { } } + /** + * 根据传入的游标Cursor c判断需要同步的操作: + * 如果本地和远程都没有进行更新,则返回“无需同步”状态; + * 如果只有远程数据更新了,则返回“将远程更新应用到本地”状态; + * 如果既有本地数据更新又有远程数据更新,则返回“将本地更新应用到远程”状态; + * 如果出现错误,则返回“同步错误”状态。 + * @param c + * @return + */ public int getSyncAction(Cursor c) { try { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { @@ -216,10 +247,19 @@ public class TaskList extends Node { return SYNC_ACTION_ERROR; } + /** + * 返回当前任务列表下子任务的数量 + * @return + */ public int getChildTaskCount() { return mChildren.size(); } + /** + * 向当前任务列表中添加一个子任务,如果添加成功则返回true。 + * @param task + * @return + */ public boolean addChildTask(Task task) { boolean ret = false; if (task != null && !mChildren.contains(task)) { @@ -234,6 +274,12 @@ public class TaskList extends Node { return ret; } + /** + * 向当前任务列表中特定位置添加一个子任务。如果添加成功,则返回true。如果指定的索引不合法,则返回false。 + * @param task + * @param index + * @return + */ public boolean addChildTask(Task task, int index) { if (index < 0 || index > mChildren.size()) { Log.e(TAG, "add child task: invalid index"); @@ -260,6 +306,11 @@ public class TaskList extends Node { return true; } + /** + * 从当前任务列表中删除一个子任务,并将该子任务的前一个同级任务的后继任务设置为该子任务的后继任务。如果删除成功则返回true,否则返回false。 + * @param task + * @return + */ public boolean removeChildTask(Task task) { boolean ret = false; int index = mChildren.indexOf(task); @@ -281,6 +332,12 @@ public class TaskList extends Node { return ret; } + /** + * 将指定的子任务移至当前任务列表中特定位置。如果移动成功,则返回true,否则返回false。 + * @param task + * @param index + * @return + */ public boolean moveChildTask(Task task, int index) { if (index < 0 || index >= mChildren.size()) { @@ -299,6 +356,11 @@ public class TaskList extends Node { return (removeChildTask(task) && addChildTask(task, index)); } + /** + * 查找并返回与指定任务ID相同的子任务。如果找到则返回该子任务,否则返回null。 + * @param gid + * @return + */ public Task findChildTaskByGid(String gid) { for (int i = 0; i < mChildren.size(); i++) { Task t = mChildren.get(i); @@ -309,10 +371,20 @@ public class TaskList extends Node { return null; } + /** + * 返回当前任务列表中指定子任务的索引。 + * @param task + * @return + */ public int getChildTaskIndex(Task task) { return mChildren.indexOf(task); } + /** + * 返回当前任务列表中指定索引下标的子任务对象。 + * @param index + * @return + */ public Task getChildTaskByIndex(int index) { if (index < 0 || index >= mChildren.size()) { Log.e(TAG, "getTaskByIndex: invalid index"); @@ -321,6 +393,11 @@ public class TaskList extends Node { return mChildren.get(index); } + /** + * 根据指定任务ID查找并返回与之匹配的子任务。 + * @param gid + * @return + */ public Task getChilTaskByGid(String gid) { for (Task task : mChildren) { if (task.getGid().equals(gid)) @@ -329,14 +406,26 @@ public class TaskList extends Node { return null; } + /** + * 返回当前任务列表中包含的所有子任务。 + * @return + */ public ArrayList getChildTaskList() { return this.mChildren; } + /** + * 将当前任务列表的索引设置为指定值。 + * @param index + */ public void setIndex(int index) { this.mIndex = index; } + /** + * 返回当前任务列表的索引值。 + * @return + */ public int getIndex() { return this.mIndex; } diff --git a/src/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java b/src/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java index 15504be..56ed92b 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java +++ b/src/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java @@ -16,17 +16,32 @@ package net.micode.notes.gtask.exception; +/** + * 一个继承了RuntimeException的自定义异常类,用于表示执行某个操作时出现了失败或错误。 + */ public class ActionFailureException extends RuntimeException { private static final long serialVersionUID = 4425249765923293627L; + /** + * 默认构造函数,直接调用父类的默认构造函数。 + */ public ActionFailureException() { super(); } + /** + * 带有一个字符串参数的构造函数,用于设置异常的详细信息。 + * @param paramString + */ public ActionFailureException(String paramString) { super(paramString); } + /** + * 带有两个参数的构造函数,用于同时设置异常的详细信息和原因(即异常链)。 + * @param paramString + * @param paramThrowable + */ public ActionFailureException(String paramString, Throwable paramThrowable) { super(paramString, paramThrowable); } diff --git a/src/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java b/src/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java index b08cfb1..b72a4b9 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java +++ b/src/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java @@ -16,17 +16,32 @@ package net.micode.notes.gtask.exception; +/** + * 一个继承了Exception的自定义异常类,用于表示在进行网络请求时出现了失败或错误。 + */ public class NetworkFailureException extends Exception { private static final long serialVersionUID = 2107610287180234136L; + /** + * 默认构造函数,直接调用父类的默认构造函数。 + */ public NetworkFailureException() { super(); } + /** + * 带有一个字符串参数的构造函数,用于设置异常的详细信息。 + * @param paramString + */ public NetworkFailureException(String paramString) { super(paramString); } + /** + * 带有两个参数的构造函数,用于同时设置异常的详细信息和原因(即异常链)。 + * @param paramString + * @param paramThrowable + */ public NetworkFailureException(String paramString, Throwable paramThrowable) { super(paramString, paramThrowable); } diff --git a/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java index afc2fe1..05a22c6 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java +++ b/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java @@ -28,15 +28,21 @@ import net.micode.notes.R; import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesPreferenceActivity; - +/** + * 一个继承了AsyncTask的异步任务类,用于在后台执行与谷歌任务同步相关的操作,并向用户展示同步进度通知。 + */ public class GTaskASyncTask extends AsyncTask { private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; + /** + * 一个接口,用于在异步任务完成时回调。 + */ public interface OnCompleteListener { void onComplete(); } + private Context mContext; private NotificationManager mNotifiManager; @@ -53,16 +59,28 @@ public class GTaskASyncTask extends AsyncTask { mTaskManager = GTaskManager.getInstance(); } + /** + * 取消同步操作的方法 + */ public void cancelSync() { mTaskManager.cancelSync(); } + /** + * 将同步进度信息发布到主线程中更新进度通知。 + * @param message + */ public void publishProgess(String message) { publishProgress(new String[] { message }); } + /** + * 根据传入的提示符ID和内容创建并展示通知。 + * @param tickerId + * @param content + */ private void showNotification(int tickerId, String content) { PendingIntent pendingIntent; if (tickerId != R.string.ticker_success) { @@ -86,6 +104,11 @@ public class GTaskASyncTask extends AsyncTask { mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); } + /** + * 在后台线程中执行任务的主要方法,用于启动同步操作并返回同步状态码。 + * @param unused + * @return + */ @Override protected Integer doInBackground(Void... unused) { publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity @@ -93,6 +116,10 @@ public class GTaskASyncTask extends AsyncTask { return mTaskManager.sync(mContext, this); } + /** + * 在主线程中更新同步进度通知的方法,用于将同步进度信息发布到通知栏中。 + * @param progress + */ @Override protected void onProgressUpdate(String... progress) { showNotification(R.string.ticker_syncing, progress[0]); @@ -101,6 +128,10 @@ public class GTaskASyncTask extends AsyncTask { } } + /** + * 在主线程中处理同步结果的方法,根据同步状态码显示相应的通知,并在任务完成时回调OnCompleteListener接口。 + * @param result + */ @Override protected void onPostExecute(Integer result) { if (result == GTaskManager.STATE_SUCCESS) { diff --git a/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java b/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java index c67dfdf..20f8bbd 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java +++ b/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java @@ -62,6 +62,8 @@ import java.util.zip.InflaterInputStream; public class GTaskClient { + + //一些常量的定义 private static final String TAG = GTaskClient.class.getSimpleName(); private static final String GTASK_URL = "https://mail.google.com/tasks/"; @@ -90,6 +92,9 @@ public class GTaskClient { private JSONArray mUpdateArray; + /** + * Gtask服务器信息 + */ private GTaskClient() { mHttpClient = null; mGetUrl = GTASK_GET_URL; @@ -102,6 +107,10 @@ public class GTaskClient { mUpdateArray = null; } + /** + * 静态方法,用于获取GTaskClient单例对象。 + * @return + */ public static synchronized GTaskClient getInstance() { if (mInstance == null) { mInstance = new GTaskClient(); @@ -109,6 +118,13 @@ public class GTaskClient { return mInstance; } + /** + * 登录Google账户并获取GTask服务的授权Token。 + * 如果已经登录则不做处理,否则重新登录; + * 登录成功后,需要判断是否为自定义域名的Google账户,如是则使用对应的URL地址登录。 + * @param activity Activity + * @return bool + */ public boolean login(Activity activity) { // we suppose that the cookie would expire after 5 minutes // then we need to re-login @@ -164,6 +180,12 @@ public class GTaskClient { return true; } + /** + *该方法实现了登录Google账户并获取授权Token的过程 + * @param activity Activity + * @param invalidateToken Token + * @return NULL or Token + */ private String loginGoogleAccount(Activity activity, boolean invalidateToken) { String authToken; AccountManager accountManager = AccountManager.get(activity); @@ -207,6 +229,12 @@ public class GTaskClient { return authToken; } + /** + * 实现了尝试登录Gtask的过程 + * @param activity Activity + * @param authToken Token + * @return bool + */ private boolean tryToLoginGtask(Activity activity, String authToken) { if (!loginGtask(authToken)) { // maybe the auth token is out of date, now let's invalidate the @@ -225,6 +253,11 @@ public class GTaskClient { return true; } + /** + * 该方法实现了Gtask登录的过程 + * @param authToken + * @return + */ private boolean loginGtask(String authToken) { int timeoutConnection = 10000; int timeoutSocket = 15000; @@ -280,10 +313,18 @@ public class GTaskClient { return true; } + /** + * 实现了获取当前操作id的功能,每次调用该方法时,将操作id加一并返回 + * @return + */ private int getActionId() { return mActionId++; } + /** + * 实现了创建一个HttpPost对象的功能,并设置了请求头信息。 + * @return + */ private HttpPost createHttpPost() { HttpPost httpPost = new HttpPost(mPostUrl); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); @@ -291,6 +332,12 @@ public class GTaskClient { return httpPost; } + /** + * 用于将返回结果的流数据读取并转化成字符串形式 + * @param entity + * @return + * @throws IOException + */ private String getResponseContent(HttpEntity entity) throws IOException { String contentEncoding = null; if (entity.getContentEncoding() != null) { @@ -323,6 +370,12 @@ public class GTaskClient { } } + /** + * 实现了POST请求的功能 + * @param js + * @return + * @throws NetworkFailureException + */ private JSONObject postRequest(JSONObject js) throws NetworkFailureException { if (!mLoggedin) { Log.e(TAG, "please login first"); @@ -360,6 +413,11 @@ public class GTaskClient { } } + /** + * 负责创建任务,在请求返回结果后将新增的任务的gid字段设置为返回结果中的新id。 + * @param task + * @throws NetworkFailureException + */ public void createTask(Task task) throws NetworkFailureException { commitUpdate(); try { @@ -386,6 +444,11 @@ public class GTaskClient { } } + /** + * 负责创建任务列表,在请求返回结果后将新增的列表的gid字段设置为返回结果中的新id。 + * @param tasklist + * @throws NetworkFailureException + */ public void createTaskList(TaskList tasklist) throws NetworkFailureException { commitUpdate(); try { @@ -412,6 +475,10 @@ public class GTaskClient { } } + /** + * 用于提交更新,即将所有等待提交的更新操作组成的JSON数组提交到服务器端 + * @throws NetworkFailureException + */ public void commitUpdate() throws NetworkFailureException { if (mUpdateArray != null) { try { @@ -433,6 +500,11 @@ public class GTaskClient { } } + /** + * 用于向待提交的更新操作数组中添加一个操作 + * @param node + * @throws NetworkFailureException + */ public void addUpdateNode(Node node) throws NetworkFailureException { if (node != null) { // too many update items may result in an error @@ -447,6 +519,13 @@ public class GTaskClient { } } + /** + * 用于将一个任务从一个列表中移动到另一个列表中,或者在同一列表中进行位置调整 + * @param task + * @param preParent + * @param curParent + * @throws NetworkFailureException + */ public void moveTask(Task task, TaskList preParent, TaskList curParent) throws NetworkFailureException { commitUpdate(); @@ -486,6 +565,11 @@ public class GTaskClient { } } + /** + * 用于删除一个节点,即设置节点的deleted属性为true,并将待提交的操作添加到提交数组中 + * @param node + * @throws NetworkFailureException + */ public void deleteNode(Node node) throws NetworkFailureException { commitUpdate(); try { @@ -509,6 +593,11 @@ public class GTaskClient { } } + /** + * 用于获取当前用户的任务列表 + * @return + * @throws NetworkFailureException + */ public JSONArray getTaskLists() throws NetworkFailureException { if (!mLoggedin) { Log.e(TAG, "please login first"); @@ -547,6 +636,12 @@ public class GTaskClient { } } + /** + * 用于获取指定任务列表中的所有任务。 + * @param listGid + * @return + * @throws NetworkFailureException + */ public JSONArray getTaskList(String listGid) throws NetworkFailureException { commitUpdate(); try { @@ -575,10 +670,17 @@ public class GTaskClient { } } + /** + * 返回当前同步的Google账号信息 + * @return + */ public Account getSyncAccount() { return mAccount; } + /** + * 则将待提交的操作数组mUpdateArray重置为null,以便进行下一轮的操作。 + */ public void resetUpdateArray() { mUpdateArray = null; } diff --git a/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java b/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java index d2b4082..e69113e 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java +++ b/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java @@ -49,6 +49,7 @@ import java.util.Map; public class GTaskManager { + //一些常量的定义 private static final String TAG = GTaskManager.class.getSimpleName(); public static final int STATE_SUCCESS = 0; @@ -87,6 +88,9 @@ public class GTaskManager { private HashMap mNidToGid; + /** + * 构造函数中初始化了该类使用到的各种变量,包括任务列表、任务、元数据等。 + */ private GTaskManager() { mSyncing = false; mCancelled = false; @@ -99,6 +103,10 @@ public class GTaskManager { mNidToGid = new HashMap(); } + /** + * 用于获取唯一的实例 + * @return + */ public static synchronized GTaskManager getInstance() { if (mInstance == null) { mInstance = new GTaskManager(); @@ -106,11 +114,21 @@ public class GTaskManager { return mInstance; } + /** + * 用于设置当前活动的上下文环境,即调用该方法的Activity对象。该方法主要用于获取Google账号的AuthToken。 + * @param activity + */ public synchronized void setActivityContext(Activity activity) { // used for getting authtoken mActivity = activity; } + /** + * 用于执行同步操作 + * @param context + * @param asyncTask + * @return + */ public int sync(Context context, GTaskASyncTask asyncTask) { if (mSyncing) { Log.d(TAG, "Sync is in progress"); @@ -168,6 +186,10 @@ public class GTaskManager { return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; } + /** + * 用于初始化谷歌任务列表,包括元数据列表和所有任务列表以及它们的任务 + * @throws NetworkFailureException + */ private void initGTaskList() throws NetworkFailureException { if (mCancelled) return; @@ -247,6 +269,10 @@ public class GTaskManager { } } + /** + * 用于执行内容同步操作 + * @throws NetworkFailureException + */ private void syncContent() throws NetworkFailureException { int syncType; Cursor c = null; @@ -351,6 +377,11 @@ public class GTaskManager { } + /** + * 同步本地文件夹和Google Tasks的文件夹 + * 对于根文件夹、通话录音文件夹、本地已存在的文件夹和远程添加的文件夹进行分别处理 + * @throws NetworkFailureException + */ private void syncFolder() throws NetworkFailureException { Cursor c = null; String gid; @@ -476,6 +507,13 @@ public class GTaskManager { GTaskClient.getInstance().commitUpdate(); } + /** + * 具体的同步操作,利用参数syncType的不同,实现增加本地节点、增加远程节点、删除本地节点、删除远程节点、更新本地节点、更新远程节点等操作。 + * @param syncType + * @param node + * @param c + * @throws NetworkFailureException + */ private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -522,6 +560,11 @@ public class GTaskManager { } } + /** + * 向本地添加新节点的具体操作,包括创建SqlNote、更新gid-nid映射等。 + * @param node + * @throws NetworkFailureException + */ private void addLocalNode(Node node) throws NetworkFailureException { if (mCancelled) { return; @@ -596,6 +639,12 @@ public class GTaskManager { updateRemoteMeta(node.getGid(), sqlNote); } + /** + * 用于更新本地节点,即将Google任务列表或任务的信息更新到本地SQLite数据库中 + * @param node + * @param c + * @throws NetworkFailureException + */ private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -619,6 +668,12 @@ public class GTaskManager { updateRemoteMeta(node.getGid(), sqlNote); } + /** + * 用于添加远程节点,即在Google服务端新建任务列表或者任务,然后根据返回的Gid来更新本地SQLite数据库,并更新元数据。 + * @param node + * @param c + * @throws NetworkFailureException + */ private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -692,6 +747,12 @@ public class GTaskManager { mNidToGid.put(sqlNote.getId(), n.getGid()); } + /** + * 用于更新远程节点,即在Google服务端更新任务列表或者任务,在根据返回信息来更新本地SQLite数据库,并更新元数据。 + * @param node + * @param c + * @throws NetworkFailureException + */ private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -730,6 +791,12 @@ public class GTaskManager { sqlNote.commit(true); } + /** + * 用于更新笔记的元数据,即与笔记相关的元信息 + * @param gid + * @param sqlNote + * @throws NetworkFailureException + */ private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { if (sqlNote != null && sqlNote.isNoteType()) { MetaData metaData = mMetaHashMap.get(gid); @@ -746,6 +813,10 @@ public class GTaskManager { } } + /** + * 用于刷新本地SQLite数据库中笔记的同步ID。 + * @throws NetworkFailureException + */ private void refreshLocalSyncId() throws NetworkFailureException { if (mCancelled) { return; @@ -790,10 +861,17 @@ public class GTaskManager { } } + /** + * 获取当前Google账户的同步账户名称。 + * @return + */ public String getSyncAccount() { return GTaskClient.getInstance().getSyncAccount().name; } + /** + * 取消同步过程。 + */ public void cancelSync() { mCancelled = true; } diff --git a/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java b/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java index cca36f7..51ca7c7 100644 --- a/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java +++ b/src/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java @@ -23,6 +23,9 @@ import android.content.Intent; import android.os.Bundle; import android.os.IBinder; +/** + * 谷歌任务同步服务,用于将本地备忘录数据同步到Google Tasks中 + */ public class GTaskSyncService extends Service { public final static String ACTION_STRING_NAME = "sync_action_type"; @@ -42,6 +45,9 @@ public class GTaskSyncService extends Service { private static String mSyncProgress = ""; + /** + * 用于启动同步任务 + */ private void startSync() { if (mSyncTask == null) { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { @@ -56,17 +62,30 @@ public class GTaskSyncService extends Service { } } + /** + * 用于取消同步任务 + */ private void cancelSync() { if (mSyncTask != null) { mSyncTask.cancelSync(); } } + /** + * 用于在服务创建时初始化相关资源 + */ @Override public void onCreate() { mSyncTask = null; } + /** + * 在接收同步操作命令时启动同步任务或取消同步任务 + * @param intent + * @param flags + * @param startId + * @return + */ @Override public int onStartCommand(Intent intent, int flags, int startId) { Bundle bundle = intent.getExtras(); @@ -86,6 +105,9 @@ public class GTaskSyncService extends Service { return super.onStartCommand(intent, flags, startId); } + /** + * 在低内存情况下停止同步任务。 + */ @Override public void onLowMemory() { if (mSyncTask != null) { @@ -97,6 +119,10 @@ public class GTaskSyncService extends Service { return null; } + /** + * 向应用内发送广播消息,通知相关观察者同步任务的执行状态和进度信息。 + * @param msg + */ public void sendBroadcast(String msg) { mSyncProgress = msg; Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); @@ -105,6 +131,10 @@ public class GTaskSyncService extends Service { sendBroadcast(intent); } + /** + * 用于在Activity中启动同步服务。 + * @param activity + */ public static void startSync(Activity activity) { GTaskManager.getInstance().setActivityContext(activity); Intent intent = new Intent(activity, GTaskSyncService.class); @@ -112,16 +142,28 @@ public class GTaskSyncService extends Service { activity.startService(intent); } + /** + * 用于在Activity中取消同步服务。 + * @param context + */ public static void cancelSync(Context context) { Intent intent = new Intent(context, GTaskSyncService.class); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); context.startService(intent); } + /** + * 用于检测当前是否正在执行同步任务 + * @return + */ public static boolean isSyncing() { return mSyncTask != null; } + /** + * 用于获取同步进度信息。 + * @return + */ public static String getProgressString() { return mSyncProgress; } diff --git a/src/app/src/main/java/net/micode/notes/model/Note.java b/src/app/src/main/java/net/micode/notes/model/Note.java index 6706cf6..4537e5e 100644 --- a/src/app/src/main/java/net/micode/notes/model/Note.java +++ b/src/app/src/main/java/net/micode/notes/model/Note.java @@ -33,13 +33,16 @@ import net.micode.notes.data.Notes.TextNote; import java.util.ArrayList; - +/** + * 要作用是封装了数据操作逻辑,并提供了方便的接口给外部进行调用。 + */ public class Note { private ContentValues mNoteDiffValues; private NoteData mNoteData; private static final String TAG = "Note"; /** * Create a new note id for adding a new note to databases + * 获取新的笔记 ID */ public static synchronized long getNewNoteId(Context context, long folderId) { // Create a new note in the database @@ -70,36 +73,73 @@ public class Note { mNoteData = new NoteData(); } + /** + * 设置笔记的值。 + * @param key + * @param value + */ public void setNoteValue(String key, String value) { mNoteDiffValues.put(key, value); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); } + /** + * 设置笔记数据的值。 + * @param key + * @param value + */ public void setTextData(String key, String value) { mNoteData.setTextData(key, value); } + /** + * 设置笔记数据的ID。 + * @param id + */ public void setTextDataId(long id) { mNoteData.setTextDataId(id); } + /** + * 获取笔记数据的ID。 + * @return + */ public long getTextDataId() { return mNoteData.mTextDataId; } + /** + * 设置笔记数据的ID。 + * @param id + */ public void setCallDataId(long id) { mNoteData.setCallDataId(id); } + /** + * 设置笔记数据的值。 + * @param key + * @param value + */ public void setCallData(String key, String value) { mNoteData.setCallData(key, value); } + /** + * 返回笔记是否已被本地修改。 + * @return + */ public boolean isLocalModified() { return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); } + /** + * 判断笔记是否需要同步,如果需要则更新笔记到 ContentProvider 中。 + * @param context + * @param noteId + * @return + */ public boolean syncNote(Context context, long noteId) { if (noteId <= 0) { throw new IllegalArgumentException("Wrong note id:" + noteId); @@ -148,10 +188,18 @@ public class Note { mCallDataId = 0; } + /** + * 判断笔记数据是否已经被本地修改。 + * @return + */ boolean isLocalModified() { return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; } + /** + * 设置文本数据的 ID。 + * @param id + */ void setTextDataId(long id) { if(id <= 0) { throw new IllegalArgumentException("Text data id should larger than 0"); @@ -159,6 +207,10 @@ public class Note { mTextDataId = id; } + /** + * 设置电话数据的 ID。 + * @param id + */ void setCallDataId(long id) { if (id <= 0) { throw new IllegalArgumentException("Call data id should larger than 0"); @@ -166,18 +218,34 @@ public class Note { mCallDataId = id; } + /** + * 设置笔记中电话数据的值。 + * @param key + * @param value + */ void setCallData(String key, String value) { mCallDataValues.put(key, value); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); } + /** + * 设置笔记中文本数据的值。 + * @param key + * @param value + */ void setTextData(String key, String value) { mTextDataValues.put(key, value); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); } + /** + * 将笔记数据插入 ContentProvider 中,同时更新对应的数据 ID。 + * @param context + * @param noteId + * @return + */ Uri pushIntoContentResolver(Context context, long noteId) { /** * Check for safety diff --git a/src/app/src/main/java/net/micode/notes/model/WorkingNote.java b/src/app/src/main/java/net/micode/notes/model/WorkingNote.java index be081e4..c20387f 100644 --- a/src/app/src/main/java/net/micode/notes/model/WorkingNote.java +++ b/src/app/src/main/java/net/micode/notes/model/WorkingNote.java @@ -31,7 +31,9 @@ import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.TextNote; import net.micode.notes.tool.ResourceParser.NoteBgResources; - +/** + * 它用于代表一条笔记,并提供了一些操作笔记的方法。 + */ public class WorkingNote { // Note for the working note private Note mNote; @@ -146,6 +148,7 @@ public class WorkingNote { loadNoteData(); } + private void loadNoteData() { Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { @@ -174,6 +177,15 @@ public class WorkingNote { } } + /** + * 创建一个新的空笔记。 + * @param context + * @param folderId + * @param widgetId + * @param widgetType + * @param defaultBgColorId + * @return + */ public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, int widgetType, int defaultBgColorId) { WorkingNote note = new WorkingNote(context, folderId); @@ -183,10 +195,20 @@ public class WorkingNote { return note; } + /** + * 加载指定 Id 的笔记。 + * @param context + * @param id + * @return + */ public static WorkingNote load(Context context, long id) { return new WorkingNote(context, id, 0); } + /** + * 保存当前笔记。 + * @return + */ public synchronized boolean saveNote() { if (isWorthSaving()) { if (!existInDatabase()) { @@ -225,10 +247,19 @@ public class WorkingNote { } } + /** + * 设置笔记设置变化的监听器。 + * @param l + */ public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { mNoteSettingStatusListener = l; } + /** + * 设置闹钟提醒时间。 + * @param date + * @param set + */ public void setAlertDate(long date, boolean set) { if (date != mAlertDate) { mAlertDate = date; @@ -239,6 +270,10 @@ public class WorkingNote { } } + /** + * 标记笔记是否被删除。 + * @param mark + */ public void markDeleted(boolean mark) { mIsDeleted = mark; if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID @@ -247,6 +282,10 @@ public class WorkingNote { } } + /** + * 设置笔记的背景颜色。 + * @param id + */ public void setBgColorId(int id) { if (id != mBgColorId) { mBgColorId = id; @@ -257,6 +296,10 @@ public class WorkingNote { } } + /** + * 设置笔记的模式。 + * @param mode + */ public void setCheckListMode(int mode) { if (mMode != mode) { if (mNoteSettingStatusListener != null) { @@ -267,6 +310,10 @@ public class WorkingNote { } } + /** + * 设置笔记关联的小部件类型。 + * @param type + */ public void setWidgetType(int type) { if (type != mWidgetType) { mWidgetType = type; @@ -274,6 +321,10 @@ public class WorkingNote { } } + /** + * 设置笔记关联的小部件 Id。 + * @param id + */ public void setWidgetId(int id) { if (id != mWidgetId) { mWidgetId = id; @@ -281,6 +332,10 @@ public class WorkingNote { } } + /** + * 设置笔记的文本内容。 + * @param text + */ public void setWorkingText(String text) { if (!TextUtils.equals(mContent, text)) { mContent = text; @@ -288,12 +343,18 @@ public class WorkingNote { } } + /** + * 将该笔记转化为呼叫记录。 + * @param phoneNumber + * @param callDate + */ public void convertToCallNote(String phoneNumber, long callDate) { mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); } + //一些获取方法 public boolean hasClockAlert() { return (mAlertDate > 0 ? true : false); } @@ -342,24 +403,31 @@ public class WorkingNote { return mWidgetType; } + /** + * 用于监听笔记设置的变化。 + */ public interface NoteSettingChangedListener { /** * Called when the background color of current note has just changed + * 当当前笔记的背景色改变时被调用。 */ void onBackgroundColorChanged(); /** * Called when user set clock + * 当闹钟提醒设置改变时被调用,参数 date 表示提醒时间,set 表示是否设置了提醒。 */ void onClockAlertChanged(long date, boolean set); /** * Call when user create note from widget + * 当用户从小部件创建新笔记时被调用。 */ void onWidgetChanged(); /** * Call when switch between check list mode and normal mode + * 当切换到检查列表模式或常规模式时被调用,参数 oldMode 表示变化前的模式,newMode 表示新的模式。 * @param oldMode is previous mode before change * @param newMode is new mode */ diff --git a/src/app/src/main/java/net/micode/notes/ui/NotesListActivity.java b/src/app/src/main/java/net/micode/notes/ui/NotesListActivity.java index e843aec..2b54931 100644 --- a/src/app/src/main/java/net/micode/notes/ui/NotesListActivity.java +++ b/src/app/src/main/java/net/micode/notes/ui/NotesListActivity.java @@ -17,6 +17,8 @@ package net.micode.notes.ui; import android.app.Activity; +import androidx.appcompat.app.AppCompatActivity; + import android.app.AlertDialog; import android.app.Dialog; import android.appwidget.AppWidgetManager; @@ -78,7 +80,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashSet; -public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { +public class NotesListActivity extends AppCompatActivity implements OnClickListener, OnItemLongClickListener { private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; private static final int FOLDER_LIST_QUERY_TOKEN = 1; diff --git a/src/build.gradle b/src/build.gradle index 45fb87c..3cc2d1c 100644 --- a/src/build.gradle +++ b/src/build.gradle @@ -2,8 +2,8 @@ buildscript { repositories { - jcenter() google()//add + jcenter() } dependencies { classpath 'com.android.tools.build:gradle:7.4.2' @@ -12,7 +12,7 @@ buildscript { allprojects { repositories { - jcenter() google()//add + jcenter() } } diff --git a/src/gradle.properties b/src/gradle.properties new file mode 100644 index 0000000..0aaace3 --- /dev/null +++ b/src/gradle.properties @@ -0,0 +1,3 @@ +# Enable AndroidX and Jetifier +android.useAndroidX=true +android.enableJetifier=true