diff --git a/doc/实验二.docx b/doc/实验二.docx deleted file mode 100644 index 3b3f8a1..0000000 Binary files a/doc/实验二.docx and /dev/null differ diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/data/Contact.java b/src/xiaomi/Notes-master/src/net/micode/notes/data/Contact.java index d97ac5d..c003cdf 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/data/Contact.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/data/Contact.java @@ -18,6 +18,8 @@ package net.micode.notes.data; import android.content.Context; import android.database.Cursor; +import android.provider.CloudMediaProviderContract; +import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Data; import android.telephony.PhoneNumberUtils; @@ -26,12 +28,14 @@ import android.util.Log; import java.util.HashMap; public class Contact { - private static HashMap sContactCache; - private static final String TAG = "Contact"; + private static HashMap sContactCache;//定义一个HashMap集合,string,string类型 + private static final String TAG = "Contact";//作为日志标签 + private static ContactsContract.Contacts.Entity DataColumns; + //表示呼叫者识别(Caller ID)的选择 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 " + + ",?) AND " + DataColumns.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + + " AND " + DataColumns.RAW_CONTACT_ID + " IN " + "(SELECT raw_contact_id " + " FROM phone_lookup" + " WHERE min_match = '+')"; @@ -41,31 +45,37 @@ public class Contact { sContactCache = new HashMap(); } - if(sContactCache.containsKey(phoneNumber)) { + if(sContactCache.containsKey(phoneNumber)) {// 查找HashMap中是否已有phoneNumber信息 return sContactCache.get(phoneNumber); } String selection = CALLER_ID_SELECTION.replace("+", PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); - Cursor cursor = context.getContentResolver().query( + // 查找数据库中phoneNumber的信息 + CloudMediaProviderContract.AlbumColumns ContactsColumns = null; + Cursor cursor = context.getContentResolver().query(//Cursor 是一个用于遍历数据库查询结果的对象 Data.CONTENT_URI, - new String [] { Phone.DISPLAY_NAME }, + new String [] { ContactsColumns.DISPLAY_NAME }, selection, new String[] { phoneNumber }, null); - + // 判定查询结果 + // moveToFirst()返回第一条 if (cursor != null && cursor.moveToFirst()) { try { + //找到相关信息 String name = cursor.getString(0); - sContactCache.put(phoneNumber, name); + sContactCache.put(phoneNumber, name);//添加电话号和姓名至集合 return name; - } catch (IndexOutOfBoundsException e) { + + } catch (IndexOutOfBoundsException e) {//报错 Log.e(TAG, " Cursor get string error " + e.toString()); return null; } finally { cursor.close(); } } else { + //匹配电话号失败,Log.d() 打印一条带有该标签的日志消息 Log.d(TAG, "No contact matched with number:" + phoneNumber); return null; } diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/data/NotesDatabaseHelper.java b/src/xiaomi/Notes-master/src/net/micode/notes/data/NotesDatabaseHelper.java index ffe5d57..c2f12e4 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/data/NotesDatabaseHelper.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/data/NotesDatabaseHelper.java @@ -16,23 +16,25 @@ 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.content.ContentValues;//就是用于保存一些数据(string boolean byte double float int long short ...)信息,这些信息可以被数据库操作时使用。 +import android.content.Context;//加载和访问资源。(android中主要是这两个功能,但是这里具体不清楚) +import android.database.sqlite.SQLiteDatabase;//主要提供了对应于添加、删除、更新、查询的操作方法: insert()、delete()、update()和query()。配合content.values +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; public class NotesDatabaseHelper extends SQLiteOpenHelper { - private static final String DB_NAME = "note.db"; + private static final String DB_NAME = "note.db";//定义一个数据库 private static final int DB_VERSION = 4; - public interface TABLE { + public interface TABLE {//一个接口类型,通常用于表示一个数据表的结构 public static final String NOTE = "note"; public static final String DATA = "data"; @@ -40,7 +42,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { private static final String TAG = "NotesDatabaseHelper"; - private static NotesDatabaseHelper mInstance; + private static NotesDatabaseHelper mInstance;//用于存储一个NotesDatabaseHelper类的对象。 private static final String CREATE_NOTE_TABLE_SQL = "CREATE TABLE " + TABLE.NOTE + "(" + @@ -61,7 +63,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + - ")"; + ")";//数据库中需要存储的项目的名称,就相当于创建一个表格的表头的内容 private static final String CREATE_DATA_TABLE_SQL = "CREATE TABLE " + TABLE.DATA + "(" + @@ -76,7 +78,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + - ")"; + ")";//这段代码是用于创建一个名为"DATA"的数据表的SQL语句。 private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = "CREATE INDEX IF NOT EXISTS note_id_index ON " + @@ -106,7 +108,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper { " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + " END"; - + //这段代码是用于创建一个触发器,当笔记表(Note)中的父ID字段(PARENT_ID)更新时,会自动减少与之关联的子笔记的数量。 + // 具体来说,它会在笔记表(Note)中查找与被更新的笔记(old)具有相同父ID的笔记,并将其数量减1。 /** * Increase folder's note count when insert new note to the folder */ diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/data/NotesProvider.java b/src/xiaomi/Notes-master/src/net/micode/notes/data/NotesProvider.java index edb0a60..3dd6e4e 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/data/NotesProvider.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/data/NotesProvider.java @@ -29,14 +29,14 @@ 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; +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;//定义了一个枚举类型,表示数据库表的名称。 -public class NotesProvider extends ContentProvider { - private static final UriMatcher mMatcher; +public class NotesProvider extends ContentProvider {//android中的ContentProvider类 + private static final UriMatcher mMatcher;//riMatcher是Android中的一个类,用于匹配URI。 private NotesDatabaseHelper mHelper; @@ -51,34 +51,37 @@ public class NotesProvider extends ContentProvider { private static final int URI_SEARCH_SUGGEST = 6; static { - mMatcher = new UriMatcher(UriMatcher.NO_MATCH); + mMatcher = new UriMatcher(UriMatcher.NO_MATCH);// + //创建一个UriMatcher对象mMatcher,初始值为UriMatcher.NO_MATCH,表示没有任何匹配规则。 mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); + //第一个参数是authority(授权),第二个参数是路径,第三个参数是匹配的URI类型。 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); - } + }//根据不同的URI路径,确定应该调用哪个处理程序来处理请求 + //例如,当用户访问"http://example.com/note"时,mMatcher会匹配到第一个规则 /** * 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. */ - 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; - + 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查询语句,以便在数据库中搜索和检索相关笔记。 private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION - + " FROM " + TABLE.NOTE + + " FROM " + TABLE.NOTE//从名为TABLE.NOTE的表中检索数据 + " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; - + //是一个SQL查询语句,用于从数据库中检索与给定搜索条件匹配的笔记 @Override public boolean onCreate() { mHelper = NotesDatabaseHelper.getInstance(getContext()); @@ -86,12 +89,15 @@ public class NotesProvider extends ContentProvider { } @Override + //查询uri在数据库的位置 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); @@ -113,6 +119,7 @@ public class NotesProvider extends ContentProvider { 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"); } @@ -148,10 +155,12 @@ public class NotesProvider extends ContentProvider { } @Override + //插入uri public Uri insert(Uri uri, ContentValues values) { - SQLiteDatabase db = mHelper.getWritableDatabase(); - long dataId = 0, noteId = 0, insertedId = 0; + 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; @@ -167,6 +176,7 @@ public class NotesProvider extends ContentProvider { throw new IllegalArgumentException("Unknown URI " + uri); } // Notify the note uri + //通知Android系统中的Notes应用程序,某个笔记或数据已经发生了变化 if (noteId > 0) { getContext().getContentResolver().notifyChange( ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); @@ -177,11 +187,15 @@ public class NotesProvider extends ContentProvider { getContext().getContentResolver().notifyChange( ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); } - + //它通过调用getContentResolver().notifyChange()方法来实现这个功能。 + //在这段代码中,首先检查noteId和dataId是否大于0,以确保它们是有效的ID。然后,使用ContentUris.withAppendedId()方法来构建对应的URI, + // 其中Notes.CONTENT_NOTE_URI和Notes.CONTENT_DATA_URI分别表示笔记和数据的URI。 + // 最后,调用getContext().getContentResolver().notifyChange()方法并传入构建好的URI,以通知系统该URI所对应的资源已经发生了变化。 return ContentUris.withAppendedId(uri, insertedId); } @Override + //删除一个uri,操作与上面差不多 public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0; String id = null; @@ -218,6 +232,7 @@ public class NotesProvider extends ContentProvider { default: throw new IllegalArgumentException("Unknown URI " + uri); } + //通知系统相关数据已经发生变化,以便进行相应的更新或处理。 if (count > 0) { if (deleteData) { getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); @@ -228,6 +243,7 @@ public class NotesProvider extends ContentProvider { } @Override + //更新uri public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = 0; String id = null; @@ -270,9 +286,10 @@ public class NotesProvider extends ContentProvider { private String parseSelection(String selection) { return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); } - + //这段代码是一个私有方法,用于增加笔记的版本号。 + // 它接受三个参数:id(笔记的ID)、selection(查询条件)和selectionArgs(查询条件的参数) private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { - StringBuilder sql = new StringBuilder(120); + StringBuilder sql = new StringBuilder(120);//sql对象,构建SQL语句 sql.append("UPDATE "); sql.append(TABLE.NOTE); sql.append(" SET "); @@ -280,12 +297,14 @@ public class NotesProvider extends ContentProvider { sql.append("=" + NoteColumns.VERSION + "+1 "); if (id > 0 || !TextUtils.isEmpty(selection)) { - sql.append(" WHERE "); + sql.append(" WHERE ");//那么在WHERE子句中添加相应的条件 } if (id > 0) { sql.append(NoteColumns.ID + "=" + String.valueOf(id)); + ////将笔记ID等于给定id的条件添加到WHERE子句中 } if (!TextUtils.isEmpty(selection)) { + //那么将解析后的查询条件添加到WHERE子句中。 String selectString = id > 0 ? parseSelection(selection) : selection; for (String args : selectionArgs) { selectString = selectString.replaceFirst("\\?", args); diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/exception/ActionFailureException.java b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/exception/ActionFailureException.java index 15504be..b82bd8a 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/exception/ActionFailureException.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/exception/ActionFailureException.java @@ -15,14 +15,34 @@ */ package net.micode.notes.gtask.exception; - +/** + * @aPackage : net.micode.notes.gtask.exception + * @aClassName: ActionFailureException + * @Description: + * 该类是一个名为 ActionFailureException的公共类,该类继承自 RuntimeException 类 + * RuntimeException 是Java中的一个异常类,它是所有运行时异常的父类。 + * 当程序在运行过程中遇到无法处理的错误或异常情况时,会抛出 RuntimeException 类型的异常 + * 作用: + * 通过继承的方式,ActionFailureException 类可以自定义自己的异常行为和处理方式 + * 以便更精确地描述和处理这种特定类型的异常 + * @aAuthor: Li Qiushi + * @createdate: 12/24/2023 19:31 PM + */ public class ActionFailureException extends RuntimeException { private static final long serialVersionUID = 4425249765923293627L; - + /* + * serialVersionUID相当于java类的身份证。主要用于版本控制。 + * serialVersionUID作用是序列化时保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。 + */ public ActionFailureException() { super(); } - + /* + * 在JAVA类中使用super来引用父类的成分,用this来引用当前对象. + * 如果一个类从另外一个类继承,我们new这个子类的实例对象的时候,这个子类对象里面会有一个父类对象。 + * 怎么去引用里面的父类对象呢?使用super来引用 + * 也就是说,此处super()以及super (paramString)可认为是Exception ()和Exception (paramString) + */ public ActionFailureException(String paramString) { super(paramString); } diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/exception/NetworkFailureException.java b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/exception/NetworkFailureException.java index b08cfb1..90a60f4 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/exception/NetworkFailureException.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/exception/NetworkFailureException.java @@ -15,14 +15,30 @@ */ package net.micode.notes.gtask.exception; - +/** + * @aPackage : net.micode.notes.gtask.exception + * @aClassName: NetworkFailureException + * @Description: + * 该类继承自Java的内置异常类 Exception + * 在Java中,异常(Exception)是一种用于处理程序运行时可能出现的错误情况的对象 + * 当程序在运行过程中遇到无法处理的错误或异常情况时,会抛出 RuntimeException 类型的异常 + * 作用: + * 通过继承Exception类,可以自定义自己的异常类型,以便更好地描述和处理特定类型的错误 + * @aAuthor: Li Qiushi + * @createdate: 12/24/2023 19:31 PM + */ public class NetworkFailureException extends Exception { private static final long serialVersionUID = 2107610287180234136L; - + /* + * serialVersionUID相当于java类的身份证。主要用于版本控制。 + * serialVersionUID作用是序列化时保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。 + */ public NetworkFailureException() { super(); } - + /* + super()含义与ActionFailureException类的相同 + */ public NetworkFailureException(String paramString) { super(paramString); } diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskASyncTask.java b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskASyncTask.java index b3b61e7..9a48e8e 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskASyncTask.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskASyncTask.java @@ -27,8 +27,19 @@ import android.os.AsyncTask; import net.micode.notes.R; import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesPreferenceActivity; - - +/** + * @aPackage : net.micode.notes.gtask.remote + * @aClassName: GTaskASyncTask + * @Description: + * 异步操作类,实现GTask的异步操作过程 + * 主要方法: + * showNotification(int tickerId, String content) 向用户提示当前同步的状态,是一个用于交互的方法 + * doInBackground(Void... unused) 此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间 + * onProgressUpdate(String... progress) 可以使用进度条增加用户体验度。 此方法在主线程执行,用于显示任务执行的进度。 + * onPostExecute(Integer result) 相当于Handler 处理UI的方式,在这里面可以使用在doInBackground 得到的结果处理操作UI + * @aAuthor: Li Qiushi + * @createdate: 12/24/2023 19:31 PM + */ public class GTaskASyncTask extends AsyncTask { private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; @@ -48,6 +59,9 @@ public class GTaskASyncTask extends AsyncTask { public GTaskASyncTask(Context context, OnCompleteListener listener) { mContext = context; mOnCompleteListener = listener; + /* + 获取系统服务中的NotificationManager对象,并将其赋值给成员变量mNotifiManager。这个对象用于管理应用程序的通知 + */ mNotifiManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); mTaskManager = GTaskManager.getInstance(); @@ -57,18 +71,19 @@ public class GTaskASyncTask extends AsyncTask { mTaskManager.cancelSync(); } - public void publishProgess(String message) { + public void publishProgess(String message) {//发布进度单位,系统将会调用onProgressUpdate()方法更新这些值 publishProgress(new String[] { message }); } - private void showNotification(int tickerId, String content) { - Notification notification = new Notification(R.drawable.notification, mContext - .getString(tickerId), System.currentTimeMillis()); - notification.defaults = Notification.DEFAULT_LIGHTS; - notification.flags = Notification.FLAG_AUTO_CANCEL; - PendingIntent pendingIntent; + /** + * 该函数用于向用户提示当前同步的状态,是一个用于交互的方法 + * 两个参数:一个整数类型的tickerId,表示通知的唯一标识符 + * 和一个字符串类型的content,表示通知的内容,可以是任何文本信息,例如消息、警告或其他相关信息 + */ + private void showNotification(int tickerId, String content) { + PendingIntent pendingIntent;//一个描述了想要启动一个Activity、Broadcast或是Service的意图 if (tickerId != R.string.ticker_success) { pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesPreferenceActivity.class), 0); @@ -77,16 +92,41 @@ public class GTaskASyncTask extends AsyncTask { pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesListActivity.class), 0); } - notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, - pendingIntent); + /* + 如果同步不成功,那么从系统取得一个用于启动一个NotesPreferenceActivity的PendingIntent对象 + 如果同步成功,那么从系统取得一个用于启动一个NotesListActivity的PendingIntent对象 + */ + + 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(); + //通过NotificationManager对象的notify()方法来执行一个notification的消息 mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); } + /** + *用于在后台线程中执行耗时操作具体来说,它的作用是在后台线程中同步数据 + * 它是一个受保护的方法,返回类型为Integer。该方法接受一个可变参数unused,表示没有使用到的参数 + */ @Override protected Integer doInBackground(Void... unused) { publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity .getSyncAccountName(mContext))); + /* + publishProgess用于更新进度信息,NotesPreferenceActivity.getSyncAccountName(mContext)来生成进度信息 + 利用getString,把进程信息的内容传进sync_progress_login中 + + */ return mTaskManager.sync(mContext, this); + /* + 进行后台同步具体操作 + sync方法接受两个参数:一个是上下文对象mContext,另一个是当前对象this + */ } @Override @@ -97,6 +137,15 @@ public class GTaskASyncTask extends AsyncTask { } } + /** + * 用于在执行完后台任务后更新UI,显示结果 + * 根据不同的执行结果,代码会调用showNotification方法来显示相应的通知信息 + * 显示的不同结果: + * 如果结果为GTaskManager.STATE_SUCCESS,则显示成功同步的通知 + * 如果结果为GTaskManager.STATE_NETWORK_ERROR,则显示网络错误的通知 + * 如果结果为GTaskManager.STATE_INTERNAL_ERROR,则显示内部错误的通知 + * 如果结果为GTaskManager.STATE_SYNC_CANCELLED,则显示同步取消的通知 + */ @Override protected void onPostExecute(Integer result) { if (result == GTaskManager.STATE_SUCCESS) { @@ -111,6 +160,9 @@ public class GTaskASyncTask extends AsyncTask { showNotification(R.string.ticker_cancel, mContext .getString(R.string.error_sync_cancelled)); } + /* + 如果存在mOnCompleteListener对象,代码还会创建一个新的线程来执行mOnCompleteListener.onComplete()方法,以完成一次操作 + */ if (mOnCompleteListener != null) { new Thread(new Runnable() { diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskClient.java b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskClient.java index c67dfdf..4044e44 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskClient.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskClient.java @@ -59,7 +59,15 @@ import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; - +/** + * @aPackage : net.micode.notes.gtask.remote + * @aClassName: GTaskClient + * @Description: + * 主要功能:实现GTASK的登录操作,进行GTASK任务的创建,创建任务列表,从网络上获取任务和任务列表的内容 + * 主要使用类或技术:accountManager JSONObject HttpParams authToken Gid + * @aAuthor: Li Qiushi + * @createdate: 12/24/2023 19:31 PM + */ public class GTaskClient { private static final String TAG = GTaskClient.class.getSimpleName(); @@ -102,6 +110,10 @@ public class GTaskClient { mUpdateArray = null; } + /* 用来获取的实例化对象 + * 使用 getInstance() + * 返回mInstance这个实例化对象 + */ public static synchronized GTaskClient getInstance() { if (mInstance == null) { mInstance = new GTaskClient(); @@ -109,42 +121,50 @@ public class GTaskClient { return mInstance; } + + /*用来实现登录操作的函数,传入的参数是一个Activity + * 设置登录操作限制时间,如果超时则需要重新登录 + * 有两种登录方式,使用用户自己的URL登录或者使用谷歌官方的URL登录 + * 返回true或者false,即最后是否登陆成功 + */ public boolean login(Activity activity) { - // we suppose that the cookie would expire after 5 minutes - // then we need to re-login + //判断距离最后一次登录操作是否超过5分钟 final long interval = 1000 * 60 * 5; if (mLastLoginTime + interval < System.currentTimeMillis()) { mLoggedin = false; } - // need to re-login after account switch + // 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); + 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"; + mGetUrl = url.toString() + "ig";//设置用户对应的getUrl + mPostUrl = url.toString() + "r/ig";//设置用户对应的postUrl if (tryToLoginGtask(activity, authToken)) { mLoggedin = true; @@ -152,6 +172,7 @@ public class GTaskClient { } // try to login with google official url + //如果用户账户无法登录,则使用谷歌官方的URI进行登录 if (!mLoggedin) { mGetUrl = GTASK_GET_URL; mPostUrl = GTASK_POST_URL; @@ -164,10 +185,15 @@ public class GTaskClient { return true; } + /*具体实现登录谷歌账户的方法 + * 使用令牌机制 + * 使用AccountManager来管理注册账号 + * 返回值是账号的令牌 + */ private String loginGoogleAccount(Activity activity, boolean invalidateToken) { - String authToken; - AccountManager accountManager = AccountManager.get(activity); - Account[] accounts = accountManager.getAccountsByType("com.google"); + String authToken; //令牌,是登录操作保证安全性的一个方法 + AccountManager accountManager = AccountManager.get(activity);//AccountManager这个类给用户提供了集中注册账号的接口 + Account[] accounts = accountManager.getAccountsByType("com.google");//获取全部以com.google结尾的account if (accounts.length == 0) { Log.e(TAG, "there is no available google account"); @@ -176,6 +202,7 @@ public class GTaskClient { String accountName = NotesPreferenceActivity.getSyncAccountName(activity); Account account = null; + //遍历获得的accounts信息,寻找已经记录过的账户信息 for (Account a : accounts) { if (a.name.equals(accountName)) { account = a; @@ -190,11 +217,13 @@ public class GTaskClient { } // 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); + //如果是invalidateToken,那么需要调用invalidateAuthToken(String, String)方法废除这个无效token if (invalidateToken) { accountManager.invalidateAuthToken("com.google", authToken); loginGoogleAccount(activity, false); @@ -207,10 +236,13 @@ public class GTaskClient { return authToken; } + + //尝试登陆Gtask,这只是一个预先判断令牌是否是有效以及是否能登上GTask的方法,而不是具体实现登陆的方法 private boolean tryToLoginGtask(Activity activity, String authToken) { if (!loginGtask(authToken)) { - // maybe the auth token is out of date, now let's invalidate the + // maybe the auth token is out of authTokedate, now let's invalidate the // token and try again + //删除过一个无效的authToken,申请一个新的后再次尝试登陆 authToken = loginGoogleAccount(activity, true); if (authToken == null) { Log.e(TAG, "login google account failed"); @@ -225,25 +257,27 @@ public class GTaskClient { return true; } + //实现登录GTask的具体操作 private boolean loginGtask(String authToken) { int timeoutConnection = 10000; - int timeoutSocket = 15000; - HttpParams httpParameters = new BasicHttpParams(); - HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); - HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); + int timeoutSocket = 15000; //socket是一种通信连接实现数据的交换的端口 + HttpParams httpParameters = new BasicHttpParams(); //实例化一个新的HTTP参数类 + HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);//设置连接超时时间 + HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);//设置设置端口超时时间 mHttpClient = new DefaultHttpClient(httpParameters); - BasicCookieStore localBasicCookieStore = new BasicCookieStore(); + BasicCookieStore localBasicCookieStore = new BasicCookieStore(); //设置本地cookie mHttpClient.setCookieStore(localBasicCookieStore); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); // login gtask try { - String loginUrl = mGetUrl + "?auth=" + authToken; - HttpGet httpGet = new HttpGet(loginUrl); + String loginUrl = mGetUrl + "?auth=" + authToken; //设置登录的url + HttpGet httpGet = new HttpGet(loginUrl); //通过登录的uri实例化网页上资源的查找 HttpResponse response = null; response = mHttpClient.execute(httpGet); // get the cookie now + //获取CookieStore里存放的cookie,看如果存有“GTL(不知道什么意思)”,则说明有验证成功的有效的cookie List cookies = mHttpClient.getCookieStore().getCookies(); boolean hasAuthCookie = false; for (Cookie cookie : cookies) { @@ -256,6 +290,7 @@ public class GTaskClient { } // get the client version + //获取client的内容,具体操作是在返回的Content中截取从_setup(开始到)}中间的字符串内容,也就是gtask_url的内容 String resString = getResponseContent(response.getEntity()); String jsBegin = "_setup("; String jsEnd = ")}"; @@ -280,10 +315,24 @@ public class GTaskClient { return true; } + /*实例化创建一个用于向网络传输数据的对象 + * 使用HttpPost类 + * 返回一个httpPost实例化对象,但里面还没有内容 + */ private int getActionId() { return mActionId++; } + /*通过URL获取响应后返回的数据,也就是网络上的数据和资源 + * 使用getContentEncoding()获取网络上的资源和数据 + * 返回值就是获取到的资源 + */ + + + /*实例化创建一个用于向网络传输数据的对象 + * 使用HttpPost类 + * 返回一个httpPost实例化对象,但里面还没有内容 + */ private HttpPost createHttpPost() { HttpPost httpPost = new HttpPost(mPostUrl); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); @@ -291,6 +340,10 @@ public class GTaskClient { return httpPost; } + /*通过URL获取响应后返回的数据,也就是网络上的数据和资源 + * 使用getContentEncoding()获取网络上的资源和数据 + * 返回值就是获取到的资源 + */ private String getResponseContent(HttpEntity entity) throws IOException { String contentEncoding = null; if (entity.getContentEncoding() != null) { @@ -323,43 +376,57 @@ public class GTaskClient { } } - 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"); - } - } - + /*通过JSON发送请求 + * 请求的具体内容在json的实例化对象js中然后传入 + * 利用UrlEncodedFormEntity entity和httpPost.setEntity(entity)方法把js中的内容放置到httpPost中 + * 执行请求后使用getResponseContent方法得到返回的数据和资源 + * 将资源再次放入json后返回 + */ + private JSONObject postRequest(JSONObject js) throws NetworkFailureException { + if (!mLoggedin) {//未登录 + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + //实例化一个httpPost的对象用来向服务器传输数据,在这里就是发送请求,而请求的内容在js里 + HttpPost httpPost = createHttpPost(); + try { + LinkedList list = new LinkedList(); + list.add(new BasicNameValuePair("r", js.toString())); + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); //UrlEncodedFormEntity()的形式比较单一,是普通的键值对 + 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"); + } + } + + /*创建单个任务 + * 传入参数是一个.gtask.data.Task包里Task类的对象 + * 利用json获取Task里的内容,并且创建相应的jsPost + * 利用postRequest得到任务的返回信息 + * 使用task.setGid设置task的new_ID + */ public void createTask(Task task) throws NetworkFailureException { commitUpdate(); try { @@ -386,6 +453,9 @@ public class GTaskClient { } } + /* + * 创建一个任务列表,与createTask几乎一样,区别就是最后设置的是tasklist的gid + */ public void createTaskList(TaskList tasklist) throws NetworkFailureException { commitUpdate(); try { @@ -412,6 +482,11 @@ public class GTaskClient { } } + /* + * 同步更新操作 + * 使用JSONObject进行数据存储,使用jsPost.put,Put的信息包括UpdateArray和ClientVersion + * 使用postRequest发送这个jspost,进行处理 + */ public void commitUpdate() throws NetworkFailureException { if (mUpdateArray != null) { try { @@ -433,6 +508,10 @@ public class GTaskClient { } } + /* + * 添加更新的事项 + * 调用commitUpdate()实现 + */ public void addUpdateNode(Node node) throws NetworkFailureException { if (node != null) { // too many update items may result in an error @@ -447,6 +526,12 @@ public class GTaskClient { } } + /* + * 移动task,比如讲task移动到不同的task列表中去 + * 通过getGid获取task所属列表的gid + * 通过JSONObject.put(String name, Object value)函数设置移动后的task的相关属性值,从而达到移动的目的 + * 最后还是通过postRequest进行更新后的发送 + */ public void moveTask(Task task, TaskList preParent, TaskList curParent) throws NetworkFailureException { commitUpdate(); @@ -463,15 +548,17 @@ public class GTaskClient { if (preParent == curParent && task.getPriorSibling() != null) { // put prioring_sibing_id only if moving within the tasklist and // it is not the first one + //设置优先级ID,只有当移动是发生在文件中 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()); + 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); + //最后将ACTION_LIST加入到jsPost中 jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // client_version @@ -486,6 +573,11 @@ public class GTaskClient { } } + /* + * 删除操作节点 + * 还是利用JSON + * 删除过后使用postRequest发送删除后的结果 + */ public void deleteNode(Node node) throws NetworkFailureException { commitUpdate(); try { @@ -494,7 +586,7 @@ public class GTaskClient { // action_list node.setDeleted(true); - actionList.put(node.getUpdateAction(getActionId())); + actionList.put(node.getUpdateAction(getActionId()));//这里会获取到删除操作的ID,加入到actionLiast中 jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // client_version @@ -509,6 +601,11 @@ public class GTaskClient { } } + /* + * 获取任务列表 + * 首先通过GetURI使用getResponseContent从网上获取数据 + * 然后筛选出"_setup("到)}的部分,并且从中获取GTASK_JSON_LISTS的内容返回 + */ public JSONArray getTaskLists() throws NetworkFailureException { if (!mLoggedin) { Log.e(TAG, "please login first"); @@ -521,6 +618,7 @@ public class GTaskClient { response = mHttpClient.execute(httpGet); // get the task list + //筛选工作,把筛选出的字符串放入jsString String resString = getResponseContent(response.getEntity()); String jsBegin = "_setup("; String jsEnd = ")}"; @@ -531,6 +629,8 @@ public class GTaskClient { jsString = resString.substring(begin + jsBegin.length(), end); } JSONObject js = new JSONObject(jsString); + + //获取GTASK_JSON_LISTS return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); } catch (ClientProtocolException e) { Log.e(TAG, e.toString()); @@ -547,6 +647,9 @@ public class GTaskClient { } } + /* + * 通过传入的TASKList的gid,从网络上获取相应属于这个任务列表的任务 + */ public JSONArray getTaskList(String listGid) throws NetworkFailureException { commitUpdate(); try { @@ -558,7 +661,7 @@ public class GTaskClient { 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_LIST_ID, listGid); //这里设置为传入的listGid action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); actionList.put(action); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); @@ -579,6 +682,7 @@ public class GTaskClient { return mAccount; } + //重置更新的内容 public void resetUpdateArray() { mUpdateArray = null; } diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskManager.java b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskManager.java index d2b4082..ffb8566 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskManager.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskManager.java @@ -46,8 +46,14 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; - - +/** + * @aPackage : net.micode.notes.gtask.remote + * @aClassName: GTaskManager + * @Description: + * GTask管理者,提供同步本地和远端的任务,初始化任务列表,同步内容、文件夹,添加、更新本地和远端结点,刷新本地同步任务D等功能 + * @aAuthor: Li Qiushi + * @createdate: 12/24/2023 19:31 PM + */ public class GTaskManager { private static final String TAG = GTaskManager.class.getSimpleName(); @@ -73,49 +79,67 @@ public class GTaskManager { private boolean mCancelled; - private HashMap mGTaskListHashMap; + private HashMap mGTaskListHashMap = new HashMap<>(); - private HashMap mGTaskHashMap; + private HashMap mGTaskHashMap = new HashMap<>(); - private HashMap mMetaHashMap; + private HashMap mMetaHashMap = new HashMap<>(); - private TaskList mMetaList; + private TaskList mMetaList = null; - private HashSet mLocalDeleteIdMap; + private HashSet mLocalDeleteIdMap = new HashSet<>(); - private HashMap mGidToNid; + private HashMap mGidToNid = new HashMap<>(); - private HashMap mNidToGid; + private HashMap mNidToGid = new HashMap<>(); 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(); } - public static synchronized GTaskManager getInstance() { + /** + * 包含关键字synchronized,语言级同步,指明该函数可能运行在多线程的环境下。 + * 功能:类初始化函数 + * @return GtaskManger + */ + public static synchronized GTaskManager getInstance() {//可能运行在多线程环境下,使用语言级同步--synchronized if (mInstance == null) { mInstance = new GTaskManager(); } return mInstance; } + /** + * 包含关键字synchronized,语言级同步,指明该函数可能运行在多线程的环境下。 + * @param activity + */ public synchronized void setActivityContext(Activity activity) { - // used for getting authtoken + // used for getting auth token mActivity = activity; } - public int sync(Context context, GTaskASyncTask asyncTask) { + /** + * 核心函数 + * 功能:实现了本地同步操作和远端同步操作,用于同步Google任务列表 + * @param context-----获取上下文 + * @param asyncTask-------用于同步的异步操作类 + * @return int + */ + public int sync(Context context, GTaskASyncTask asyncTask) { //核心函数 + /*检查是否已经在进行同步操作(mSyncing为true) + 如果是,则记录一条调试日志并返回STATE_SYNC_IN_PROGRESS状态,表示同步正在进行中 + */ if (mSyncing) { Log.d(TAG, "Sync is in progress"); return STATE_SYNC_IN_PROGRESS; } + + /* + 将传入的context赋值给成员变量mContext,并获取其内容解析器(ContentResolver)赋值给成员变量mContentResolver + 将mSyncing设置为true,表示开始同步操作,将mCancelled设置为false,表示同步未被取消 + 清空所有与任务相关的数据结构(如任务列表、任务映射、元数据映射等) + */ mContext = context; mContentResolver = mContext.getContentResolver(); mSyncing = true; @@ -127,9 +151,16 @@ public class GTaskManager { mGidToNid.clear(); mNidToGid.clear(); + /** + *创建一个GTaskClient实例 + * 重置更新数组 + * 登录Google任务。如果登录失败,抛出NetworkFailureException异常 + * 从Google获取任务列表,并将其转换为本地任务列表 + * 执行内容同步工作 + */ try { - GTaskClient client = GTaskClient.getInstance(); - client.resetUpdateArray(); + GTaskClient client = GTaskClient.getInstance();//getInstance即为创建一个实例,client--客户机 + client.resetUpdateArray();//JSONArray类型,reset即置为NULL // login google task if (!mCancelled) { @@ -140,15 +171,15 @@ public class GTaskManager { // get the task list from google asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); - initGTaskList(); + initGTaskList(); //获取Google上的JSONtasklist转为本地TaskList // do content sync work asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); syncContent(); - } catch (NetworkFailureException e) { - Log.e(TAG, e.toString()); + } catch (NetworkFailureException e) { //分为两种异常,此类异常为网络异常 + Log.e(TAG, e.toString()); //创建日志文件(调试信息),error return STATE_NETWORK_ERROR; - } catch (ActionFailureException e) { + } catch (ActionFailureException e) { //此类异常为操作异常 Log.e(TAG, e.toString()); return STATE_INTERNAL_ERROR; } catch (Exception e) { @@ -164,36 +195,53 @@ public class GTaskManager { mNidToGid.clear(); mSyncing = false; } - + //根据mCancelled的值返回相应的状态(STATE_SYNC_CANCELLED表示同步已取消,STATE_SUCCESS表示同步成功) return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; } + /** + *功能:初始化GtaskList,获取Google上的JSONtasklist转为本地TaskList。 + *获得的数据存储在mMetaList,mGTaskListHashMap,mGTaskHashMap + *@exception NetworkFailureException + *@return void + */ private void initGTaskList() throws NetworkFailureException { if (mCancelled) return; + //getInstance即为创建一个实例,client应指远端客户机,用于与远程服务器进行通信 GTaskClient client = GTaskClient.getInstance(); try { - JSONArray jsTaskLists = client.getTaskLists(); + /*Json对象是Name Value对(即子元素)的无序集合,相当于一个Map对象。JsonObject类是bantouyan-json库对Json对象的抽象,提供操纵Json对象的各种方法。 + 其格式为{"key1":value1,"key2",value2....};key 必须是字符串。 + 因为ajax请求不刷新页面,但配合js可以实现局部刷新,因此json常常被用来作为异步请求的返回对象使用 + */ + JSONArray jsTaskLists = client.getTaskLists(); //通过调用client.getTaskLists()方法获取远程服务器上的任务列表,并将其存储在JSONArray对象jsTaskLists中 // init meta list first mMetaList = null; + /* + 遍历jsTaskLists中的每个元素,将其转换为JSONObject对象,并从中提取任务列表的ID和名称 + */ for (int i = 0; i < jsTaskLists.length(); i++) { - JSONObject object = jsTaskLists.getJSONObject(i); + JSONObject object = jsTaskLists.getJSONObject(i); //JSONObject与JSONArray一个为对象,一个为数组。此处取出单个JASONObject 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); + /* + 如果任务列表的名称以特定的前缀开头且不等于元数据文件夹的前缀,则创建一个新的TaskList对象,并将其添加到本地的任务列表映射中 + 同时,加载该任务列表的元数据,并将其添加到元数据列表映射中 + */ + if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { + mMetaList = new TaskList(); //MetaList意为元表,Tasklist类型,此处为初始化 + mMetaList.setContentByRemoteJSON(object); //将JSON中部分数据复制到自己定义的对象中相对应的数据:name->mname... // 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 metaData = new MetaData(); //继承自Node metaData.setContentByRemoteJSON(object); - if (metaData.isWorthSaving()) { + if (metaData.isWorthSaving()) { //if not worth to save,metadata将不加入mMetaList mMetaList.addChildTask(metaData); if (metaData.getGid() != null) { mMetaHashMap.put(metaData.getRelatedGid(), metaData); @@ -203,7 +251,10 @@ public class GTaskManager { } } - // create meta list if not existed + /* + 如果本地没有元数据列表,则创建一个新的元数据列表,并将其设置为默认名称 + 然后,使用GTaskClient.getInstance().createTaskList(mMetaList)方法将元数据列表上传到远程服务器 + */ if (mMetaList == null) { mMetaList = new TaskList(); mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX @@ -211,16 +262,22 @@ public class GTaskManager { GTaskClient.getInstance().createTaskList(mMetaList); } - // init task list + /* + 最后,再次遍历jsTaskLists中的每个元素,将其转换为JSONObject对象,并从中提取任务列表的ID和名称 + */ for (int i = 0; i < jsTaskLists.length(); i++) { JSONObject object = jsTaskLists.getJSONObject(i); - String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); //通过getString函数传入本地某个标志数据的名称,获取其在远端的名称。 String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); + /* + 如果任务列表的名称以特定的前缀开头且不等于元数据文件夹的前缀,则创建一个新的TaskList对象,并将其添加到本地的任务列表映射中 + 同时,加载该任务列表的任务,并将其添加到任务列表映射中 + */ if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META)) { - TaskList tasklist = new TaskList(); + + GTaskStringUtils.FOLDER_META)) { + TaskList tasklist = new TaskList(); //继承自Node tasklist.setContentByRemoteJSON(object); mGTaskListHashMap.put(gid, tasklist); mGTaskHashMap.put(gid, tasklist); @@ -240,26 +297,40 @@ public class GTaskManager { } } } + } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); throw new ActionFailureException("initGTaskList: handing JSONObject failed"); + /* + 如果在处理过程中发生任何JSONException异常,将记录错误日志并抛出一个ActionFailureException异常 + */ } } - private void syncContent() throws NetworkFailureException { + /** + * 功能:本地内容同步操作 + * @throws NetworkFailureException + * @return 无返回值 + */ + private void syncContent() throws NetworkFailureException { //本地内容同步操作 int syncType; - Cursor c = null; - String gid; - Node node; + Cursor c = null; //数据库指针 + String gid; //GoogleID + Node node; //Node包含Sync_Action的不同类型 - mLocalDeleteIdMap.clear(); + mLocalDeleteIdMap.clear(); //HashSet类型 if (mCancelled) { return; } - // for local deleted note + /* + 查询本地已删除的笔记(即类型不是系统类型且父ID是垃圾文件夹的笔记),并将查询结果存储在游标c中 + 遍历游标,获取每个笔记的Google ID(gid)和对应的节点(node) + 如果节点不为空,则从mGTaskHashMap中移除该节点,并调用doContentSync()方法进行同步操作 + 同时,将该笔记的ID添加到mLocalDeleteIdMap中 + */ try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(type<>? AND parent_id=?)", new String[] { @@ -286,10 +357,15 @@ public class GTaskManager { } } - // sync folder first + //同步文件夹 syncFolder(); - // for note existing in database + /* + 查询数据库中存在的笔记(即类型是系统类型且父ID不是垃圾文件夹的笔记),并将查询结果存储在游标c中 + 遍历游标,获取每个笔记的Google ID(gid)和对应的节点(node) + 如果节点不为空,则从mGTaskHashMap中移除该节点,并通过hashmap建立联系 + 然后根据节点的同步操作类型(syncType),调用doContentSync()方法进行同步操作 + */ try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(type=? AND parent_id<>?)", new String[] { @@ -301,8 +377,8 @@ public class GTaskManager { 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); + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); //通过hashmap建立联系 + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); //通过hashmap建立联系 syncType = node.getSyncAction(c); } else { if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { @@ -327,23 +403,25 @@ public class GTaskManager { } // go through remaining items - Iterator> iter = mGTaskHashMap.entrySet().iterator(); + Iterator> iter = mGTaskHashMap.entrySet().iterator(); //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 + /*如果mCancelled为假,首先调用DataUtils.batchDeleteNotes()方法批量删除本地已删除的笔记 + 若删除失败,则抛出ActionFailureException异常 + */ if (!mCancelled) { if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { throw new ActionFailureException("failed to batch-delete local deleted notes"); } } - // refresh local sync id + /* + 用于提交更新并且刷新本地同步ID + */ if (!mCancelled) { GTaskClient.getInstance().commitUpdate(); refreshLocalSyncId(); @@ -351,6 +429,14 @@ public class GTaskManager { } + /** + * 功能: + * 同步文件夹 + * 先查询根文件夹、电话记录文件夹和本地存在的文件夹,然后根据查询结果执行相应的同步操作 + * 最后,会遍历远程添加的文件夹,并将它们添加到本地 + * 在整个过程中,如果遇到网络故障,会抛出NetworkFailureException异常 + * @throws NetworkFailureException + */ private void syncFolder() throws NetworkFailureException { Cursor c = null; String gid; @@ -394,7 +480,7 @@ public class GTaskManager { try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", new String[] { - String.valueOf(Notes.ID_CALL_RECORD_FOLDER) + String.valueOf(Notes.ID_CALL_RECORD_FOLDER) }, null); if (c != null) { if (c.moveToNext()) { @@ -476,6 +562,14 @@ public class GTaskManager { GTaskClient.getInstance().commitUpdate(); } + /** + * 功能: + * 根据传入的同步类型(syncType)对节点(Node)进行相应的操作 + * @param syncType + * @param node + * @param c + * @throws NetworkFailureException + */ private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -522,6 +616,14 @@ public class GTaskManager { } } + /** + * 功能:将一个本地节点(Node)添加到数据库中 + * 首先检查是否已经取消操作,如果是,则直接返回 + * 否则,根据节点的类型(TaskList或其他类型),创建一个新的SqlNote对象,并设置其内容和父ID + * 接下来,将新创建的SqlNote对象提交到数据库中,并更新gid-nid映射以及元数据。 + * @param node + * @throws NetworkFailureException + */ private void addLocalNode(Node node) throws NetworkFailureException { if (mCancelled) { return; @@ -596,6 +698,14 @@ public class GTaskManager { updateRemoteMeta(node.getGid(), sqlNote); } + /** + * 功能:update本地node + * @param node + * ----同步操作的基础数据类型 + * @param c + * ----Cursor + * @throws NetworkFailureException + */ private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -619,12 +729,21 @@ public class GTaskManager { updateRemoteMeta(node.getGid(), sqlNote); } + /** + * 功能:远程增加Node + * 需要updateRemoteMeta + * @param node + * ----同步操作的基础数据类型 + * @param c + * --Cursor + * @throws NetworkFailureException + */ private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; } - SqlNote sqlNote = new SqlNote(mContext, c); + SqlNote sqlNote = new SqlNote(mContext, c); //从本地mContext中获取内容 Node n; // update remotely @@ -634,11 +753,12 @@ public class GTaskManager { String parentGid = mNidToGid.get(sqlNote.getParentId()); if (parentGid == null) { - Log.e(TAG, "cannot find task's parent tasklist"); + Log.e(TAG, "cannot find task's parent tasklist"); //调试信息 throw new ActionFailureException("cannot add remote task"); } - mGTaskListHashMap.get(parentGid).addChildTask(task); + mGTaskListHashMap.get(parentGid).addChildTask(task); //在本地生成的GTaskList中增加子结点 + //登录远程服务器,创建Task GTaskClient.getInstance().createTask(task); n = (Node) task; @@ -656,6 +776,7 @@ public class GTaskManager { else folderName += sqlNote.getSnippet(); + //iterator迭代器,通过统一的接口迭代所有的map元素 Iterator> iter = mGTaskListHashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = iter.next(); @@ -687,11 +808,19 @@ public class GTaskManager { sqlNote.resetLocalModified(); sqlNote.commit(true); - // gid-id mapping + // gid-id mapping //创建id间的映射 mGidToNid.put(n.getGid(), sqlNote.getId()); mNidToGid.put(sqlNote.getId(), n.getGid()); } + /** + * 功能:更新远端的Node,包含meta更新(updateRemoteMeta) + * @param node + * ----同步操作的基础数据类型 + * @param c + * --Cursor + * @throws NetworkFailureException + */ private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -701,7 +830,7 @@ public class GTaskManager { // update remotely node.setContentByLocalJSON(sqlNote.getContent()); - GTaskClient.getInstance().addUpdateNode(node); + GTaskClient.getInstance().addUpdateNode(node); //GTaskClient用途为从本地登陆远端服务器 // update meta updateRemoteMeta(node.getGid(), sqlNote); @@ -710,14 +839,17 @@ public class GTaskManager { if (sqlNote.isNoteType()) { Task task = (Task) node; TaskList preParentList = task.getParent(); + //preParentList为通过node获取的父节点列表 String curParentGid = mNidToGid.get(sqlNote.getParentId()); + //curParentGid为通过光标在数据库中找到sqlNote的mParentId,再通过mNidToGid由long类型转为String类型的Gid + if (curParentGid == null) { Log.e(TAG, "cannot find task's parent tasklist"); throw new ActionFailureException("cannot update remote task"); } TaskList curParentList = mGTaskListHashMap.get(curParentGid); - + //通过HashMap找到对应Gid的TaskList if (preParentList != curParentList) { preParentList.removeChildTask(task); curParentList.addChildTask(task); @@ -725,11 +857,19 @@ public class GTaskManager { } } - // clear local modified flag sqlNote.resetLocalModified(); + //commit到本地数据库 sqlNote.commit(true); } + /** + * 功能:升级远程meta。 meta---元数据----计算机文件系统管理数据---管理数据的数据。 + * @param gid + * ---GoogleID为String类型 + * @param sqlNote + * ---同步前的数据库操作,故使用类SqlNote + * @throws NetworkFailureException + */ private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { if (sqlNote != null && sqlNote.isNoteType()) { MetaData metaData = mMetaHashMap.get(gid); @@ -746,12 +886,17 @@ public class GTaskManager { } } + /** + * 功能:刷新本地,给sync的ID对应上最后更改过的对象 + * @return void + * @throws NetworkFailureException + */ private void refreshLocalSyncId() throws NetworkFailureException { if (mCancelled) { return; } - // get the latest gtask list + //获取最近的(最晚的)gtask list mGTaskHashMap.clear(); mGTaskListHashMap.clear(); mMetaHashMap.clear(); @@ -762,16 +907,16 @@ public class GTaskManager { 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"); + }, NoteColumns.TYPE + " DESC"); //query语句:五个参数,NoteColumns.TYPE + " DESC"-----为按类型递减顺序返回查询结果。new String[] {String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)}------为选择参数。"(type<>? AND parent_id<>?)"-------指明返回行过滤器。SqlNote.PROJECTION_NOTE--------应返回的数据列的名字。Notes.CONTENT_NOTE_URI--------contentProvider包含所有数据集所对应的uri 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(); + ContentValues values = new ContentValues(); //在ContentValues中创建键值对。准备通过contentResolver写入数据 values.put(NoteColumns.SYNC_ID, node.getLastModified()); - mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, + mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, //进行批量更改,选择参数为NULL,应该可以用insert替换,参数分别为表名和需要更新的value对象。 c.getLong(SqlNote.ID_COLUMN)), values, null, null); } else { Log.e(TAG, "something is missed"); @@ -790,10 +935,18 @@ public class GTaskManager { } } + /** + * 功能:获取同步账号,mAccount.name + * @return String + */ public String getSyncAccount() { return GTaskClient.getInstance().getSyncAccount().name; } + /** + * 功能:取消同步,置mCancelled为true + * @author TTS + */ public void cancelSync() { mCancelled = true; } diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskSyncService.java b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskSyncService.java index cca36f7..b210494 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskSyncService.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/gtask/remote/GTaskSyncService.java @@ -22,7 +22,16 @@ import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; - +/** + * @aPackage : net.micode.notes.gtask.remote + * @aClassName: GTaskSyncService + * @Description: + * 该类继承了Service父类,Service是在一段不定的时间运行在后台,不和用户交互的应用组件 + * 作用: + * GTask同步服务,用于提供同步服务(开始、取消同步),发送广播 + * @aAuthor: Li Qiushi + * @createdate: 12/24/2023 20:15 PM + */ public class GTaskSyncService extends Service { public final static String ACTION_STRING_NAME = "sync_action_type"; @@ -42,20 +51,28 @@ public class GTaskSyncService extends Service { private static String mSyncProgress = ""; + /** + *功能:用于自动一个同步任务 + */ private void startSync() { + /* + 如果mSyncTask为null,则创建一个新的GTaskASyncTask对象,并将其赋值给mSyncTask + 这个新对象的构造函数接受两个参数:当前对象(this)和一个Lambda表达式 + */ if (mSyncTask == null) { - mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { - public void onComplete() { - mSyncTask = null; - sendBroadcast(""); - stopSelf(); - } + mSyncTask = new GTaskASyncTask(this, () -> { + mSyncTask = null; + sendBroadcast(""); + stopSelf(); }); sendBroadcast(""); mSyncTask.execute(); } } + /** + * 功能:取消同步任务,以避免不必要的资源占用和潜在的错误 + */ private void cancelSync() { if (mSyncTask != null) { mSyncTask.cancelSync(); @@ -67,11 +84,20 @@ public class GTaskSyncService extends Service { mSyncTask = null; } + /** + * 功能: + * 用于处理启动服务时的命令 + * @param intent + * @param flags + * @param startId + * @return int + */ @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; @@ -86,6 +112,9 @@ public class GTaskSyncService extends Service { return super.onStartCommand(intent, flags, startId); } + /** + * 功能:用于处理低内存情况,当系统内存不足时,该方法会被调用 + */ @Override public void onLowMemory() { if (mSyncTask != null) { @@ -97,24 +126,36 @@ public class GTaskSyncService extends Service { 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); + sendBroadcast(intent);//将intent对象发送出去,以便其他组件或服务可以接收到这个广播消息并进行相应的处理 } + /** + * 功能:启动一个名为GTaskSyncService的服务来进行同步操作 + * @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.startService(intent);//启动GTaskSyncService服务,之后服务就会开始执行同步操作 } + /** + * 功能:取消正在进行的同步操作 + * @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); + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);//向Intent对象添加额外的数据 context.startService(intent); } diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/tool/DataUtils.java b/src/xiaomi/Notes-master/src/net/micode/notes/tool/DataUtils.java index 2a14982..ab329c2 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/tool/DataUtils.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/tool/DataUtils.java @@ -59,7 +59,7 @@ public class DataUtils { } try { ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); - if (results == null || results.length == 0 || results[0] == null) { + if (results.length == 0 || results[0] == null) { Log.d(TAG, "delete notes failed, ids:" + ids.toString()); return false; } @@ -98,7 +98,7 @@ public class DataUtils { try { ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); - if (results == null || results.length == 0 || results[0] == null) { + if (results.length == 0 || results[0] == null) { Log.d(TAG, "delete notes failed, ids:" + ids.toString()); return false; } @@ -122,15 +122,13 @@ public class DataUtils { null); int count = 0; - if(cursor != null) { - if(cursor.moveToFirst()) { - try { - count = cursor.getInt(0); - } catch (IndexOutOfBoundsException e) { - Log.e(TAG, "get folder count failed:" + e.toString()); - } finally { - cursor.close(); - } + if(cursor != null && cursor.moveToFirst()) { + try { + count = cursor.getInt(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "get folder count failed:" + e.toString()); + } finally { + cursor.close(); } } return count; diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/ui/NoteEditActivity.java b/src/xiaomi/Notes-master/src/net/micode/notes/ui/NoteEditActivity.java index 96a9ff8..30a803f 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/ui/NoteEditActivity.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/ui/NoteEditActivity.java @@ -507,48 +507,38 @@ public class NoteEditActivity extends Activity implements OnClickListener, @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; + int itemId = item.getItemId(); + if (itemId == R.id.menu_new_note) { + createNewNote(); + } else if (itemId == 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(); + } else if (itemId == R.id.menu_font_size) { + mFontSizeSelector.setVisibility(View.VISIBLE); + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); + } else if (itemId == R.id.menu_list_mode) { + mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ? + TextNote.MODE_CHECK_LIST : 0); + } else if (itemId == R.id.menu_share) { + getWorkingText(); + sendTo(this, mWorkingNote.getContent()); + } else if (itemId == R.id.menu_send_to_desktop) { + sendToDesktop(); + } else if (itemId == R.id.menu_alert) { + setReminder(); + } else if (itemId == R.id.menu_delete_remind) { + mWorkingNote.setAlertDate(0, false); } return true; } @@ -576,35 +566,47 @@ public class NoteEditActivity extends Activity implements OnClickListener, 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); + //将运行便签的id添加到INTENT_EXTRA_FOLDER_ID标记中 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(); + //如果不是头文件夹建立一个hash表把便签id存起来 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"); } } } + //将这些标签的删除标记置为true mWorkingNote.markDeleted(true); } diff --git a/src/xiaomi/Notes-master/src/net/micode/notes/ui/NotesListActivity.java b/src/xiaomi/Notes-master/src/net/micode/notes/ui/NotesListActivity.java index e843aec..eed884c 100644 --- a/src/xiaomi/Notes-master/src/net/micode/notes/ui/NotesListActivity.java +++ b/src/xiaomi/Notes-master/src/net/micode/notes/ui/NotesListActivity.java @@ -319,28 +319,26 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt return true; } - switch (item.getItemId()) { - case R.id.delete: - AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.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_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: - startQueryDestinationFolders(); - break; - default: - return false; + int itemId = item.getItemId(); + if (itemId == R.id.delete) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.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_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(); + } else if (itemId == R.id.move) { + startQueryDestinationFolders(); + } else { + return false; } return true; } @@ -558,12 +556,8 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } public void onClick(View v) { - switch (v.getId()) { - case R.id.btn_new_note: - createNewNote(); - break; - default: - break; + if (v.getId() == R.id.btn_new_note) { + createNewNote(); } } @@ -578,7 +572,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt 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); @@ -624,7 +617,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt values.put(NoteColumns.LOCAL_MODIFIED, 1); mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + "=?", new String[] { - String.valueOf(mFocusNoteDataItem.getId()) + String.valueOf(mFocusNoteDataItem.getId()) }); } } else if (!TextUtils.isEmpty(name)) { @@ -637,6 +630,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } }); + if (TextUtils.isEmpty(etName.getText())) { positive.setEnabled(false); } @@ -780,40 +774,27 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt @Override public boolean onOptionsItemSelected(MenuItem item) { - 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))) { - GTaskSyncService.startSync(this); - } else { - GTaskSyncService.cancelSync(this); - } + int itemId = item.getItemId(); + if (itemId == R.id.menu_new_folder) { + showCreateOrModifyFolderDialog(true); + } else if (itemId == R.id.menu_export_text) { + exportNoteToText(); + } else if (itemId == R.id.menu_sync) { + if (isSyncMode()) { + if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { + GTaskSyncService.startSync(this); } else { - startPreferenceActivity(); + GTaskSyncService.cancelSync(this); } - break; - } - case R.id.menu_setting: { + } else { startPreferenceActivity(); - break; - } - case R.id.menu_new_note: { - createNewNote(); - break; } - case R.id.menu_search: - onSearchRequested(); - break; - default: - break; + } else if (itemId == R.id.menu_setting) { + startPreferenceActivity(); + } else if (itemId == R.id.menu_new_note) { + createNewNote(); + } else if (itemId == R.id.menu_search) { + onSearchRequested(); } return true; }